Storing citation text in a hidden object

This commit is contained in:
Artur
2025-11-25 10:37:04 +03:00
parent 209c0bf2b3
commit 059d3d5024
5 changed files with 92 additions and 45 deletions

View File

@ -246,8 +246,7 @@
<input type="file" id="cslFileInput" accept=".csl,.xml" style="display: none;" />
</div>
<div id="div_temp" class="hidden"></div>
</div>
<script src="scripts/zotero/zotero-environment.js"></script>
<script src="scripts/zotero/zotero-api-checker.js"></script>

View File

@ -127,7 +127,7 @@ CitationDocService.prototype.addCitation = function (text, value) {
/**
* @returns {Promise<Array<CustomField>>}
*/
CitationDocService.prototype.getAllAddinFields = function () {
CitationDocService.prototype._getAllAddinFields = function () {
const self = this;
return new Promise(function (resolve, reject) {
window.Asc.plugin.executeMethod("GetAllAddinFields", null, resolve);
@ -137,10 +137,10 @@ CitationDocService.prototype.getAllAddinFields = function () {
/**
* @returns {Promise<Array<CustomField>>}
*/
CitationDocService.prototype._getAddinZoteroFields = function () {
CitationDocService.prototype.getAddinZoteroFields = function () {
const self = this;
return new Promise(function (resolve, reject) {
self.getAllAddinFields().then(function (arrFields) {
self._getAllAddinFields().then(function (arrFields) {
try {
if (arrFields.length) {
arrFields = arrFields.filter(function (field) {
@ -233,7 +233,7 @@ CitationDocService.prototype._removeSuperSubTagsWithPositions = function (
*/
CitationDocService.prototype.saveAsText = function () {
// TODO потом добавить ещё форматы, пока только как текст
return this._getAddinZoteroFields().then(function (arrFields) {
return this.getAddinZoteroFields().then(function (arrFields) {
let count = arrFields.length;
if (!count) {
window.Asc.plugin.executeCommand("close", "");

View File

@ -18,6 +18,7 @@
/// <reference path="./zotero/zotero.js" />
/// <reference path="./csl/citation/citation.js" />
/// <reference path="./csl/citation/storage.js" />
/// <reference path="./csl/styles/styles-manager.js" />
(function () {
@ -39,8 +40,7 @@
let bibPlaceholder = "Please insert some citation into the document.";
var bUserItemsUpdated = false;
var bGroupsItemsUpdated = false;
// TODO добавить варианты сохранения для совместимости с другими редакторами
// (ms, libre, google, мой офис), пока есть вариант сохранить как текст
// TODO добавить ещё обработку событий (удаление линков) их не нужно удалять
// из библиографии автоматически (это делать только при обновлении библиографии
// или refresh), но их точно нужно удалить из formatter!
@ -218,7 +218,6 @@
const option = elements.locatorLabelsList.querySelector('[data-value="'+id+'"]');
option && option.setAttribute("selected", "");
const name = option.textContent;
console.log(id);
locatorLabel.value = option.textContent;
locatorLabel.setAttribute("data-value", id);
locatorLabel.setAttribute("title", name);
@ -1259,10 +1258,10 @@
/**
* @param {boolean} bUpadteAll
* @param {boolean} bPastBib
* @param {boolean} bSyncronize
* @param {boolean} bSynchronize
* @returns {Promise<void>}
*/
function updateAllOrAddBib(bUpadteAll, bPastBib, bSyncronize) {
function updateAllOrAddBib(bUpadteAll, bPastBib, bSynchronize) {
if (!selectedStyle) {
showError(getMessage("Style is not selected"));
return;
@ -1271,7 +1270,7 @@
showError(getMessage("Language is not selected"));
return;
}
return citationDocService.getAllAddinFields().then(function(arrFields) {
return citationDocService.getAddinZoteroFields().then(function(arrFields) {
if (!arrFields.length) {
showLoader(false);
return;
@ -1279,6 +1278,10 @@
var updatedFields = [];
var bibField = null;
var bibFieldValue = ' ';
const fragment = document.createDocumentFragment();
const tempElement = document.createElement("div");
fragment.appendChild(tempElement);
try {
var bibItems = new Array(CSLCitationStorage.size);
@ -1302,13 +1305,13 @@
}
bibItems[citationIndex] = bibText;
}
elements.tempDiv.innerHTML = bibItems.join('');
tempElement.innerHTML = bibItems.join('');
} catch (e) {
if (
false === cslStylesManager.isLastUsedStyleContainBibliography()
) {
// style does not describe the bibliography
elements.tempDiv.textContent = "";
tempElement.textContent = "";
} else {
console.error(e);
showError(getMessage("Failed to apply this style."));
@ -1317,7 +1320,7 @@
}
}
var bibliography = elements.tempDiv.innerText;
var bibliography = tempElement.innerText;
arrFields.forEach(function(field) {
var citationObject;
var citationStartIndex = field.Value.indexOf("{");
@ -1337,9 +1340,9 @@
cslCitation = new CSLCitation(keysL.length, citationID);
cslCitation.fillFromObject(citationObject);
keysL = cslCitation.getInfoForCitationCluster();
elements.tempDiv.innerHTML = formatter.makeCitationCluster(keysL);
field["Content"] = elements.tempDiv.innerText;
if (bSyncronize && cslCitation) {
tempElement.innerHTML = formatter.makeCitationCluster(keysL);
field["Content"] = tempElement.innerText;
if (bSynchronize && cslCitation) {
// if we make synchronization we must update value too
field["Value"] = citPrefixNew + ' ' + citSuffixNew + JSON.stringify(cslCitation.toJSON());
}
@ -1377,12 +1380,12 @@
});
};
function updateFormatter(bUpadteAll, bPastBib, bPastLink, bSyncronize) {
function updateFormatter(bUpadteAll, bPastBib, bPastLink, bSynchronize) {
// looks like a crutch
clearTimeout(repeatTimeout);
if (loadingStyle || loadingLocale || !cslStylesManager.cached(selectedStyle) || !locales[selectedLocale]) {
repeatTimeout = setTimeout( function() {
updateFormatter(bUpadteAll, bPastBib, bPastLink, bSyncronize);
updateFormatter(bUpadteAll, bPastBib, bPastLink, bSynchronize);
}, 100);
return;
}
@ -1415,7 +1418,7 @@
let promises = [];
if (bUpadteAll) {
promises.push(updateAllOrAddBib(bUpadteAll, bPastBib, bSyncronize));
promises.push(updateAllOrAddBib(bUpadteAll, bPastBib, bSynchronize));
}
if (bPastLink) {
promises.push(insertSelectedCitations());
@ -1437,7 +1440,7 @@
function updateCslItems(bUpdadeFormatter, bUpadteAll, bPastBib, bPastLink) {
CSLCitationStorage.clear();
return citationDocService.getAllAddinFields().then(function(arrFields) {
return citationDocService.getAddinZoteroFields().then(function(arrFields) {
if (arrFields.length) {
var numOfItems = 0;
var bibField = null;
@ -1574,12 +1577,16 @@
keys.forEach(function(key) {
removeSelected(key);
})
});
const fragment = document.createDocumentFragment();
const tempElement = document.createElement("div");
fragment.appendChild(tempElement);
// TODO может ещё очистить поиск (подумать над этим)
elements.tempDiv.innerHTML = formatter.makeCitationCluster(keysL);
tempElement.innerHTML = formatter.makeCitationCluster(keysL);
cslCitation.addPlainCitation(tempElement.innerText);
return citationDocService.addCitation(
elements.tempDiv.innerText,
tempElement.innerText,
JSON.stringify(cslCitation.toJSON())
).then(function() {
showLoader(false);

View File

@ -39,7 +39,8 @@ function CSLCitation(itemsStartIndex, citationID) {
this._itemsStartIndex = itemsStartIndex;
/** @type {Array<CitationItem>} */
this._citationItems = new Array();
this._properties = new Object();
/** @type {Object<string, string>} */
this._properties = {};
this._schema =
"https://raw.githubusercontent.com/citation-style-language/schema/master/schemas/input/csl-citation.json";
@ -203,19 +204,14 @@ CSLCitation.prototype.getInfoForCitationCluster = function () {
};
/**
* @param {string} key
* @returns
* @returns {string}
*/
CSLCitation.prototype.getProperty = function (key) {
let items = this._citationItems;
for (var i = 0; i < items.length; i++) {
let itemData = items[i].getItemData();
if (itemData.getCustomProperty(key) !== null) {
return itemData.getCustomProperty(key);
}
CSLCitation.prototype.getPlainCitation = function () {
if (Object.hasOwnProperty.call(this._properties, "plainCitation")) {
return this._properties.plainCitation;
}
return null;
return "";
};
/**
@ -235,11 +231,25 @@ CSLCitation.prototype._addCitationItem = function (item) {
};
/**
* @param {object} properties
* @param {string} plainCitation
* @returns
*/
CSLCitation.prototype.addPlainCitation = function (plainCitation) {
this._setProperties({ plainCitation: plainCitation });
return this;
};
/**
* @param {Object<string, string>} properties
* @returns
*/
CSLCitation.prototype._setProperties = function (properties) {
this._properties = properties;
const self = this;
Object.keys(properties).forEach(function (key) {
if (Object.hasOwnProperty.call(properties, key)) {
self._properties[key] = properties[key];
}
}, this);
return this;
};

View File

@ -1,16 +1,28 @@
var CSLCitationStorage = {
/** @type {Array<CSLCitationItem>} */
// @ts-check
/// <reference path="./citation-item.js" />
const CSLCitationStorage = {
/** @type {Array<CitationItem>} */
_items: [],
/** @type {Array<string>} */
_ids: [],
size: 0,
/** @returns {CSLCitationItem} */
/** @returns {CitationItem} */
/**
* @param {string|number} id
* @returns {CitationItem|null}
**/
get: function (id) {
id = id.toString();
var id = this._ids.indexOf(id);
if (id >= 0) return this._items[id];
const index = this._ids.indexOf(id);
if (index >= 0) return this._items[index];
return null;
},
/**
*
* @param {string|number} id
* @returns {number}
*/
getIndex: function (id) {
id = id.toString();
return this._ids.indexOf(id);
@ -19,7 +31,12 @@ var CSLCitationStorage = {
this._items = [];
this._ids = [];
this.size = 0;
return this;
},
/**
* @param {string|number} id
* @returns {CSLCitationStorage}
*/
delete: function (id) {
id = id.toString();
const index = this._ids.indexOf(id);
@ -28,25 +45,39 @@ var CSLCitationStorage = {
this._ids.splice(index, 1);
this.size--;
}
return this;
},
/**
* @param {function(CitationItem, string, CSLCitationStorage?)} callback
*/
forEach: function (callback) {
for (var i = 0; i < this.size; i++) {
callback(this._items[i], this._ids[i], this);
}
},
/**
* @param {string|number} id
* @returns {boolean}
*/
has: function (id) {
id = id.toString();
return this._ids.indexOf(id) >= 0;
},
/**
* @param {string|number} id
* @param {CitationItem} item
* @returns {CSLCitationStorage}
*/
set: function (id, item) {
id = id.toString();
var index = this._ids.indexOf(id);
const index = this._ids.indexOf(id);
if (index >= 0) {
this._items[index] = item;
return;
return this;
}
this._items.push(item);
this._ids.push(id);
this.size++;
return this;
},
};