2019-08-02 10:09:36 +00:00
|
|
|
/*
|
|
|
|
***** BEGIN LICENSE BLOCK *****
|
|
|
|
|
|
|
|
Copyright © 2011 Center for History and New Media
|
|
|
|
George Mason University, Fairfax, Virginia, USA
|
|
|
|
http://zotero.org
|
|
|
|
|
|
|
|
This file is part of Zotero.
|
|
|
|
|
|
|
|
Zotero is free software: you can redistribute it and/or modify
|
|
|
|
it under the terms of the GNU Affero General Public License as published by
|
|
|
|
the Free Software Foundation, either version 3 of the License, or
|
|
|
|
(at your option) any later version.
|
|
|
|
|
|
|
|
Zotero is distributed in the hope that it will be useful,
|
|
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
GNU Affero General Public License for more details.
|
|
|
|
|
|
|
|
You should have received a copy of the GNU Affero General Public License
|
|
|
|
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
***** END LICENSE BLOCK *****
|
|
|
|
*/
|
|
|
|
|
2022-06-08 22:16:50 +00:00
|
|
|
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
|
|
|
|
var { E10SUtils } = ChromeUtils.import("resource://gre/modules/E10SUtils.jsm");
|
2022-07-19 20:26:17 +00:00
|
|
|
var { Subprocess } = ChromeUtils.import("resource://gre/modules/Subprocess.jsm");
|
2023-04-14 15:37:07 +00:00
|
|
|
var { RemoteTranslate } = ChromeUtils.import("chrome://zotero/content/RemoteTranslate.jsm");
|
|
|
|
var { ContentDOMReference } = ChromeUtils.import("resource://gre/modules/ContentDOMReference.jsm");
|
2022-06-08 22:16:50 +00:00
|
|
|
|
2021-09-09 09:17:35 +00:00
|
|
|
import FilePicker from 'zotero/modules/filePicker';
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
var Zotero = Components.classes["@zotero.org/Zotero;1"]
|
|
|
|
// Currently uses only nsISupports
|
|
|
|
//.getService(Components.interfaces.chnmIZoteroService).
|
|
|
|
.getService(Components.interfaces.nsISupports)
|
|
|
|
.wrappedJSObject;
|
|
|
|
|
|
|
|
// Fix JSON stringify 2028/2029 "bug"
|
|
|
|
// Borrowed from http://stackoverflow.com/questions/16686687/json-stringify-and-u2028-u2029-check
|
|
|
|
if (JSON.stringify(["\u2028\u2029"]) !== '["\\u2028\\u2029"]') {
|
|
|
|
JSON.stringify = function (stringify) {
|
|
|
|
return function () {
|
|
|
|
var str = stringify.apply(this, arguments);
|
|
|
|
if (str && str.indexOf('\u2028') != -1) str = str.replace(/\u2028/g, '\\u2028');
|
|
|
|
if (str && str.indexOf('\u2029') != -1) str = str.replace(/\u2029/g, '\\u2029');
|
|
|
|
return str;
|
|
|
|
};
|
|
|
|
}(JSON.stringify);
|
|
|
|
}
|
|
|
|
|
|
|
|
// To be used elsewhere (e.g. varDump)
|
|
|
|
function fix2028(str) {
|
|
|
|
if (str.indexOf('\u2028') != -1) str = str.replace(/\u2028/g, '\\u2028');
|
|
|
|
if (str.indexOf('\u2029') != -1) str = str.replace(/\u2029/g, '\\u2029');
|
|
|
|
return str;
|
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
var Scaffold = new function () {
|
2022-06-08 22:16:50 +00:00
|
|
|
var _browser, _frames = [], _document;
|
2019-08-02 10:09:36 +00:00
|
|
|
var _translatorsLoadedPromise;
|
2021-12-29 01:32:56 +00:00
|
|
|
var _translatorProvider = null;
|
|
|
|
var _lastModifiedTime = 0;
|
2022-11-01 20:36:44 +00:00
|
|
|
var _needRebuildTranslatorSuggestions = true;
|
2022-06-08 22:16:50 +00:00
|
|
|
|
|
|
|
this.browser = () => _browser;
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
var _editors = {};
|
|
|
|
|
|
|
|
var _propertyMap = {
|
2021-12-29 01:32:56 +00:00
|
|
|
'textbox-translatorID': 'translatorID',
|
|
|
|
'textbox-label': 'label',
|
|
|
|
'textbox-creator': 'creator',
|
|
|
|
'textbox-target': 'target',
|
|
|
|
'textbox-minVersion': 'minVersion',
|
|
|
|
'textbox-priority': 'priority',
|
|
|
|
'textbox-target-all': 'targetAll',
|
|
|
|
'textbox-hidden-prefs': 'hiddenPrefs'
|
2019-08-02 10:09:36 +00:00
|
|
|
};
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
var _linesOfMetadata = 15;
|
|
|
|
|
2019-08-24 08:25:51 +00:00
|
|
|
this.onLoad = async function (e) {
|
2021-12-29 01:32:56 +00:00
|
|
|
if (e.target !== document) return;
|
2019-08-02 10:09:36 +00:00
|
|
|
_document = document;
|
2021-12-29 01:32:56 +00:00
|
|
|
|
2022-04-05 21:48:32 +00:00
|
|
|
if (!Zotero.isMac) {
|
|
|
|
// Hack to fix Windows/Linux toolbar
|
2021-12-29 01:32:56 +00:00
|
|
|
let toolbar = document.getElementById('zotero-toolbar');
|
2022-04-05 21:48:32 +00:00
|
|
|
toolbar.className = 'toolbar-scaffold-small';
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
_browser = document.getElementById('browser');
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2022-06-08 22:16:50 +00:00
|
|
|
window.messageManager.addMessageListener('Scaffold:Load', ({ data }) => {
|
|
|
|
document.getElementById("browser-url").value = data.url;
|
|
|
|
});
|
|
|
|
|
|
|
|
window.messageManager.loadFrameScript('chrome://scaffold/content/content.js', true);
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
let browserUrl = document.getElementById("browser-url");
|
2022-06-08 22:16:50 +00:00
|
|
|
browserUrl.addEventListener('keydown', function (e) {
|
|
|
|
if (e.key == 'Enter') {
|
|
|
|
Zotero.debug('Scaffold: Loading URL in browser: ' + browserUrl.value);
|
|
|
|
_browser.loadURI(browserUrl.value, {
|
|
|
|
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()
|
|
|
|
});
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
});
|
2022-06-08 22:16:50 +00:00
|
|
|
|
|
|
|
document.getElementById('tabpanels').addEventListener('select', event => Scaffold.handleTabSelect(event));
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2023-06-24 22:00:57 +00:00
|
|
|
let lastTranslatorID = Zotero.Prefs.get('scaffold.lastTranslatorID');
|
|
|
|
if (lastTranslatorID) {
|
|
|
|
document.getElementById("textbox-translatorID").value = lastTranslatorID;
|
|
|
|
document.getElementById("textbox-label").value = 'Loading…';
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
this.generateTranslatorID();
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
// Add List fields help menu entries for all other item types
|
|
|
|
var types = Zotero.ItemTypes.getAll().map(t => t.name).sort();
|
|
|
|
var morePopup = document.getElementById('mb-help-fields-more-popup');
|
|
|
|
var primaryTypes = ['book', 'bookSection', 'conferencePaper', 'journalArticle', 'magazineArticle', 'newspaperArticle'];
|
|
|
|
for (let type of types) {
|
|
|
|
if (primaryTypes.includes(type)) continue;
|
2022-06-29 14:16:49 +00:00
|
|
|
var menuitem = document.createXULElement('menuitem');
|
2019-08-02 10:09:36 +00:00
|
|
|
menuitem.setAttribute('label', type);
|
2021-12-29 01:32:56 +00:00
|
|
|
menuitem.addEventListener('command', () => {
|
|
|
|
Scaffold.addTemplate('templateNewItem', type);
|
|
|
|
});
|
2019-08-02 10:09:36 +00:00
|
|
|
morePopup.appendChild(menuitem);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!Scaffold_Translators.getDirectory()) {
|
2019-08-24 08:25:51 +00:00
|
|
|
if (!await this.promptForTranslatorsDirectory()) {
|
2019-08-02 10:09:36 +00:00
|
|
|
window.close();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
var importWin = document.getElementById("editor-import").contentWindow;
|
|
|
|
var codeWin = document.getElementById("editor-code").contentWindow;
|
|
|
|
var testsWin = document.getElementById("editor-tests").contentWindow;
|
2022-06-28 19:05:11 +00:00
|
|
|
|
|
|
|
await Promise.all([
|
|
|
|
importWin.loadMonaco({ language: 'plaintext' }).then(({ monaco, editor }) => {
|
|
|
|
_editors.importGlobal = monaco;
|
|
|
|
_editors.import = editor;
|
|
|
|
}),
|
|
|
|
codeWin.loadMonaco({ language: 'javascript' }).then(({ monaco, editor }) => {
|
|
|
|
_editors.codeGlobal = monaco;
|
|
|
|
_editors.code = editor;
|
|
|
|
}),
|
|
|
|
testsWin.loadMonaco({ language: 'json' }).then(({ monaco, editor }) => {
|
|
|
|
_editors.testsGlobal = monaco;
|
|
|
|
_editors.tests = editor;
|
|
|
|
}),
|
|
|
|
]);
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
this.initImportEditor();
|
|
|
|
this.initCodeEditor();
|
|
|
|
this.initTestsEditor();
|
|
|
|
|
2022-05-10 16:09:25 +00:00
|
|
|
// Set font size from general pref
|
|
|
|
Zotero.setFontSize(document.getElementById('scaffold-pane'));
|
|
|
|
|
|
|
|
// Set font size of code editor
|
|
|
|
var size = Zotero.Prefs.get("scaffold.fontSize");
|
|
|
|
if (size) {
|
|
|
|
this.setFontSize(size);
|
|
|
|
}
|
|
|
|
|
2022-04-08 02:50:00 +00:00
|
|
|
// Listen for Scaffold coming to the foreground and reload translators
|
|
|
|
window.addEventListener('activate', () => this.reloadTranslators());
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
Scaffold_Translators.setLoadListener({
|
|
|
|
onLoadBegin: () => {
|
|
|
|
document.getElementById('cmd_load').setAttribute('disabled', true);
|
|
|
|
},
|
|
|
|
|
|
|
|
onLoadComplete: () => {
|
|
|
|
document.getElementById('cmd_load').removeAttribute('disabled');
|
2022-11-01 20:36:44 +00:00
|
|
|
_needRebuildTranslatorSuggestions = true;
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
});
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
_translatorsLoadedPromise = Scaffold_Translators.load();
|
|
|
|
_translatorProvider = Scaffold_Translators.getProvider();
|
2023-06-24 22:00:57 +00:00
|
|
|
|
|
|
|
if (lastTranslatorID) {
|
|
|
|
this.load(lastTranslatorID).then((success) => {
|
|
|
|
if (!success) {
|
|
|
|
Zotero.Prefs.clear('scaffold.lastTranslatorID');
|
|
|
|
this.newTranslator(true);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
};
|
|
|
|
|
2019-08-24 08:25:51 +00:00
|
|
|
this.promptForTranslatorsDirectory = async function () {
|
2019-08-02 10:09:36 +00:00
|
|
|
var ps = Services.prompt;
|
|
|
|
var buttonFlags = ps.BUTTON_POS_0 * ps.BUTTON_TITLE_IS_STRING
|
|
|
|
+ ps.BUTTON_POS_1 * ps.BUTTON_TITLE_IS_STRING
|
|
|
|
+ ps.BUTTON_POS_2 * ps.BUTTON_TITLE_IS_STRING;
|
|
|
|
var index = ps.confirmEx(null,
|
|
|
|
"Scaffold",
|
|
|
|
"To set up Scaffold, select your development directory for Zotero translators.\n\n"
|
2019-08-05 09:15:58 +00:00
|
|
|
+ "In most cases, this should be a git clone of the zotero/translators GitHub repository.",
|
2019-08-02 10:09:36 +00:00
|
|
|
buttonFlags,
|
|
|
|
"Choose Directory…",
|
|
|
|
Zotero.getString('general.cancel'),
|
|
|
|
"Open GitHub Repo", null, {}
|
|
|
|
);
|
|
|
|
// Revert to home directory
|
|
|
|
if (index == 0) {
|
2019-08-24 08:25:51 +00:00
|
|
|
let dir = await this.setTranslatorsDirectory();
|
2019-08-02 10:09:36 +00:00
|
|
|
if (dir) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else if (index == 2) {
|
|
|
|
Zotero.launchURL('https://github.com/zotero/translators');
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
2019-08-24 08:25:51 +00:00
|
|
|
this.setTranslatorsDirectory = async function () {
|
|
|
|
var fp = new FilePicker();
|
2019-08-02 10:09:36 +00:00
|
|
|
var oldPath = Zotero.Prefs.get('scaffold.translatorsDir');
|
|
|
|
if (oldPath) {
|
2019-08-24 08:25:51 +00:00
|
|
|
fp.displayDirectory = oldPath;
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
fp.init(
|
|
|
|
window,
|
|
|
|
"Select Translators Directory",
|
2019-08-24 08:25:51 +00:00
|
|
|
fp.modeGetFolder
|
2019-08-02 10:09:36 +00:00
|
|
|
);
|
2019-08-24 08:25:51 +00:00
|
|
|
fp.appendFilters(fp.filterAll);
|
|
|
|
if (await fp.show() != fp.returnOK) {
|
2019-08-02 10:09:36 +00:00
|
|
|
return false;
|
|
|
|
}
|
2019-08-24 08:25:51 +00:00
|
|
|
var path = OS.Path.normalize(fp.file);
|
2019-08-02 10:09:36 +00:00
|
|
|
if (oldPath == path) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
Zotero.Prefs.set('scaffold.translatorsDir', path);
|
|
|
|
Scaffold_Translators.load(true); // async
|
|
|
|
return path;
|
|
|
|
};
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
this.reloadTranslators = async function () {
|
|
|
|
Zotero.debug('Reloading translators quietly');
|
|
|
|
let { numLoaded, numDeleted } = await Scaffold_Translators.load(true);
|
|
|
|
if (numLoaded) {
|
|
|
|
_logOutput(`${numLoaded} ${Zotero.Utilities.pluralize(numLoaded, 'translator')} updated.`);
|
|
|
|
}
|
|
|
|
if (numDeleted) {
|
|
|
|
_logOutput(`${numDeleted} ${Zotero.Utilities.pluralize(numDeleted, 'translator')} deleted.`);
|
|
|
|
}
|
|
|
|
|
|
|
|
let translatorID = document.getElementById('textbox-translatorID').value;
|
|
|
|
let modifiedTime = Scaffold_Translators.getModifiedTime(translatorID);
|
|
|
|
if (modifiedTime && modifiedTime > _lastModifiedTime) {
|
|
|
|
let ps = Services.prompt;
|
|
|
|
let buttonFlags = ps.BUTTON_POS_0 * ps.BUTTON_TITLE_IS_STRING
|
|
|
|
+ ps.BUTTON_POS_1 * ps.BUTTON_TITLE_IS_STRING;
|
|
|
|
var index = ps.confirmEx(null,
|
|
|
|
"Scaffold",
|
|
|
|
"Translator code changed externally. Discard unsaved changes and reload?",
|
|
|
|
buttonFlags,
|
|
|
|
Zotero.getString('general.no'),
|
|
|
|
Zotero.getString('general.yes'),
|
|
|
|
null, null, {}
|
|
|
|
);
|
|
|
|
if (index == 1) {
|
2023-01-23 17:32:30 +00:00
|
|
|
await this.load(translatorID);
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
_lastModifiedTime = modifiedTime;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
this.initImportEditor = function () {
|
|
|
|
let monaco = _editors.importGlobal, editor = _editors.import;
|
2022-06-28 19:05:11 +00:00
|
|
|
// Nothing to do here
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
this.initCodeEditor = async function () {
|
|
|
|
let monaco = _editors.codeGlobal, editor = _editors.code;
|
2022-09-12 21:06:17 +00:00
|
|
|
|
|
|
|
// For some reason, even if we explicitly re-set the default model's language to JavaScript,
|
|
|
|
// Monaco still treats it as TypeScript. Recreating the model manually fixes the issue.
|
|
|
|
editor.setModel(monaco.editor.createModel('', 'javascript', monaco.Uri.parse('inmemory:///translator.js')));
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
editor.updateOptions({
|
|
|
|
lineNumbers: num => num + _linesOfMetadata - 1,
|
|
|
|
});
|
|
|
|
|
|
|
|
monaco.languages.registerCodeLensProvider('javascript', this.createRunCodeLensProvider(monaco, editor));
|
|
|
|
monaco.languages.registerHoverProvider('javascript', this.createHoverProvider(monaco, editor));
|
2022-11-01 20:36:44 +00:00
|
|
|
monaco.languages.registerCompletionItemProvider('javascript', this.createCompletionProvider(monaco, editor));
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
let tsLib = await Zotero.File.getContentsAsync(
|
|
|
|
OS.Path.join(Scaffold_Translators.getDirectory(), 'index.d.ts'));
|
|
|
|
let tsLibPath = 'ts:filename/index.d.ts';
|
|
|
|
monaco.languages.typescript.javascriptDefaults.addExtraLib(tsLib, tsLibPath);
|
|
|
|
// this would allow peeking:
|
|
|
|
// monaco.editor.createModel(tsLib, 'typescript', monaco.Uri.parse(tsLibPath));
|
|
|
|
// but it doesn't currently seem to work
|
|
|
|
};
|
|
|
|
|
|
|
|
this.initTestsEditor = function () {
|
|
|
|
let monaco = _editors.testsGlobal, editor = _editors.tests;
|
|
|
|
|
|
|
|
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
|
|
|
|
validate: true,
|
|
|
|
allowComments: false,
|
|
|
|
trailingCommas: false,
|
|
|
|
schemaValidation: 'error'
|
|
|
|
});
|
|
|
|
|
|
|
|
editor.getModel().updateOptions({
|
|
|
|
insertSpaces: false
|
|
|
|
});
|
|
|
|
|
|
|
|
editor.getModel().onDidChangeContent((_) => {
|
|
|
|
this.populateTests();
|
|
|
|
});
|
|
|
|
|
|
|
|
editor.updateOptions({
|
|
|
|
links: false
|
|
|
|
});
|
|
|
|
|
|
|
|
monaco.languages.registerCodeLensProvider('json', this.createTestCodeLensProvider(monaco, editor));
|
|
|
|
};
|
|
|
|
|
|
|
|
this.createRunCodeLensProvider = function (monaco, editor) {
|
|
|
|
let runMethod = editor.addCommand(0, (_ctx, method) => this.run(method), '');
|
|
|
|
|
|
|
|
return {
|
|
|
|
provideCodeLenses: (model, _token) => {
|
|
|
|
let methodRe = '(async\\s+)?\\bfunction\\s+(detect|do)(Web|Import|Export|Search)\\s*\\(';
|
|
|
|
let lenses = [];
|
|
|
|
|
|
|
|
let matches = model.findMatches(
|
|
|
|
methodRe,
|
|
|
|
/* searchOnlyEditableRange: */ false,
|
|
|
|
/* isRegex: */ true,
|
|
|
|
/* matchCase: */ true,
|
|
|
|
/* wordSeparators: */ null,
|
|
|
|
/* captureMatches: */ true
|
|
|
|
);
|
|
|
|
|
|
|
|
for (let match of matches) {
|
|
|
|
let line = match.matches[0];
|
|
|
|
let methodName = line.match(/function\s+(\w*)/)[1];
|
|
|
|
lenses.push({
|
|
|
|
range: match.range,
|
|
|
|
command: {
|
|
|
|
id: runMethod,
|
|
|
|
title: `Run ${methodName}`,
|
|
|
|
arguments: [methodName]
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-06-08 22:38:59 +00:00
|
|
|
return { lenses, dispose() {} };
|
2021-12-29 01:32:56 +00:00
|
|
|
},
|
|
|
|
resolveCodeLens: (_model, codeLens, _token) => codeLens
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
this.createHoverProvider = function (monaco, _editor) {
|
|
|
|
let uuidRe = `(["'])([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\\1`;
|
|
|
|
let types = Zotero.ItemTypes.getTypes().map(t => t.name);
|
|
|
|
let itemTypeRe = `(["'])(${types.join('|')})\\1`;
|
|
|
|
|
|
|
|
return {
|
|
|
|
provideHover: (model, position) => {
|
|
|
|
let lineRange = new monaco.Range(
|
|
|
|
position.lineNumber,
|
|
|
|
model.getLineMinColumn(position.lineNumber),
|
|
|
|
position.lineNumber,
|
|
|
|
model.getLineMaxColumn(position.lineNumber)
|
|
|
|
);
|
|
|
|
|
|
|
|
let matches = model.findMatches(
|
|
|
|
uuidRe,
|
|
|
|
/* searchScope: */ lineRange,
|
|
|
|
/* isRegex: */ true,
|
|
|
|
/* matchCase: */ true,
|
|
|
|
/* wordSeparators: */ null,
|
|
|
|
/* captureMatches: */ true
|
|
|
|
);
|
|
|
|
|
|
|
|
for (let uuidMatch of matches) {
|
|
|
|
if (!uuidMatch.range.containsPosition(position)) continue;
|
|
|
|
let translator = _translatorProvider.get(uuidMatch.matches[2]);
|
|
|
|
|
|
|
|
if (translator) {
|
|
|
|
let metadataJSON = JSON.stringify(translator.metadata, null, '\t');
|
|
|
|
|
|
|
|
return {
|
|
|
|
range: uuidMatch.range,
|
|
|
|
contents: [
|
|
|
|
{ value: `**${translator.label}**` },
|
|
|
|
{ value: '```json\n' + metadataJSON + '\n```' }
|
|
|
|
]
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
matches = model.findMatches(
|
|
|
|
itemTypeRe,
|
|
|
|
/* searchScope: */ lineRange,
|
|
|
|
/* isRegex: */ true,
|
|
|
|
/* matchCase: */ true,
|
|
|
|
/* wordSeparators: */ null,
|
|
|
|
/* captureMatches: */ true
|
|
|
|
);
|
|
|
|
|
|
|
|
for (let itemTypeMatch of matches) {
|
|
|
|
if (!itemTypeMatch.range.containsPosition(position)) continue;
|
|
|
|
|
|
|
|
let fieldsJSON = this.listFieldsForItemType(itemTypeMatch.matches[2]);
|
|
|
|
return {
|
|
|
|
range: itemTypeMatch.range,
|
|
|
|
contents: [
|
|
|
|
{ value: '```json\n' + fieldsJSON + '\n```' }
|
|
|
|
]
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
this.createTestCodeLensProvider = function (monaco, editor) {
|
|
|
|
let runTestsCommand = editor.addCommand(
|
|
|
|
0,
|
|
|
|
(_ctx, testIndices) => {
|
|
|
|
let tests;
|
|
|
|
try {
|
|
|
|
tests = JSON.parse(editor.getValue());
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
_logOutput('Error parsing tests:\n' + e);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (testIndices) {
|
|
|
|
tests = testIndices.map(index => tests[index]);
|
|
|
|
}
|
|
|
|
|
|
|
|
this.runTests(tests);
|
|
|
|
},
|
|
|
|
'');
|
|
|
|
|
|
|
|
let updateTestsCommand = editor.addCommand(
|
|
|
|
0,
|
|
|
|
async (_ctx, testIndices) => {
|
|
|
|
testIndices = testIndices || Object.keys(allTests);
|
|
|
|
|
|
|
|
try {
|
|
|
|
var allTests = JSON.parse(editor.getValue());
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
_logOutput('Error parsing tests:\n' + e);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let tests = testIndices.map(index => allTests[index]);
|
|
|
|
|
|
|
|
await this.updateTests(tests,
|
|
|
|
(newTest) => {
|
|
|
|
allTests[testIndices.shift()] = newTest;
|
|
|
|
});
|
|
|
|
|
|
|
|
_writeTestsToPane(allTests);
|
|
|
|
},
|
|
|
|
'');
|
|
|
|
|
|
|
|
return {
|
|
|
|
provideCodeLenses: (model, _token) => {
|
|
|
|
let lenses = [];
|
|
|
|
|
|
|
|
let firstChar = {
|
|
|
|
startLineNumber: 1,
|
|
|
|
startColumn: 1,
|
|
|
|
endLineNumber: 1,
|
|
|
|
endColumn: 1
|
|
|
|
};
|
|
|
|
lenses.push({
|
|
|
|
range: firstChar,
|
|
|
|
command: {
|
|
|
|
id: runTestsCommand,
|
|
|
|
title: 'Run All'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
lenses.push({
|
|
|
|
range: firstChar,
|
|
|
|
command: {
|
|
|
|
id: updateTestsCommand,
|
|
|
|
title: 'Run and Update All'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
for (let [testIndex, range] of _findTestObjectTops(monaco, model).entries()) {
|
|
|
|
lenses.push({
|
|
|
|
range: range,
|
|
|
|
command: {
|
|
|
|
id: runTestsCommand,
|
|
|
|
title: 'Run',
|
|
|
|
arguments: [[testIndex]]
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
lenses.push({
|
|
|
|
range: range,
|
|
|
|
command: {
|
|
|
|
id: updateTestsCommand,
|
|
|
|
title: 'Run and Update',
|
|
|
|
arguments: [[testIndex]]
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-06-08 22:38:59 +00:00
|
|
|
return { lenses, dispose() {} };
|
2021-12-29 01:32:56 +00:00
|
|
|
},
|
|
|
|
resolveCodeLens: (_model, codeLens, _token) => codeLens
|
|
|
|
};
|
|
|
|
};
|
2022-11-01 20:36:44 +00:00
|
|
|
|
|
|
|
this.createCompletionProvider = function (monaco, editor) {
|
|
|
|
let suggestions = null;
|
|
|
|
return {
|
|
|
|
provideCompletionItems(model, position) {
|
|
|
|
let prefixText = model.getValueInRange({
|
|
|
|
startLineNumber: position.lineNumber,
|
|
|
|
startColumn: 1,
|
|
|
|
endLineNumber: position.lineNumber,
|
|
|
|
endColumn: position.column
|
|
|
|
});
|
|
|
|
if (/setTranslator\([^)]*$/.test(prefixText)) {
|
|
|
|
let word = model.getWordUntilPosition(position);
|
|
|
|
let range = {
|
|
|
|
startLineNumber: position.lineNumber,
|
|
|
|
endLineNumber: position.lineNumber,
|
|
|
|
startColumn: word.startColumn,
|
|
|
|
endColumn: word.endColumn
|
|
|
|
};
|
|
|
|
if (!suggestions || _needRebuildTranslatorSuggestions) {
|
|
|
|
// Cache the suggestions minus the range field
|
|
|
|
suggestions = [...Scaffold_Translators._translators.entries()].map(([id, meta]) => {
|
|
|
|
return {
|
|
|
|
label: `${meta.translator.label}: '${id}'`,
|
|
|
|
kind: monaco.languages.CompletionItemKind.Constant,
|
|
|
|
insertText: `'${id}'`
|
|
|
|
};
|
|
|
|
});
|
|
|
|
_needRebuildTranslatorSuggestions = false;
|
|
|
|
}
|
|
|
|
// Add the range to each suggestion before returning
|
|
|
|
return { suggestions: suggestions.map(s => ({ ...s, range })) };
|
|
|
|
}
|
|
|
|
return { suggestions: [] };
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
this.updateModelMarkers = function (translatorPath) {
|
|
|
|
runESLint(translatorPath)
|
|
|
|
.then(eslintOutputToModelMarkers)
|
|
|
|
.then(markers => _editors.codeGlobal.editor.setModelMarkers(_editors.code.getModel(), 'eslint', markers));
|
|
|
|
};
|
|
|
|
|
|
|
|
this.setFontSize = function (size) {
|
2019-08-02 10:09:36 +00:00
|
|
|
var sizeWithPX = size + 'px';
|
2021-12-29 01:32:56 +00:00
|
|
|
_editors.import.updateOptions({ fontSize: size + 1 }); // editor font needs to be a little bigger
|
|
|
|
_editors.code.updateOptions({ fontSize: size + 1 });
|
|
|
|
_editors.tests.updateOptions({ fontSize: size + 1 });
|
2019-08-02 10:09:36 +00:00
|
|
|
document.getElementById("scaffold-pane").style.fontSize = sizeWithPX;
|
2021-12-29 01:32:56 +00:00
|
|
|
if (size == 11) {
|
2019-08-02 10:09:36 +00:00
|
|
|
// for the default value 11, clear the prefs
|
|
|
|
Zotero.Prefs.clear('scaffold.fontSize');
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
else {
|
2019-08-02 10:09:36 +00:00
|
|
|
Zotero.Prefs.set("scaffold.fontSize", size);
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
this.increaseFontSize = function () {
|
2019-08-02 10:09:36 +00:00
|
|
|
var currentSize = Zotero.Prefs.get("scaffold.fontSize") || 11;
|
2021-12-29 01:32:56 +00:00
|
|
|
this.setFontSize(currentSize + 2);
|
|
|
|
};
|
|
|
|
this.decreaseFontSize = function () {
|
2019-08-02 10:09:36 +00:00
|
|
|
var currentSize = Zotero.Prefs.get("scaffold.fontSize") || 11;
|
2021-12-29 01:32:56 +00:00
|
|
|
this.setFontSize(currentSize - 2);
|
|
|
|
};
|
|
|
|
|
2023-07-31 13:44:20 +00:00
|
|
|
this.newTranslator = async function (skipSavePrompt) {
|
|
|
|
if (!skipSavePrompt && _editors.code.getValue()) {
|
|
|
|
let ps = Services.prompt;
|
|
|
|
let buttonFlags = ps.BUTTON_POS_0 * ps.BUTTON_TITLE_IS_STRING
|
|
|
|
+ ps.BUTTON_POS_1 * ps.BUTTON_TITLE_IS_STRING;
|
|
|
|
let label = document.getElementById('textbox-label').value;
|
|
|
|
let index = ps.confirmEx(null,
|
|
|
|
"Scaffold",
|
|
|
|
`Do you want to save the changes you made to ${label}?`,
|
|
|
|
buttonFlags,
|
|
|
|
Zotero.getString('general.no'),
|
|
|
|
Zotero.getString('general.yes'),
|
|
|
|
null, null, {}
|
|
|
|
);
|
|
|
|
if (index == 1 && !await this.save()) {
|
|
|
|
return;
|
|
|
|
}
|
2023-06-24 22:00:57 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
this.generateTranslatorID();
|
|
|
|
document.getElementById('textbox-label').value = 'Untitled';
|
|
|
|
document.getElementById('textbox-creator').value
|
|
|
|
= document.getElementById('textbox-target').value
|
|
|
|
= document.getElementById('textbox-target-all').value
|
|
|
|
= document.getElementById('textbox-configOptions').value
|
|
|
|
= document.getElementById('textbox-displayOptions').value
|
|
|
|
= document.getElementById('textbox-hidden-prefs').value
|
|
|
|
= '';
|
|
|
|
document.getElementById('textbox-minVersion').value = '5.0';
|
|
|
|
document.getElementById('textbox-priority').value = '100';
|
|
|
|
document.getElementById('checkbox-import').checked = false;
|
|
|
|
document.getElementById('checkbox-export').checked = false;
|
|
|
|
document.getElementById('checkbox-web').checked = true;
|
|
|
|
document.getElementById('checkbox-search').checked = false;
|
|
|
|
|
|
|
|
_editors.code.setValue('');
|
|
|
|
_editors.tests.setValue('');
|
|
|
|
|
|
|
|
this.populateTests();
|
|
|
|
|
|
|
|
document.getElementById('textbox-label').focus();
|
|
|
|
_showTab('metadata');
|
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* load translator
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.load = async function (translatorID) {
|
|
|
|
await _translatorsLoadedPromise;
|
|
|
|
|
2023-06-24 22:00:57 +00:00
|
|
|
var translator;
|
2019-08-02 10:09:36 +00:00
|
|
|
if (translatorID === undefined) {
|
|
|
|
var io = {};
|
|
|
|
io.translatorProvider = _translatorProvider;
|
2022-06-08 22:16:50 +00:00
|
|
|
io.url = io.rootUrl = _browser.currentURI.spec;
|
|
|
|
window.openDialog("chrome://scaffold/content/load.xhtml",
|
2021-12-29 01:32:56 +00:00
|
|
|
"_blank", "chrome,modal", io);
|
2019-08-02 10:09:36 +00:00
|
|
|
translator = io.dataOut;
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
else {
|
2019-08-02 10:09:36 +00:00
|
|
|
translator = _translatorProvider.get(translatorID);
|
|
|
|
}
|
|
|
|
|
|
|
|
// No translator was selected in the dialog.
|
2023-06-24 22:00:57 +00:00
|
|
|
if (!translator) return false;
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
for (var id in _propertyMap) {
|
2019-08-02 10:09:36 +00:00
|
|
|
document.getElementById(id).value = translator[_propertyMap[id]] || "";
|
|
|
|
}
|
|
|
|
|
|
|
|
//Strip JSON metadata
|
2021-12-29 01:32:56 +00:00
|
|
|
var code = await _translatorProvider.getCodeForTranslator(translator);
|
2019-08-02 10:09:36 +00:00
|
|
|
var lastUpdatedIndex = code.indexOf('"lastUpdated"');
|
|
|
|
var header = code.substr(0, lastUpdatedIndex + 50);
|
|
|
|
var m = /^\s*{[\S\s]*?}\s*?[\r\n]+/.exec(header);
|
2021-12-29 01:32:56 +00:00
|
|
|
var fixedCode = code.substr(m[0].length);
|
2019-08-02 10:09:36 +00:00
|
|
|
// adjust the first line number when there are an unusual number of metadata lines
|
2021-12-29 01:32:56 +00:00
|
|
|
_linesOfMetadata = m[0].split('\n').length;
|
|
|
|
// load tests into test editing pane
|
|
|
|
_loadTestsFromTranslator(fixedCode);
|
|
|
|
// clear selection
|
|
|
|
_editors.tests.setSelection({
|
|
|
|
startLineNumber: 1,
|
|
|
|
endLineNumber: 1,
|
|
|
|
startColumn: 1,
|
|
|
|
endColumn: 1
|
|
|
|
});
|
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
// Set up the test running pane
|
|
|
|
this.populateTests();
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
// remove tests from the translator code before loading into the code editor
|
|
|
|
var testStart = fixedCode.indexOf("/** BEGIN TEST CASES **/");
|
|
|
|
var testEnd = fixedCode.indexOf("/** END TEST CASES **/");
|
|
|
|
if (testStart !== -1 && testEnd !== -1) fixedCode = fixedCode.substr(0, testStart) + fixedCode.substr(testEnd + 23);
|
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
// Convert whitespace to tabs
|
2021-12-29 01:32:56 +00:00
|
|
|
_editors.code.setValue(normalizeWhitespace(fixedCode));
|
2019-08-02 10:09:36 +00:00
|
|
|
// Then go to line 1
|
2021-12-29 01:32:56 +00:00
|
|
|
_editors.code.setPosition({ lineNumber: 1, column: 1 });
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
// Reset configOptions and displayOptions before loading
|
|
|
|
document.getElementById('textbox-configOptions').value = '';
|
|
|
|
document.getElementById('textbox-displayOptions').value = '';
|
|
|
|
|
|
|
|
if (translator.configOptions) {
|
|
|
|
let configOptions = JSON.stringify(translator.configOptions);
|
|
|
|
if (configOptions != '{}') {
|
|
|
|
document.getElementById('textbox-configOptions').value = configOptions;
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
if (translator.displayOptions) {
|
|
|
|
let displayOptions = JSON.stringify(translator.displayOptions);
|
|
|
|
if (displayOptions != '{}') {
|
|
|
|
document.getElementById('textbox-displayOptions').value = displayOptions;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// get translator type; might as well have some fun here
|
|
|
|
var type = translator.translatorType;
|
|
|
|
var types = ["import", "export", "web", "search"];
|
2021-12-29 01:32:56 +00:00
|
|
|
for (var i = 2; i <= 16; i *= 2) {
|
2019-08-02 10:09:36 +00:00
|
|
|
var mod = type % i;
|
2021-12-29 01:32:56 +00:00
|
|
|
document.getElementById('checkbox-' + types.shift()).checked = !!mod;
|
|
|
|
if (mod) type -= mod;
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
this.updateModelMarkers(translator.path);
|
|
|
|
_lastModifiedTime = new Date().getTime();
|
2023-06-24 22:00:57 +00:00
|
|
|
|
|
|
|
Zotero.Prefs.set('scaffold.lastTranslatorID', translator.translatorID);
|
|
|
|
|
|
|
|
return true;
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
function _getMetadataObject() {
|
|
|
|
var metadata = {
|
|
|
|
translatorID: document.getElementById('textbox-translatorID').value,
|
|
|
|
label: document.getElementById('textbox-label').value,
|
|
|
|
creator: document.getElementById('textbox-creator').value,
|
|
|
|
target: document.getElementById('textbox-target').value,
|
|
|
|
minVersion: document.getElementById('textbox-minVersion').value,
|
2021-12-29 01:32:56 +00:00
|
|
|
maxVersion: '',
|
2019-08-02 10:09:36 +00:00
|
|
|
priority: parseInt(document.getElementById('textbox-priority').value)
|
|
|
|
};
|
|
|
|
|
|
|
|
// optional (hidden) metadata
|
|
|
|
if (document.getElementById('textbox-target-all').value) {
|
|
|
|
metadata.targetAll = document.getElementById('textbox-target-all').value;
|
|
|
|
}
|
|
|
|
if (document.getElementById('textbox-hidden-prefs').value) {
|
|
|
|
metadata.hiddenPrefs = document.getElementById('textbox-hidden-prefs').value;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (document.getElementById('textbox-configOptions').value) {
|
2021-12-29 01:32:56 +00:00
|
|
|
metadata.configOptions = JSON.parse(document.getElementById('textbox-configOptions').value);
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
if (document.getElementById('textbox-displayOptions').value) {
|
2021-12-29 01:32:56 +00:00
|
|
|
metadata.displayOptions = JSON.parse(document.getElementById('textbox-displayOptions').value);
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// no option for this
|
|
|
|
metadata.inRepository = true;
|
|
|
|
|
|
|
|
metadata.translatorType = 0;
|
2021-12-29 01:32:56 +00:00
|
|
|
if (document.getElementById('checkbox-import').checked) {
|
2019-08-02 10:09:36 +00:00
|
|
|
metadata.translatorType += 1;
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
if (document.getElementById('checkbox-export').checked) {
|
2019-08-02 10:09:36 +00:00
|
|
|
metadata.translatorType += 2;
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
if (document.getElementById('checkbox-web').checked) {
|
2019-08-02 10:09:36 +00:00
|
|
|
metadata.translatorType += 4;
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
if (document.getElementById('checkbox-search').checked) {
|
2019-08-02 10:09:36 +00:00
|
|
|
metadata.translatorType += 8;
|
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (document.getElementById('checkbox-web').checked) {
|
|
|
|
// save browserSupport only for web tranlsators
|
|
|
|
metadata.browserSupport = "gcsibv";
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
var date = new Date();
|
|
|
|
metadata.lastUpdated = date.getUTCFullYear()
|
2021-12-29 01:32:56 +00:00
|
|
|
+ "-" + Zotero.Utilities.lpad(date.getUTCMonth() + 1, '0', 2)
|
|
|
|
+ "-" + Zotero.Utilities.lpad(date.getUTCDate(), '0', 2)
|
|
|
|
+ " " + Zotero.Utilities.lpad(date.getUTCHours(), '0', 2)
|
|
|
|
+ ":" + Zotero.Utilities.lpad(date.getUTCMinutes(), '0', 2)
|
|
|
|
+ ":" + Zotero.Utilities.lpad(date.getUTCSeconds(), '0', 2);
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
return metadata;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* save translator to database
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.save = async function (updateZotero) {
|
|
|
|
var code = _editors.code.getValue();
|
|
|
|
var tests = _editors.tests.getValue().trim();
|
|
|
|
if (!tests || tests == '[]') tests = '[\n]'; // eslint wants a line break between the brackets
|
|
|
|
|
|
|
|
code += '/** BEGIN TEST CASES **/\nvar testCases = ' + tests + '\n/** END TEST CASES **/';
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
var metadata = _getMetadataObject();
|
|
|
|
if (metadata.label === "Untitled") {
|
|
|
|
_logOutput("Can't save an untitled translator.");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
var path = await _translatorProvider.save(metadata, code);
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
if (updateZotero) {
|
2021-12-29 01:32:56 +00:00
|
|
|
await Zotero.Translators.save(metadata, code);
|
|
|
|
await Zotero.Translators.reinit();
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
_lastModifiedTime = new Date().getTime();
|
|
|
|
|
|
|
|
this.updateModelMarkers(path);
|
2023-01-23 17:32:30 +00:00
|
|
|
await this.reloadTranslators();
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* If an editor is focused, trigger `editorTrigger` in it.
|
|
|
|
* Otherwise, run `fallbackCommand`.
|
|
|
|
*/
|
|
|
|
this.trigger = function (editorTrigger, fallbackCommand) {
|
|
|
|
let activeEditor = _editors[_getActiveEditorName()];
|
|
|
|
if (activeEditor) {
|
|
|
|
activeEditor.trigger('Scaffold.trigger', editorTrigger);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
// editMenuOverlay.js
|
|
|
|
goDoCommand(fallbackCommand);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-12-24 07:46:19 +00:00
|
|
|
this.handleTabSelect = function (event) {
|
2022-06-08 22:16:50 +00:00
|
|
|
if (event.target.tagName != 'tabpanels') {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-12-24 07:46:19 +00:00
|
|
|
// Focus editor when switching to tab
|
2022-06-08 22:16:50 +00:00
|
|
|
var tab = document.getElementById('tabs').selectedItem.id.match(/^tab-(.+)$/)[1];
|
2020-12-24 07:46:19 +00:00
|
|
|
switch (tab) {
|
|
|
|
case 'import':
|
|
|
|
case 'code':
|
|
|
|
case 'tests':
|
2021-12-29 01:32:56 +00:00
|
|
|
// the select event's default behavior is to focus the selected tab.
|
|
|
|
// we don't want to prevent *all* of the event's default behavior,
|
|
|
|
// but we do want to focus the editor instead of the tab.
|
|
|
|
// so this stupid hack waits 10 ms for event processing to finish
|
|
|
|
// before focusing the editor.
|
|
|
|
setTimeout(() => {
|
|
|
|
document.getElementById(`editor-${tab}`).focus();
|
|
|
|
_editors[tab].focus();
|
|
|
|
}, 10);
|
2020-12-24 07:46:19 +00:00
|
|
|
break;
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
let codeTabBroadcaster = document.getElementById('code-tab-only');
|
|
|
|
if (tab == 'code') {
|
|
|
|
codeTabBroadcaster.removeAttribute('disabled');
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
codeTabBroadcaster.setAttribute('disabled', true);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
this.handleTestSelect = function (event) {
|
|
|
|
let selected = event.target.selectedItems[0];
|
|
|
|
if (!selected) return;
|
|
|
|
|
|
|
|
let editImport = document.getElementById('testing_editImport');
|
|
|
|
let openURL = document.getElementById('testing_openURL');
|
2022-06-08 22:16:50 +00:00
|
|
|
if (selected.dataset.testType == 'web') {
|
2021-12-29 01:32:56 +00:00
|
|
|
editImport.setAttribute('disabled', true);
|
|
|
|
openURL.removeAttribute('disabled');
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
editImport.removeAttribute('disabled');
|
|
|
|
openURL.setAttribute('disabled', true);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
this.listFieldsForItemType = function (itemType) {
|
|
|
|
var outputObject = {};
|
|
|
|
outputObject.itemType = Zotero.ItemTypes.getName(itemType);
|
|
|
|
var typeID = Zotero.ItemTypes.getID(itemType);
|
|
|
|
var fieldList = Zotero.ItemFields.getItemTypeFields(typeID);
|
|
|
|
for (let field of fieldList) {
|
|
|
|
var key = Zotero.ItemFields.getName(field);
|
2023-01-17 15:38:43 +00:00
|
|
|
let fieldLocalizedName = Zotero.ItemFields.getLocalizedString(field);
|
|
|
|
outputObject[key] = fieldLocalizedName;
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
var creatorList = Zotero.CreatorTypes.getTypesForItemType(typeID);
|
|
|
|
var creators = [];
|
|
|
|
for (let creatorType of creatorList) {
|
|
|
|
creators.push({ firstName: "", lastName: "", creatorType: creatorType.name, fieldMode: true });
|
|
|
|
}
|
|
|
|
outputObject.creators = creators;
|
|
|
|
outputObject.attachments = [{ url: "", document: "", title: "", mimeType: "" }];
|
|
|
|
outputObject.tags = [{ tag: "" }];
|
|
|
|
outputObject.notes = [{ note: "" }];
|
|
|
|
outputObject.seeAlso = [];
|
|
|
|
return JSON.stringify(outputObject, null, '\t');
|
2020-12-24 07:46:19 +00:00
|
|
|
};
|
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
/*
|
|
|
|
* add template code
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.addTemplate = async function (template, second) {
|
|
|
|
switch (template) {
|
2019-08-02 10:09:36 +00:00
|
|
|
case "templateNewItem":
|
2021-12-29 01:32:56 +00:00
|
|
|
document.getElementById('output').value = this.listFieldsForItemType(second);
|
2019-08-02 10:09:36 +00:00
|
|
|
break;
|
|
|
|
case "templateAllTypes":
|
|
|
|
var typeNames = Zotero.ItemTypes.getTypes().map(t => t.name);
|
|
|
|
document.getElementById('output').value = JSON.stringify(typeNames, null, '\t');
|
|
|
|
break;
|
2021-12-29 01:32:56 +00:00
|
|
|
default: {
|
2019-08-02 10:09:36 +00:00
|
|
|
//newWeb, scrapeEM, scrapeRIS, scrapeBibTeX, scrapeMARC
|
|
|
|
//These names in the XUL file have to match the file names in template folder.
|
2021-12-29 01:32:56 +00:00
|
|
|
let value = Zotero.File.getContentsFromURL(`chrome://scaffold/content/templates/${template}.js`);
|
|
|
|
let cursorOffset = value.indexOf('$$CURSOR$$');
|
|
|
|
value = value.replace('$$CURSOR$$', '');
|
|
|
|
|
|
|
|
var selection = _editors.code.getSelection();
|
|
|
|
var id = { major: 1, minor: 1 };
|
|
|
|
var op = { identifier: id, range: selection, text: value, forceMoveMarkers: true };
|
|
|
|
_editors.code.executeEdits("addTemplate", [op]);
|
|
|
|
|
|
|
|
if (cursorOffset != -1) {
|
|
|
|
_editors.code.setPosition(_editors.code.getModel().getPositionAt(cursorOffset));
|
|
|
|
}
|
|
|
|
|
|
|
|
break;
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* run translator
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.run = async function (functionToRun) {
|
2019-08-02 10:09:36 +00:00
|
|
|
if (document.getElementById('textbox-label').value == 'Untitled') {
|
2021-12-29 01:32:56 +00:00
|
|
|
_logOutput("Translator title not set");
|
2019-08-02 10:09:36 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
_clearOutput();
|
|
|
|
|
|
|
|
// Handle generic call run('detect'), run('do')
|
|
|
|
if (functionToRun == "detect" || functionToRun == "do") {
|
2021-12-29 01:32:56 +00:00
|
|
|
if (document.getElementById('checkbox-web').checked
|
2022-06-08 22:16:50 +00:00
|
|
|
&& _browser.currentURI.spec != 'about:blank') {
|
2021-12-29 01:32:56 +00:00
|
|
|
functionToRun += 'Web';
|
|
|
|
}
|
|
|
|
else if (document.getElementById('checkbox-import').checked
|
|
|
|
&& _editors.import.getValue().trim()) {
|
|
|
|
functionToRun += 'Import';
|
|
|
|
}
|
|
|
|
else if (document.getElementById('checkbox-export').checked
|
|
|
|
&& functionToRun == 'do') {
|
|
|
|
functionToRun += 'Export';
|
|
|
|
}
|
|
|
|
else if (document.getElementById('checkbox-search').checked
|
|
|
|
&& _editors.import.getValue().trim()) {
|
|
|
|
functionToRun += 'Search';
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
_logOutput('No appropriate detect/do function to run');
|
|
|
|
return;
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
_logOutput(`Running ${functionToRun}`);
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2022-06-08 22:16:50 +00:00
|
|
|
let input = await _getInput(functionToRun);
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
if (functionToRun.endsWith('Export')) {
|
|
|
|
let numItems = Zotero.getActiveZoteroPane().getSelectedItems().length;
|
|
|
|
_logOutput(`Exporting ${numItems} item${numItems == 1 ? '' : 's'} selected in library`);
|
|
|
|
_run(functionToRun, input, _selectItems, () => {}, _getTranslatorsHandler(functionToRun), _myExportDone);
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
else {
|
|
|
|
_run(functionToRun, input, _selectItems, _myItemDone, _getTranslatorsHandler(functionToRun));
|
|
|
|
}
|
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* run translator in given mode with given input
|
|
|
|
*/
|
2023-04-14 15:37:07 +00:00
|
|
|
async function _run(functionToRun, input, selectItems, itemDone, detectHandler, done) {
|
|
|
|
let translate;
|
|
|
|
let isRemoteWeb = false;
|
2019-08-02 10:09:36 +00:00
|
|
|
if (functionToRun == "detectWeb" || functionToRun == "doWeb") {
|
2023-04-14 15:37:07 +00:00
|
|
|
translate = new RemoteTranslate();
|
|
|
|
isRemoteWeb = true;
|
2019-08-30 05:02:12 +00:00
|
|
|
if (!_testTargetRegex(input)) {
|
2023-04-14 15:37:07 +00:00
|
|
|
_logOutput("Target did not match " + _getCurrentURI(input));
|
2019-08-30 05:02:12 +00:00
|
|
|
if (done) {
|
|
|
|
done();
|
|
|
|
}
|
|
|
|
return;
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2023-04-14 15:37:07 +00:00
|
|
|
await translate.setBrowser(input);
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
else if (functionToRun == "detectImport" || functionToRun == "doImport") {
|
|
|
|
translate = new Zotero.Translate.Import();
|
2019-08-02 10:09:36 +00:00
|
|
|
translate.setString(input);
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
else if (functionToRun == "doExport") {
|
|
|
|
translate = new Zotero.Translate.Export();
|
|
|
|
translate.setItems(input);
|
|
|
|
}
|
|
|
|
else if (functionToRun == "detectSearch" || functionToRun == "doSearch") {
|
|
|
|
translate = new Zotero.Translate.Search();
|
|
|
|
translate.setSearch(input);
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
translate.setTranslatorProvider(_translatorProvider);
|
|
|
|
translate.setHandler("error", _error);
|
|
|
|
translate.setHandler("debug", _debug);
|
|
|
|
if (done) {
|
|
|
|
translate.setHandler("done", done);
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
// get translator
|
|
|
|
var translator = _getTranslatorFromPane();
|
|
|
|
if (functionToRun.startsWith('detect')) {
|
2023-04-14 15:37:07 +00:00
|
|
|
if (isRemoteWeb) {
|
2023-06-15 23:18:57 +00:00
|
|
|
try {
|
|
|
|
translate.setTranslator(translator);
|
|
|
|
detectHandler(translate, await translate.detect());
|
|
|
|
}
|
|
|
|
finally {
|
|
|
|
translate.dispose();
|
|
|
|
}
|
2023-04-14 15:37:07 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
// don't let target prevent translator from operating
|
|
|
|
translator.target = null;
|
|
|
|
// generate sandbox
|
|
|
|
translate.setHandler("translators", detectHandler);
|
|
|
|
// internal hack to call detect on this translator
|
|
|
|
translate._potentialTranslators = [translator];
|
|
|
|
translate._foundTranslators = [];
|
|
|
|
translate._currentState = "detect";
|
|
|
|
translate._detect();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else if (isRemoteWeb) {
|
2023-06-15 23:18:57 +00:00
|
|
|
try {
|
|
|
|
translate.setHandler("select", selectItems);
|
|
|
|
translate.setTranslator(translator);
|
|
|
|
let items = await translate.translate({ libraryID: false });
|
|
|
|
if (items) {
|
|
|
|
for (let item of items) {
|
|
|
|
itemDone(translate, item);
|
|
|
|
}
|
2023-04-14 15:37:07 +00:00
|
|
|
}
|
|
|
|
}
|
2023-06-15 23:18:57 +00:00
|
|
|
finally {
|
|
|
|
translate.dispose();
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
else {
|
2019-08-02 10:09:36 +00:00
|
|
|
// don't let the detectCode prevent the translator from operating
|
|
|
|
translator.detectCode = null;
|
|
|
|
translate.setTranslator(translator);
|
|
|
|
translate.setHandler("select", selectItems);
|
|
|
|
translate.clearHandlers("itemDone");
|
|
|
|
translate.clearHandlers("collectionDone");
|
|
|
|
translate.setHandler("itemDone", itemDone);
|
2021-12-29 01:32:56 +00:00
|
|
|
translate.setHandler("collectionDone", function (obj, collection) {
|
|
|
|
_logOutput("Collection: " + collection.name + ", " + collection.children.length + " items");
|
2019-08-02 10:09:36 +00:00
|
|
|
});
|
|
|
|
translate.translate({
|
|
|
|
// disable saving to database
|
|
|
|
libraryID: false
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-09 07:42:08 +00:00
|
|
|
this.runTranslatorOrTests = async function () {
|
2021-12-29 01:32:56 +00:00
|
|
|
if (document.getElementById('tabs').selectedItem.id == 'tab-tests'
|
|
|
|
&& document.activeElement.id == 'testing-listbox') {
|
2021-07-09 07:42:08 +00:00
|
|
|
this.runSelectedTests();
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
this.run('do');
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2021-07-09 07:42:08 +00:00
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
/*
|
|
|
|
* generate translator GUID
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.generateTranslatorID = function () {
|
2019-08-02 10:09:36 +00:00
|
|
|
document.getElementById("textbox-translatorID").value = _generateGUID();
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2019-08-30 05:02:12 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Test target regular expression against document URL and log the result
|
2019-08-02 10:09:36 +00:00
|
|
|
*/
|
2022-06-08 22:16:50 +00:00
|
|
|
this.logTargetRegex = async function () {
|
2023-04-14 15:37:07 +00:00
|
|
|
_logOutput(_testTargetRegex(_browser));
|
2019-08-30 05:02:12 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Test target regular expression against document URL and return the result
|
|
|
|
*/
|
2023-04-14 15:37:07 +00:00
|
|
|
function _testTargetRegex(browser) {
|
|
|
|
var url = _getCurrentURI(browser);
|
2019-08-30 05:02:12 +00:00
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
try {
|
|
|
|
var targetRe = new RegExp(document.getElementById('textbox-target').value, "i");
|
|
|
|
}
|
2019-08-30 05:02:12 +00:00
|
|
|
catch (e) {
|
|
|
|
_logOutput("Regex parse error:\n" + JSON.stringify(e, null, "\t"));
|
|
|
|
}
|
|
|
|
|
|
|
|
return targetRe.test(url);
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2019-08-30 05:02:12 +00:00
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
/*
|
|
|
|
* called to select items
|
|
|
|
*/
|
|
|
|
function _selectItems(obj, itemList) {
|
2021-12-29 01:32:56 +00:00
|
|
|
var io = { dataIn: itemList, dataOut: null };
|
2022-06-08 22:16:50 +00:00
|
|
|
window.openDialog("chrome://zotero/content/ingester/selectitems.xhtml",
|
2021-12-29 01:32:56 +00:00
|
|
|
"_blank", "chrome,modal,centerscreen,resizable=yes", io);
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
return io.dataOut;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* called if an error occurs
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
function _error(_obj, _error) {
|
|
|
|
// stub: this handler doesn't actually seem to get called by the current
|
|
|
|
// translation architecture when a translator throws
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* logs translator output (instead of logging in the console)
|
|
|
|
*/
|
|
|
|
function _debug(obj, string) {
|
|
|
|
_logOutput(string);
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* logs item output
|
|
|
|
*/
|
|
|
|
function _myItemDone(obj, item) {
|
2022-03-09 19:42:16 +00:00
|
|
|
if (Array.isArray(item.attachments)) {
|
|
|
|
for (let attachment of item.attachments) {
|
|
|
|
if (attachment.document) {
|
|
|
|
attachment.document = '[object Document]';
|
|
|
|
attachment.mimeType = 'text/html';
|
|
|
|
}
|
|
|
|
delete attachment.url;
|
|
|
|
delete attachment.complete;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_logOutput("Returned item:\n" + Zotero_TranslatorTester._generateDiff(item, _sanitizeItemForDisplay(item)));
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2021-12-29 01:32:56 +00:00
|
|
|
* logs string output
|
2019-08-02 10:09:36 +00:00
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
function _myExportDone({ string }, worked) {
|
|
|
|
if (worked) {
|
|
|
|
Zotero.debug("Export successful");
|
|
|
|
_logOutput("Returned string:\n" + string);
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
else {
|
|
|
|
Zotero.debug("Export failed");
|
|
|
|
}
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
2021-12-29 01:32:56 +00:00
|
|
|
* returns a 'translators' handler that prints information from detectCode to window
|
2019-08-02 10:09:36 +00:00
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
function _getTranslatorsHandler(fnName) {
|
|
|
|
return (obj, translators) => {
|
|
|
|
if (translators && translators.length != 0) {
|
|
|
|
if (translators[0].itemType === true) {
|
|
|
|
_logOutput(`${fnName} matched`);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
_logOutput(`${fnName} returned type "${translators[0].itemType}"`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
_logOutput(`${fnName} did not match`);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* logs debug info (instead of console)
|
|
|
|
*/
|
|
|
|
function _logOutput(string) {
|
|
|
|
var date = new Date();
|
|
|
|
var output = document.getElementById('output');
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (typeof string != "string") {
|
2019-08-02 10:09:36 +00:00
|
|
|
string = fix2028(Zotero.Utilities.varDump(string));
|
|
|
|
}
|
|
|
|
|
2023-04-21 17:38:04 +00:00
|
|
|
// Put off actually building the log message and appending it to the console until the next animation frame
|
|
|
|
// so as not to slow down translation with repeated layout recalculations triggered by appending text
|
|
|
|
// and accessing scrollHeight
|
|
|
|
// requestAnimationFrame() callbacks are guaranteed to be called in the order they were set
|
|
|
|
requestAnimationFrame(() => {
|
|
|
|
if (output.value) output.value += "\n";
|
|
|
|
output.value += Zotero.Utilities.lpad(date.getHours(), '0', 2)
|
2021-12-29 01:32:56 +00:00
|
|
|
+ ":" + Zotero.Utilities.lpad(date.getMinutes(), '0', 2)
|
|
|
|
+ ":" + Zotero.Utilities.lpad(date.getSeconds(), '0', 2)
|
|
|
|
+ " " + string.replace(/\n/g, "\n ");
|
2023-04-21 17:38:04 +00:00
|
|
|
// move to end
|
|
|
|
output.scrollTop = output.scrollHeight;
|
|
|
|
});
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* gets import text for import translator
|
|
|
|
*/
|
|
|
|
function _getImport() {
|
2021-12-29 01:32:56 +00:00
|
|
|
var text = _editors.import.getValue();
|
2019-08-02 10:09:36 +00:00
|
|
|
return text;
|
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
/*
|
|
|
|
* gets items to export for export translator
|
|
|
|
*/
|
|
|
|
function _getExport() {
|
|
|
|
return Zotero.getActiveZoteroPane().getSelectedItems();
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* gets search JSON object for search translator
|
|
|
|
*/
|
|
|
|
function _getSearch() {
|
|
|
|
return JSON.parse(_getImport());
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* gets appropriate input for the given type/method
|
|
|
|
*/
|
2022-06-08 22:16:50 +00:00
|
|
|
async function _getInput(typeOrMethod) {
|
2021-12-29 01:32:56 +00:00
|
|
|
typeOrMethod = typeOrMethod.toLowerCase();
|
|
|
|
if (typeOrMethod.endsWith('web')) {
|
2023-04-14 15:37:07 +00:00
|
|
|
return _browser;
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
else if (typeOrMethod.endsWith('import')) {
|
|
|
|
return _getImport();
|
|
|
|
}
|
|
|
|
else if (typeOrMethod.endsWith('export')) {
|
|
|
|
return _getExport();
|
|
|
|
}
|
|
|
|
else if (typeOrMethod.endsWith('search')) {
|
|
|
|
return _getSearch();
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
/*
|
|
|
|
* transfers metadata to the translator object
|
|
|
|
* Replicated from translator.js
|
|
|
|
*/
|
|
|
|
function _metaToTranslator(translator, metadata) {
|
2021-12-29 01:32:56 +00:00
|
|
|
var props = ["translatorID",
|
|
|
|
"translatorType",
|
|
|
|
"label",
|
|
|
|
"creator",
|
|
|
|
"target",
|
|
|
|
"minVersion",
|
|
|
|
"maxVersion",
|
|
|
|
"priority",
|
|
|
|
"lastUpdated",
|
|
|
|
"inRepository",
|
|
|
|
"configOptions",
|
|
|
|
"displayOptions",
|
|
|
|
"browserSupport",
|
|
|
|
"targetAll",
|
|
|
|
"hiddenPrefs"];
|
|
|
|
for (var i = 0; i < props.length; i++) {
|
2019-08-02 10:09:36 +00:00
|
|
|
translator[props[i]] = metadata[props[i]];
|
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (!translator.configOptions) translator.configOptions = {};
|
|
|
|
if (!translator.displayOptions) translator.displayOptions = {};
|
|
|
|
if (!translator.browserSupport) translator.browserSupport = "g";
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* gets translator data from the metadata pane
|
|
|
|
*/
|
|
|
|
function _getTranslatorFromPane() {
|
|
|
|
//create a barebones translator
|
2021-12-29 01:32:56 +00:00
|
|
|
var translator = {};
|
2019-08-02 10:09:36 +00:00
|
|
|
var metadata = _getMetadataObject(true);
|
|
|
|
|
|
|
|
//copy metadata into the translator object
|
|
|
|
_metaToTranslator(translator, metadata);
|
|
|
|
|
|
|
|
metadata = JSON.stringify(metadata, null, "\t") + ";\n";
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
translator.code = metadata + "\n" + _editors.code.getValue();
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
// make sure translator gets run in browser in Zotero >2.1
|
2021-12-29 01:32:56 +00:00
|
|
|
if (Zotero.Translator.RUN_MODE_IN_BROWSER) {
|
2019-08-02 10:09:36 +00:00
|
|
|
translator.runMode = Zotero.Translator.RUN_MODE_IN_BROWSER;
|
|
|
|
}
|
|
|
|
|
|
|
|
return translator;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2021-12-29 01:32:56 +00:00
|
|
|
* loads the translator's tests from the translator code
|
2019-08-02 10:09:36 +00:00
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
function _loadTestsFromTranslator(code) {
|
2019-08-02 10:09:36 +00:00
|
|
|
var testStart = code.indexOf("/** BEGIN TEST CASES **/");
|
2021-12-29 01:32:56 +00:00
|
|
|
var testEnd = code.indexOf("/** END TEST CASES **/");
|
2019-08-02 10:09:36 +00:00
|
|
|
if (testStart !== -1 && testEnd !== -1) {
|
2021-12-29 01:32:56 +00:00
|
|
|
code = code.substring(testStart + 24, testEnd);
|
|
|
|
}
|
|
|
|
|
|
|
|
code = code.replace(/var testCases = /, '').trim();
|
|
|
|
// The JSON parser doesn't like final semicolons
|
|
|
|
if (code.lastIndexOf(';') == code.length - 1) {
|
|
|
|
code = code.slice(0, -1);
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
var testObject = JSON.parse(code);
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
catch (e) {
|
|
|
|
testObject = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
// We don't use _writeTestsToPane here because we want to avoid _stringifyTests,
|
|
|
|
// which assumes valid test data and will choke on/incorrectly "fix"
|
|
|
|
// weird inputs that the user might want to fix manually.
|
|
|
|
_writeToEditor(_editors.tests, JSON.stringify(testObject, null, "\t"));
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
2021-12-29 01:32:56 +00:00
|
|
|
* loads the translator's tests from the pane
|
2019-08-02 10:09:36 +00:00
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
function _loadTestsFromPane() {
|
|
|
|
try {
|
|
|
|
return JSON.parse(_editors.tests.getValue().trim() || '[]');
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
return null;
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
/**
|
|
|
|
* Write text to an editor, overwriting its current value.
|
|
|
|
* This operation can be undone.
|
|
|
|
*/
|
|
|
|
function _writeToEditor(editor, text) {
|
|
|
|
editor.executeEdits('_writeToEditor', [{
|
|
|
|
range: editor.getModel().getFullModelRange(),
|
|
|
|
text
|
|
|
|
}]);
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* writes tests back into the translator
|
|
|
|
*/
|
|
|
|
function _writeTestsToPane(tests) {
|
|
|
|
_writeToEditor(_editors.tests, _stringifyTests(tests));
|
|
|
|
}
|
2023-03-13 21:50:41 +00:00
|
|
|
|
|
|
|
function _confirmCreateExpectedFailTest() {
|
|
|
|
return Services.prompt.confirm(null,
|
|
|
|
'Detection Failed',
|
|
|
|
'Add test ensuring that detection always fails on this page?');
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
2022-03-09 19:42:16 +00:00
|
|
|
/**
|
|
|
|
* Mimics most of the behavior of Zotero.Item#fromJSON. Most importantly,
|
|
|
|
* extracts valid fields from item.extra and inserts invalid fields into
|
|
|
|
* item.extra.
|
|
|
|
*
|
|
|
|
* For example,
|
|
|
|
* { itemType: 'journalArticle', extra: 'DOI: foo' }
|
|
|
|
* becomes
|
|
|
|
* { itemType: 'journalArticle', DOI: 'foo' }
|
|
|
|
* and
|
|
|
|
* { itemType: 'book', DOI: 'foo' }
|
|
|
|
* becomes
|
|
|
|
* { itemType: 'book', extra: 'DOI: foo' }
|
|
|
|
*
|
|
|
|
* @param {any} item
|
|
|
|
* @return {any}
|
2019-08-02 10:09:36 +00:00
|
|
|
*/
|
2022-03-09 19:42:16 +00:00
|
|
|
function _sanitizeItemForDisplay(item) {
|
|
|
|
// try to convert to JSON and back to get rid of undesirable undeletable elements; this may fail
|
|
|
|
try {
|
|
|
|
item = JSON.parse(JSON.stringify(item));
|
|
|
|
}
|
|
|
|
catch (e) {}
|
|
|
|
|
|
|
|
let itemTypeID = Zotero.ItemTypes.getID(item.itemType);
|
|
|
|
|
|
|
|
var setFields = new Set();
|
|
|
|
var { itemType, fields: extraFields, /* creators: extraCreators, */ extra }
|
|
|
|
= Zotero.Utilities.Internal.extractExtraFields(
|
|
|
|
item.extra || '',
|
|
|
|
null,
|
|
|
|
Object.keys(item)
|
|
|
|
// TEMP until we move creator lines to real creators
|
|
|
|
.concat('creators')
|
|
|
|
);
|
|
|
|
// If a different item type was parsed out of Extra, use that instead
|
|
|
|
if (itemType && item.itemType != itemType) {
|
|
|
|
item.itemType = itemType;
|
|
|
|
itemTypeID = Zotero.ItemTypes.getID(itemType);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (let [field, value] of extraFields) {
|
|
|
|
item[field] = value;
|
|
|
|
setFields.add(field);
|
|
|
|
extraFields.delete(field);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (let [field, val] of Object.entries(item)) {
|
|
|
|
switch (field) {
|
|
|
|
case 'itemType':
|
|
|
|
case 'accessDate':
|
|
|
|
case 'creators':
|
|
|
|
case 'attachments':
|
|
|
|
case 'notes':
|
|
|
|
case 'seeAlso':
|
|
|
|
break;
|
|
|
|
|
|
|
|
case 'extra':
|
|
|
|
// We set this later
|
|
|
|
delete item[field];
|
|
|
|
break;
|
|
|
|
|
|
|
|
case 'tags':
|
|
|
|
item[field] = Zotero.Translate.Base.prototype._cleanTags(val);
|
|
|
|
break;
|
|
|
|
|
|
|
|
// Item fields
|
|
|
|
default: {
|
|
|
|
let fieldID = Zotero.ItemFields.getID(field);
|
|
|
|
if (!fieldID) {
|
|
|
|
if (typeof val == 'string') {
|
|
|
|
extraFields.set(field, val);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
delete item[field];
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// Convert to base-mapped field if necessary, so that setFields has the base-mapped field
|
|
|
|
// when it's checked for values from getUsedFields() below
|
|
|
|
let origFieldID = fieldID;
|
|
|
|
let origField = field;
|
|
|
|
fieldID = Zotero.ItemFields.getFieldIDFromTypeAndBase(itemTypeID, fieldID) || fieldID;
|
|
|
|
if (origFieldID != fieldID) {
|
|
|
|
field = Zotero.ItemFields.getName(fieldID);
|
|
|
|
}
|
|
|
|
if (!Zotero.ItemFields.isValidForType(fieldID, itemTypeID)) {
|
|
|
|
extraFields.set(field, val);
|
|
|
|
delete item[field];
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (origFieldID != fieldID) {
|
|
|
|
item[field] = item[origField];
|
|
|
|
delete item[origField];
|
|
|
|
}
|
|
|
|
setFields.add(field);
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-09 19:42:16 +00:00
|
|
|
if (extraFields.size) {
|
|
|
|
for (let field of setFields.keys()) {
|
|
|
|
let baseField;
|
|
|
|
if (Zotero.ItemFields.isBaseField(field)) {
|
|
|
|
baseField = field;
|
|
|
|
}
|
|
|
|
else if (Zotero.ItemFields.isValidForType(Zotero.ItemFields.getID(field), itemTypeID)) {
|
|
|
|
let baseFieldID = Zotero.ItemFields.getBaseIDFromTypeAndField(itemTypeID, field);
|
|
|
|
if (baseFieldID) {
|
|
|
|
baseField = baseFieldID;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (baseField) {
|
|
|
|
let mappedFieldNames = Zotero.ItemFields.getTypeFieldsFromBase(baseField, true);
|
|
|
|
for (let mappedField of mappedFieldNames) {
|
|
|
|
if (extraFields.has(mappedField)) {
|
|
|
|
extraFields.delete(mappedField);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//
|
|
|
|
// Deduplicate remaining Extra fields
|
|
|
|
//
|
|
|
|
// For each invalid-for-type base field, remove any mapped fields with the same value
|
|
|
|
let baseFields = [];
|
|
|
|
for (let field of extraFields.keys()) {
|
|
|
|
if (Zotero.ItemFields.getID(field) && Zotero.ItemFields.isBaseField(field)) {
|
|
|
|
baseFields.push(field);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for (let baseField of baseFields) {
|
|
|
|
let value = extraFields.get(baseField);
|
|
|
|
let mappedFieldNames = Zotero.ItemFields.getTypeFieldsFromBase(baseField, true);
|
|
|
|
for (let mappedField of mappedFieldNames) {
|
|
|
|
if (extraFields.has(mappedField) && extraFields.get(mappedField) === value) {
|
|
|
|
extraFields.delete(mappedField);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove Type-mapped fields from Extra, since 'Type' is mapped to Item Type by citeproc-js
|
|
|
|
// and Type values mostly aren't going to be useful for item types without a Type-mapped field.
|
|
|
|
let typeFieldNames = Zotero.ItemFields.getTypeFieldsFromBase('type', true)
|
|
|
|
.concat('audioFileType');
|
|
|
|
for (let typeFieldName of typeFieldNames) {
|
|
|
|
if (extraFields.has(typeFieldName)) {
|
|
|
|
extraFields.delete(typeFieldName);
|
|
|
|
}
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2022-03-09 19:42:16 +00:00
|
|
|
|
|
|
|
if (extra || extraFields.size) {
|
|
|
|
item.extra = Zotero.Utilities.Internal.combineExtraFields(extra, extraFields);
|
|
|
|
}
|
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
return item;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* sanitizes all items in a test
|
|
|
|
*/
|
|
|
|
function _sanitizeItemsInTest(test) {
|
2021-12-29 01:32:56 +00:00
|
|
|
if (test.items && typeof test.items != 'string' && test.items.length) {
|
|
|
|
for (var i = 0, n = test.items.length; i < n; i++) {
|
2019-08-02 10:09:36 +00:00
|
|
|
test.items[i] = Zotero_TranslatorTester._sanitizeItem(test.items[i]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return test;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* stringifies an array of tests
|
|
|
|
* Output is the same as JSON.stringify (with pretty print), except that
|
|
|
|
* Zotero.Item objects are stringified in a deterministic manner (mostly):
|
|
|
|
* * Certain important fields are placed at the top of the object
|
|
|
|
* * Certain less-frequently used fields are placed at the bottom
|
|
|
|
* * Remaining fields are sorted alphabetically
|
|
|
|
* * tags are always sorted alphabetically
|
|
|
|
* * Some fields, like those inside creator objects, notes, etc. are not sorted
|
|
|
|
*/
|
|
|
|
function _stringifyTests(value, level) {
|
2021-12-29 01:32:56 +00:00
|
|
|
function processRow(key, value) {
|
|
|
|
let val = _stringifyTests(value, level + 1);
|
|
|
|
if (val === undefined) return undefined;
|
|
|
|
|
|
|
|
val = val.replace(/\n/g, "\n\t");
|
|
|
|
return JSON.stringify('' + key) + ': ' + val;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!level) level = 0;
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (typeof (value) == 'function' || typeof (value) == 'undefined' || value === null) {
|
2019-08-02 10:09:36 +00:00
|
|
|
return level ? undefined : '';
|
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (typeof (value) !== 'object') return JSON.stringify(value, null, "\t");
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (Array.isArray(value)) {
|
2019-08-02 10:09:36 +00:00
|
|
|
let str = '[';
|
2021-12-29 01:32:56 +00:00
|
|
|
for (let i = 0; i < value.length; i++) {
|
|
|
|
let val = _stringifyTests(value[i], level + 1);
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (val === undefined) val = 'undefined';
|
2019-08-02 10:09:36 +00:00
|
|
|
else val = val.replace(/\n/g, "\n\t"); // Indent
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
str += (i ? ',' : '') + "\n\t" + val;
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
return str + (str.length > 1 ? "\n]" : ']');
|
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (!value.itemType) {
|
2019-08-02 10:09:36 +00:00
|
|
|
// Not a Zotero.Item object
|
|
|
|
let str = '{';
|
2021-12-29 01:32:56 +00:00
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
if (level < 2 && value.items) {
|
|
|
|
// Test object. Arrange properties in set order
|
2023-03-13 21:50:41 +00:00
|
|
|
let order = ['type', 'url', 'input', 'defer', 'detectedItemType', 'items'];
|
2021-12-29 01:32:56 +00:00
|
|
|
for (let i = 0; i < order.length; i++) {
|
2019-08-02 10:09:36 +00:00
|
|
|
let val = processRow(order[i], value[order[i]]);
|
|
|
|
if (val === undefined) continue;
|
|
|
|
str += (str.length > 1 ? ',' : '') + '\n\t' + val;
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
else {
|
2019-08-02 10:09:36 +00:00
|
|
|
for (let i in value) {
|
|
|
|
let val = processRow(i, value[i]);
|
|
|
|
if (val === undefined) continue;
|
|
|
|
str += (str.length > 1 ? ',' : '') + '\n\t' + val;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return str + (str.length > 1 ? "\n}" : '}');
|
|
|
|
}
|
|
|
|
|
|
|
|
// Zotero.Item object
|
2021-12-29 01:32:56 +00:00
|
|
|
const topFields = ['itemType',
|
|
|
|
'title',
|
|
|
|
'caseName',
|
|
|
|
'nameOfAct',
|
|
|
|
'subject',
|
|
|
|
'creators',
|
|
|
|
'date',
|
|
|
|
'dateDecided',
|
|
|
|
'issueDate',
|
|
|
|
'dateEnacted'];
|
2019-08-02 10:09:36 +00:00
|
|
|
const bottomFields = ['attachments', 'tags', 'notes', 'seeAlso'];
|
|
|
|
let otherFields = Object.keys(value);
|
|
|
|
let presetFields = topFields.concat(bottomFields);
|
2021-12-29 01:32:56 +00:00
|
|
|
for (let i = 0; i < presetFields.length; i++) {
|
2019-08-02 10:09:36 +00:00
|
|
|
let j = otherFields.indexOf(presetFields[i]);
|
2021-12-29 01:32:56 +00:00
|
|
|
if (j == -1) continue;
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
otherFields.splice(j, 1);
|
|
|
|
}
|
|
|
|
let fields = topFields.concat(otherFields.sort()).concat(bottomFields);
|
|
|
|
|
|
|
|
let str = '{';
|
2021-12-29 01:32:56 +00:00
|
|
|
for (let i = 0; i < fields.length; i++) {
|
2019-08-02 10:09:36 +00:00
|
|
|
let rawVal = value[fields[i]];
|
2021-12-29 01:32:56 +00:00
|
|
|
if (!rawVal) continue;
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
let val;
|
2021-12-29 01:32:56 +00:00
|
|
|
if (fields[i] == 'tags') {
|
|
|
|
val = _stringifyTests(rawVal.sort(), level + 1);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
val = _stringifyTests(rawVal, level + 1);
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (val === undefined) continue;
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
val = val.replace(/\n/g, "\n\t");
|
2021-12-29 01:32:56 +00:00
|
|
|
str += (str.length > 1 ? ',' : '') + "\n\t" + JSON.stringify(fields[i]) + ': ' + val;
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return str + "\n}";
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* adds a new test from the current input/translator
|
|
|
|
* web or import only for now
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.saveTestFromCurrent = async function (type) {
|
|
|
|
_logOutput(`Creating ${type} test...`);
|
|
|
|
|
|
|
|
try {
|
|
|
|
let test = await this.constructTestFromCurrent(type);
|
|
|
|
_writeTestsToPane([..._loadTestsFromPane(), test]);
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
_logOutput('Creation failed');
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
_showTab('tests');
|
|
|
|
let listBox = document.getElementById('testing-listbox');
|
|
|
|
listBox.selectedIndex = listBox.getRowCount() - 1;
|
|
|
|
listBox.focus();
|
|
|
|
};
|
|
|
|
|
|
|
|
this.constructTestFromCurrent = async function (type) {
|
2019-08-02 10:09:36 +00:00
|
|
|
_clearOutput();
|
2021-12-29 01:32:56 +00:00
|
|
|
if ((type === "web" && !document.getElementById('checkbox-web').checked)
|
|
|
|
|| (type === "import" && !document.getElementById('checkbox-import').checked)
|
|
|
|
|| (type === "search" && !document.getElementById('checkbox-search').checked)) {
|
|
|
|
_logOutput(`Translator does not support ${type} tests`);
|
|
|
|
return Promise.reject(new Error());
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (type == 'export') {
|
|
|
|
return Promise.reject(new Error(`Test of type export cannot be created`));
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
2022-06-08 22:16:50 +00:00
|
|
|
let input = await _getInput(type);
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
if (type == "web") {
|
2023-06-15 23:18:57 +00:00
|
|
|
let translate = new RemoteTranslate();
|
|
|
|
try {
|
|
|
|
await translate.setBrowser(_browser);
|
|
|
|
await translate.setTranslatorProvider(_translatorProvider);
|
|
|
|
translate.setTranslator(_getTranslatorFromPane());
|
|
|
|
translate.setHandler("debug", _debug);
|
|
|
|
translate.setHandler("error", _error);
|
|
|
|
translate.setHandler("newTestDetectionFailed", _confirmCreateExpectedFailTest);
|
|
|
|
let newTest = await translate.newTest();
|
|
|
|
if (!newTest) {
|
|
|
|
throw new Error('Creation failed');
|
|
|
|
}
|
|
|
|
newTest = _sanitizeItemsInTest(newTest);
|
|
|
|
return newTest;
|
|
|
|
}
|
|
|
|
finally {
|
|
|
|
translate.dispose();
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
else if (type == "import" || type == "search") {
|
|
|
|
let test = { type, input: input, items: [] };
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
// TranslatorTester doesn't handle these correctly, so we do it manually
|
2021-12-29 01:32:56 +00:00
|
|
|
return new Promise(
|
|
|
|
resolve => _run(`do${type == 'import' ? 'Import' : 'Search'}`, input, null, function (obj, item) {
|
|
|
|
if (item) {
|
|
|
|
test.items.push(Zotero_TranslatorTester._sanitizeItem(item));
|
|
|
|
}
|
|
|
|
}, null, function () {
|
|
|
|
resolve(test);
|
|
|
|
})
|
|
|
|
);
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
return Promise.reject(new Error('Invalid type: ' + type));
|
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* populate tests pane and url options in browser pane
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.populateTests = function () {
|
2022-06-08 22:16:50 +00:00
|
|
|
function wrapWithHBox(elem, { flex = undefined, width = undefined } = {}) {
|
|
|
|
let hbox = document.createXULElement('hbox');
|
|
|
|
hbox.append(elem);
|
2022-07-19 18:43:24 +00:00
|
|
|
if (flex !== undefined) hbox.setAttribute('flex', flex);
|
|
|
|
if (width !== undefined) hbox.setAttribute('width', width);
|
2022-06-08 22:16:50 +00:00
|
|
|
return hbox;
|
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
let tests = _loadTestsFromPane();
|
|
|
|
let validateTestsBroadcaster = document.getElementById('validate-tests');
|
|
|
|
if (tests === null) {
|
|
|
|
validateTestsBroadcaster.setAttribute('disabled', true);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
validateTestsBroadcaster.removeAttribute('disabled');
|
|
|
|
}
|
|
|
|
|
|
|
|
let browserURL = document.getElementById("browser-url");
|
|
|
|
let currentURL = browserURL.value;
|
2022-06-08 22:16:50 +00:00
|
|
|
// browserURL.removeAllItems();
|
2019-08-02 10:09:36 +00:00
|
|
|
browserURL.value = currentURL;
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
let listBox = document.getElementById("testing-listbox");
|
|
|
|
let count = listBox.getRowCount();
|
|
|
|
let oldStatuses = {};
|
|
|
|
for (let i = 0; i < count; i++) {
|
|
|
|
let item = listBox.getItemAtIndex(i);
|
2022-06-08 22:16:50 +00:00
|
|
|
let [, statusCell] = item.firstElementChild.children;
|
|
|
|
oldStatuses[item.dataset.testString] = statusCell.getAttribute('value');
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
let testIndex = 0;
|
|
|
|
for (let test of tests) {
|
|
|
|
let testString = _stringifyTests(test, 1);
|
|
|
|
|
|
|
|
// try to reuse old rows
|
|
|
|
let item = testIndex < count
|
|
|
|
? listBox.getItemAtIndex(testIndex)
|
2022-06-08 22:16:50 +00:00
|
|
|
: document.createXULElement('richlistitem');
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
item.innerHTML = ''; // clear children/content if reusing
|
|
|
|
|
2022-06-08 22:16:50 +00:00
|
|
|
let hbox = document.createXULElement('hbox');
|
|
|
|
hbox.setAttribute('flex', 1);
|
|
|
|
hbox.setAttribute('align', 'center');
|
2021-12-29 01:32:56 +00:00
|
|
|
|
2022-06-08 22:16:50 +00:00
|
|
|
let input = document.createXULElement('label');
|
|
|
|
input.value = getTestLabel(test);
|
|
|
|
hbox.appendChild(wrapWithHBox(input, { flex: 1 }));
|
2021-12-29 01:32:56 +00:00
|
|
|
|
2022-06-08 22:16:50 +00:00
|
|
|
let status = document.createXULElement('label');
|
|
|
|
status.value = oldStatuses[testString] || 'Not run';
|
|
|
|
hbox.appendChild(wrapWithHBox(status, { width: 150 }));
|
2022-03-30 21:49:42 +00:00
|
|
|
|
2022-06-08 22:16:50 +00:00
|
|
|
let defer = document.createXULElement('checkbox');
|
|
|
|
defer.checked = test.defer;
|
|
|
|
defer.disabled = true;
|
2022-07-19 18:43:24 +00:00
|
|
|
hbox.appendChild(wrapWithHBox(defer, { width: 30 }));
|
2022-06-08 22:16:50 +00:00
|
|
|
|
|
|
|
item.appendChild(hbox);
|
|
|
|
|
|
|
|
item.dataset.testString = testString;
|
|
|
|
item.dataset.testType = test.type;
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
if (testIndex >= count) {
|
|
|
|
listBox.appendChild(item);
|
|
|
|
}
|
|
|
|
|
2022-06-08 22:16:50 +00:00
|
|
|
// if (test.type == 'web') {
|
|
|
|
// browserURL.appendItem(test.url);
|
|
|
|
// }
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
testIndex++;
|
|
|
|
}
|
|
|
|
|
|
|
|
// remove old rows that we didn't reuse
|
|
|
|
while (listBox.getItemAtIndex(testIndex)) {
|
2022-06-08 22:16:50 +00:00
|
|
|
listBox.getItemAtIndex(testIndex).remove();
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
2021-12-29 01:32:56 +00:00
|
|
|
* Delete selected test(s)
|
2019-08-02 10:09:36 +00:00
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.deleteSelectedTests = function () {
|
2019-08-02 10:09:36 +00:00
|
|
|
var listbox = document.getElementById("testing-listbox");
|
2021-12-29 01:32:56 +00:00
|
|
|
var indicesToRemove = [...listbox.selectedItems].map(item => listbox.getIndexOfItem(item));
|
|
|
|
|
|
|
|
let tests = _loadTestsFromPane();
|
|
|
|
indicesToRemove.forEach(i => tests.splice(i, 1));
|
|
|
|
_writeTestsToPane(tests);
|
|
|
|
|
|
|
|
this.populateTests();
|
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Load the import input for the first selected test in the import pane,
|
|
|
|
* from the UI.
|
2021-12-29 01:32:56 +00:00
|
|
|
*/
|
|
|
|
this.editImportFromTest = function () {
|
2019-08-02 10:09:36 +00:00
|
|
|
var listbox = document.getElementById("testing-listbox");
|
|
|
|
var item = listbox.selectedItems[0];
|
2022-06-08 22:16:50 +00:00
|
|
|
var test = JSON.parse(item.dataset.testString);
|
2019-08-02 10:09:36 +00:00
|
|
|
if (test.input === undefined) {
|
2021-12-29 01:32:56 +00:00
|
|
|
_logOutput("Can't edit input of a non-import/search test.");
|
|
|
|
}
|
|
|
|
_writeToEditor(_editors.import,
|
|
|
|
test.type == 'import'
|
|
|
|
? test.input
|
|
|
|
: JSON.stringify(test.input, null, '\t'));
|
|
|
|
_editors.import.setSelection({
|
|
|
|
startLineNumber: 1,
|
|
|
|
endLineNumber: 1,
|
|
|
|
startColumn: 1,
|
|
|
|
endColumn: 1
|
|
|
|
});
|
|
|
|
_showTab('import');
|
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Copy the url or data of the first selected test to the clipboard.
|
2021-12-29 01:32:56 +00:00
|
|
|
*/
|
|
|
|
this.copyToClipboard = function () {
|
2019-08-02 10:09:36 +00:00
|
|
|
var listbox = document.getElementById("testing-listbox");
|
|
|
|
var item = listbox.selectedItems[0];
|
2022-06-08 22:16:50 +00:00
|
|
|
var url = item.getElementsByTagName("label")[0].getAttribute("value");
|
|
|
|
var test = JSON.parse(item.dataset.testString);
|
2019-08-02 10:09:36 +00:00
|
|
|
var urlOrData = (test.input !== undefined) ? test.input : url;
|
2022-11-01 20:04:24 +00:00
|
|
|
if (typeof urlOrData !== 'string') {
|
|
|
|
urlOrData = JSON.stringify(urlOrData, null, '\t');
|
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
Zotero.Utilities.Internal.copyTextToClipboard(urlOrData);
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-07-13 07:33:57 +00:00
|
|
|
/**
|
|
|
|
* Open the url of the first selected test in the browser (Browser tab or
|
|
|
|
* the system's default browser).
|
|
|
|
* @param {boolean} openExternally whether to open in the default browser
|
|
|
|
**/
|
|
|
|
this.openURL = function (openExternally) {
|
2019-08-02 10:09:36 +00:00
|
|
|
var listbox = document.getElementById("testing-listbox");
|
|
|
|
var item = listbox.selectedItems[0];
|
2022-06-08 22:16:50 +00:00
|
|
|
var url = item.getElementsByTagName("label")[0].getAttribute("value");
|
2021-07-13 07:33:57 +00:00
|
|
|
if (openExternally) {
|
|
|
|
Zotero.launchURL(url);
|
|
|
|
}
|
|
|
|
else {
|
2022-06-08 22:16:50 +00:00
|
|
|
_browser.loadURI(url, {
|
|
|
|
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()
|
|
|
|
});
|
2021-12-29 01:32:56 +00:00
|
|
|
_showTab('browser');
|
2021-07-13 07:33:57 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
this.runTests = function (tests, callback) {
|
|
|
|
callback = callback || (() => {});
|
|
|
|
|
|
|
|
_clearOutput();
|
|
|
|
|
|
|
|
let testsByType = {
|
|
|
|
import: [],
|
|
|
|
export: [],
|
|
|
|
web: [],
|
|
|
|
search: []
|
|
|
|
};
|
|
|
|
|
|
|
|
for (let test of tests) {
|
|
|
|
testsByType[test.type].push(test);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (let [type, testsOfType] of Object.entries(testsByType)) {
|
|
|
|
if (testsOfType.length) {
|
|
|
|
let tester = new Zotero_TranslatorTester(
|
|
|
|
_getTranslatorFromPane(),
|
|
|
|
type,
|
|
|
|
_debug,
|
|
|
|
_translatorProvider
|
|
|
|
);
|
|
|
|
tester.setTests(testsOfType);
|
|
|
|
tester.runTests(callback);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Run selected test(s)
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.runSelectedTests = function () {
|
2019-08-02 10:09:36 +00:00
|
|
|
var listbox = document.getElementById("testing-listbox");
|
|
|
|
var items = listbox.selectedItems;
|
2021-12-29 01:32:56 +00:00
|
|
|
if (!items || items.length == 0) return; // No action if nothing selected
|
|
|
|
var tests = [];
|
|
|
|
for (let item of items) {
|
2022-06-08 22:16:50 +00:00
|
|
|
item.getElementsByTagName("label")[1].setAttribute("value", "Running");
|
|
|
|
var test = JSON.parse(item.dataset.testString);
|
2023-04-14 15:37:07 +00:00
|
|
|
test["ui-item"] = ContentDOMReference.get(item);
|
2021-12-29 01:32:56 +00:00
|
|
|
tests.push(test);
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
|
|
|
this.runTests(tests, (obj, test, status, message) => {
|
2023-04-14 15:37:07 +00:00
|
|
|
ContentDOMReference.resolve(test["ui-item"]).getElementsByTagName("label")[1].setAttribute("value", message);
|
2021-12-29 01:32:56 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
this.updateTests = function (tests, testUpdatedCallback) {
|
|
|
|
_clearOutput();
|
|
|
|
|
|
|
|
var updater = new TestUpdater(tests);
|
|
|
|
return new Promise(resolve => updater.updateTests(
|
|
|
|
testUpdatedCallback,
|
|
|
|
resolve
|
|
|
|
));
|
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Update selected test(s)
|
|
|
|
*/
|
2021-12-29 01:32:56 +00:00
|
|
|
this.updateSelectedTests = async function () {
|
2019-08-02 10:09:36 +00:00
|
|
|
var listbox = document.getElementById("testing-listbox");
|
|
|
|
var items = [...listbox.selectedItems];
|
2021-12-29 01:32:56 +00:00
|
|
|
if (!items || items.length == 0) return; // No action if nothing selected
|
|
|
|
var itemIndices = items.map(item => listbox.getIndexOfItem(item));
|
2019-08-02 10:09:36 +00:00
|
|
|
var tests = [];
|
2021-12-29 01:32:56 +00:00
|
|
|
for (let item of items) {
|
2022-06-08 22:16:50 +00:00
|
|
|
item.getElementsByTagName("label")[1].setAttribute("value", "Updating");
|
|
|
|
var test = JSON.parse(item.dataset.testString);
|
2019-08-02 10:09:36 +00:00
|
|
|
tests.push(test);
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
var testsDone = 0;
|
2021-12-29 01:32:56 +00:00
|
|
|
await this.updateTests(tests,
|
2019-08-02 10:09:36 +00:00
|
|
|
(newTest) => {
|
2021-12-29 01:32:56 +00:00
|
|
|
let message;
|
2019-08-02 10:09:36 +00:00
|
|
|
// Assume sequential. TODO: handle this properly via test ID of some sort
|
2021-12-29 01:32:56 +00:00
|
|
|
if (newTest) {
|
2019-08-02 10:09:36 +00:00
|
|
|
message = "Test updated";
|
2022-06-08 22:16:50 +00:00
|
|
|
items[testsDone].dataset.testString = _stringifyTests(newTest, 1);
|
2021-12-29 01:32:56 +00:00
|
|
|
tests[testsDone] = newTest;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
message = "Update failed";
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
2022-06-08 22:16:50 +00:00
|
|
|
items[testsDone].getElementsByTagName("label")[1].setAttribute("value", message);
|
2019-08-02 10:09:36 +00:00
|
|
|
testsDone++;
|
2021-12-29 01:32:56 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
let allTests = _loadTestsFromPane();
|
|
|
|
for (let [i, test] of Object.entries(tests)) {
|
|
|
|
allTests[itemIndices[i]] = test;
|
|
|
|
}
|
|
|
|
_writeTestsToPane(allTests);
|
|
|
|
_logOutput("Tests updated.");
|
|
|
|
};
|
|
|
|
|
|
|
|
this.populateLinterMenu = function () {
|
|
|
|
let status = 'Path: ' + getDefaultESLintPath();
|
|
|
|
let toggle = Zotero.Prefs.get('scaffold.eslint.enabled') ? 'Disable' : 'Enable';
|
|
|
|
document.getElementById('menu_eslintStatus').label = status;
|
|
|
|
document.getElementById('menu_toggleESLint').label = toggle;
|
|
|
|
};
|
|
|
|
|
|
|
|
this.toggleESLint = async function () {
|
|
|
|
Zotero.Prefs.set('scaffold.eslint.enabled', !Zotero.Prefs.get('scaffold.eslint.enabled'));
|
|
|
|
await getESLintPath();
|
|
|
|
};
|
|
|
|
|
|
|
|
this.showTabNumbered = function (tabNumber) {
|
|
|
|
let tabBox = document.getElementById('left-tabbox');
|
|
|
|
let numTabs = tabBox.querySelectorAll('tabs > tab').length;
|
|
|
|
if (tabNumber > numTabs) {
|
|
|
|
tabNumber = numTabs;
|
|
|
|
}
|
|
|
|
|
|
|
|
tabBox.selectedIndex = tabNumber - 1;
|
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
var TestUpdater = function (tests) {
|
2019-08-02 10:09:36 +00:00
|
|
|
this.testsToUpdate = tests.slice();
|
|
|
|
this.numTestsTotal = this.testsToUpdate.length;
|
|
|
|
this.newTests = [];
|
|
|
|
this.tester = new Zotero_TranslatorTester(
|
|
|
|
_getTranslatorFromPane(),
|
|
|
|
"web",
|
|
|
|
_debug,
|
|
|
|
_translatorProvider
|
|
|
|
);
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
TestUpdater.prototype.updateTests = function (testDoneCallback, doneCallback) {
|
|
|
|
this.testDoneCallback = testDoneCallback || function () { /* no-op */ };
|
|
|
|
this.doneCallback = doneCallback || function () { /* no-op */ };
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
this._updateTests();
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2023-04-14 15:37:07 +00:00
|
|
|
TestUpdater.prototype._updateTests = async function () {
|
2021-12-29 01:32:56 +00:00
|
|
|
if (!this.testsToUpdate.length) {
|
2019-08-02 10:09:36 +00:00
|
|
|
this.doneCallback(this.newTests);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
var test = this.testsToUpdate.shift();
|
|
|
|
_logOutput("Updating test " + (this.numTestsTotal - this.testsToUpdate.length));
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (test.type == 'web') {
|
|
|
|
_logOutput("Loading web page from " + test.url);
|
|
|
|
|
2023-04-14 15:37:07 +00:00
|
|
|
const { HiddenBrowser } = ChromeUtils.import("chrome://zotero/content/HiddenBrowser.jsm");
|
|
|
|
let browser;
|
|
|
|
try {
|
|
|
|
browser = await HiddenBrowser.create(test.url, {
|
|
|
|
requireSuccessfulStatus: true,
|
|
|
|
docShell: { allowMetaRedirects: true }
|
|
|
|
});
|
|
|
|
|
|
|
|
if (test.defer) {
|
|
|
|
_logOutput("Waiting " + (Zotero_TranslatorTester.DEFER_DELAY / 1000)
|
|
|
|
+ " second(s) for page content to settle");
|
|
|
|
await Zotero.Promise.delay(Zotero_TranslatorTester.DEFER_DELAY);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
// Wait just a bit for things to settle
|
|
|
|
await Zotero.Promise.delay(1000);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (browser.currentURI.spec != test.url) {
|
|
|
|
_logOutput("Page URL differs from test. Will be updated. " + browser.currentURI.spec);
|
|
|
|
}
|
|
|
|
|
|
|
|
let translate = new RemoteTranslate();
|
2023-06-15 23:18:57 +00:00
|
|
|
try {
|
|
|
|
await translate.setBrowser(browser);
|
|
|
|
await translate.setTranslatorProvider(_translatorProvider);
|
|
|
|
translate.setTranslator(_getTranslatorFromPane());
|
|
|
|
translate.setHandler("debug", _debug);
|
|
|
|
translate.setHandler("error", _error);
|
|
|
|
translate.setHandler("newTestDetectionFailed", _confirmCreateExpectedFailTest);
|
|
|
|
let newTest = await translate.newTest();
|
|
|
|
newTest = _sanitizeItemsInTest(newTest);
|
|
|
|
this.newTests.push(newTest);
|
|
|
|
this.testDoneCallback(newTest);
|
|
|
|
this._updateTests();
|
|
|
|
}
|
|
|
|
finally {
|
|
|
|
translate.dispose();
|
|
|
|
}
|
2023-04-14 15:37:07 +00:00
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
Zotero.logError(e);
|
|
|
|
this.newTests.push(false);
|
|
|
|
this.testDoneCallback(false);
|
|
|
|
this._updateTests();
|
|
|
|
}
|
|
|
|
finally {
|
|
|
|
if (browser) HiddenBrowser.destroy(browser);
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
else {
|
2019-08-02 10:09:36 +00:00
|
|
|
test.items = [];
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
const methods = {
|
|
|
|
import: 'doImport',
|
|
|
|
export: 'doExport', // not supported, will error
|
|
|
|
search: 'doSearch'
|
|
|
|
};
|
|
|
|
|
2019-08-02 10:09:36 +00:00
|
|
|
// Re-runs the test.
|
|
|
|
// TranslatorTester doesn't handle these correctly, so we do it manually
|
2023-03-13 21:50:41 +00:00
|
|
|
_run(methods[test.type], test.input, null, (obj, item) => {
|
2021-12-29 01:32:56 +00:00
|
|
|
if (item) {
|
2019-08-02 10:09:36 +00:00
|
|
|
test.items.push(Zotero_TranslatorTester._sanitizeItem(item));
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
2023-03-13 21:50:41 +00:00
|
|
|
}, null, () => {
|
2019-08-02 10:09:36 +00:00
|
|
|
if (!test.items.length) test = false;
|
2023-03-13 21:50:41 +00:00
|
|
|
this.newTests.push(test);
|
|
|
|
this.testDoneCallback(test);
|
|
|
|
this._updateTests();
|
2019-08-02 10:09:36 +00:00
|
|
|
});
|
|
|
|
}
|
2021-12-29 01:32:56 +00:00
|
|
|
};
|
2019-08-02 10:09:36 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Normalize whitespace to the Zotero norm of tabs
|
|
|
|
*/
|
|
|
|
function normalizeWhitespace(text) {
|
2021-12-29 01:32:56 +00:00
|
|
|
return text.replace(/^[ \t]+/gm, function (str) {
|
2019-08-02 10:09:36 +00:00
|
|
|
return str.replace(/ {4}/g, "\t");
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Clear output pane
|
|
|
|
*/
|
|
|
|
function _clearOutput() {
|
|
|
|
document.getElementById('output').value = '';
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* generates an RFC 4122 compliant random GUID
|
|
|
|
*/
|
|
|
|
function _generateGUID() {
|
|
|
|
var guid = "";
|
2021-12-29 01:32:56 +00:00
|
|
|
for (var i = 0; i < 16; i++) {
|
2019-08-02 10:09:36 +00:00
|
|
|
var bite = Math.floor(Math.random() * 255);
|
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
if (i == 4 || i == 6 || i == 8 || i == 10) {
|
2019-08-02 10:09:36 +00:00
|
|
|
guid += "-";
|
|
|
|
|
|
|
|
// version
|
2021-12-29 01:32:56 +00:00
|
|
|
if (i == 6) bite = bite & 0x0f | 0x40;
|
2019-08-02 10:09:36 +00:00
|
|
|
// variant
|
2021-12-29 01:32:56 +00:00
|
|
|
if (i == 8) bite = bite & 0x3f | 0x80;
|
2019-08-02 10:09:36 +00:00
|
|
|
}
|
|
|
|
var str = bite.toString(16);
|
|
|
|
guid += str.length == 1 ? '0' + str : str;
|
|
|
|
}
|
|
|
|
return guid;
|
|
|
|
}
|
|
|
|
|
2023-04-14 15:37:07 +00:00
|
|
|
function _getCurrentURI(browser) {
|
|
|
|
return Zotero.Proxies.proxyToProper(browser.currentURI.spec);
|
2019-08-30 05:02:12 +00:00
|
|
|
}
|
2019-08-02 10:09:36 +00:00
|
|
|
|
2021-12-29 01:32:56 +00:00
|
|
|
function _findTestObjectTops(monaco, model) {
|
|
|
|
let tokenization = monaco.editor.tokenize(model.getValue(), 'json');
|
|
|
|
|
|
|
|
let arrayLevel = 0;
|
|
|
|
let objectLevel = 0;
|
|
|
|
|
|
|
|
let ranges = [];
|
|
|
|
|
|
|
|
for (let line in tokenization) {
|
|
|
|
line = +line; // string keys
|
|
|
|
for (let token of tokenization[line]) {
|
|
|
|
if (token.type == 'delimiter.array.json' || token.type == 'delimiter.bracket.json') {
|
|
|
|
let range = {
|
|
|
|
startLineNumber: line + 1,
|
|
|
|
startColumn: token.offset + 1,
|
|
|
|
endLineNumber: line + 1,
|
|
|
|
endColumn: token.offset + 2
|
|
|
|
};
|
|
|
|
let bracket = model.getValueInRange(range);
|
|
|
|
|
|
|
|
if (bracket == '[') {
|
|
|
|
arrayLevel++;
|
|
|
|
}
|
|
|
|
else if (bracket == ']') {
|
|
|
|
arrayLevel--;
|
|
|
|
continue; // we only want to record opening brackets
|
|
|
|
}
|
|
|
|
else if (bracket == '{') {
|
|
|
|
objectLevel++;
|
|
|
|
}
|
|
|
|
else if (bracket == '}') {
|
|
|
|
objectLevel--;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (arrayLevel == 1 && objectLevel == 1) {
|
|
|
|
ranges.push(range);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ranges;
|
|
|
|
}
|
|
|
|
|
|
|
|
function getDefaultESLintPath() {
|
|
|
|
return OS.Path.join(Scaffold_Translators.getDirectory(), 'node_modules', '.bin', 'teslint');
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getESLintPath() {
|
|
|
|
if (!Zotero.Prefs.get('scaffold.eslint.enabled')) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
let eslintPath = getDefaultESLintPath();
|
|
|
|
|
|
|
|
while (!await OS.File.exists(eslintPath)) {
|
|
|
|
let ps = Services.prompt;
|
|
|
|
let buttonFlags = ps.BUTTON_POS_0 * ps.BUTTON_TITLE_IS_STRING
|
|
|
|
+ ps.BUTTON_POS_1 * ps.BUTTON_TITLE_IS_STRING
|
|
|
|
+ ps.BUTTON_POS_2 * ps.BUTTON_TITLE_CANCEL;
|
|
|
|
|
|
|
|
let index = ps.confirmEx(null,
|
|
|
|
"Scaffold",
|
|
|
|
"Zotero uses ESLint to enable code suggestions and error checking, "
|
|
|
|
+ "but it wasn't found in the selected translators directory.\n\n"
|
|
|
|
+ "You can install it from the command line:\n\n"
|
|
|
|
+ ` cd ${Scaffold_Translators.getDirectory()}\n`
|
|
|
|
+ " npm install\n\n",
|
|
|
|
buttonFlags,
|
|
|
|
"Try Again",
|
|
|
|
"Disable Error Checking",
|
|
|
|
null, null, {}
|
|
|
|
);
|
|
|
|
if (index == 1) {
|
|
|
|
Zotero.Prefs.set('scaffold.eslint.enabled', false);
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
else if (index == 2) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return eslintPath;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function runESLint(translatorPath) {
|
|
|
|
if (!translatorPath) return [];
|
|
|
|
|
|
|
|
let eslintPath = await getESLintPath();
|
|
|
|
if (!eslintPath) return [];
|
|
|
|
|
2022-07-19 20:26:17 +00:00
|
|
|
Zotero.debug('Running ESLint');
|
2021-12-29 01:32:56 +00:00
|
|
|
try {
|
2022-07-19 20:26:17 +00:00
|
|
|
let proc = await Subprocess.call({
|
|
|
|
command: eslintPath,
|
|
|
|
arguments: ['-o', '-', '--', translatorPath],
|
|
|
|
});
|
|
|
|
let lintOutput = '';
|
|
|
|
let chunk;
|
|
|
|
while ((chunk = await proc.stdout.readString())) {
|
|
|
|
lintOutput += chunk;
|
|
|
|
}
|
|
|
|
return JSON.parse(lintOutput);
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
catch (e) {
|
2022-07-19 20:26:17 +00:00
|
|
|
Zotero.logError(e);
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
2022-07-19 20:26:17 +00:00
|
|
|
return [];
|
2021-12-29 01:32:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function eslintOutputToModelMarkers(output) {
|
|
|
|
let result = output[0];
|
|
|
|
if (!result) return [];
|
|
|
|
|
|
|
|
return result.messages.map(message => ({
|
|
|
|
startLineNumber: message.line - _linesOfMetadata + 1,
|
|
|
|
startColumn: message.column,
|
|
|
|
endLineNumber: message.endLine - _linesOfMetadata + 1,
|
|
|
|
endColumn: message.endColumn,
|
|
|
|
message: message.message,
|
|
|
|
severity: message.severity * 4,
|
|
|
|
source: 'ESLint',
|
|
|
|
tags: [
|
2022-09-12 21:06:17 +00:00
|
|
|
message.ruleId || '-'
|
2021-12-29 01:32:56 +00:00
|
|
|
]
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
|
|
|
function getTestLabel(test) {
|
|
|
|
switch (test.type) {
|
|
|
|
case 'import':
|
|
|
|
return test.input.substr(0, 80);
|
|
|
|
case 'web':
|
|
|
|
return test.url;
|
|
|
|
case 'search':
|
|
|
|
return JSON.stringify(test.input).substr(0, 80);
|
|
|
|
default:
|
|
|
|
return `Unknown type: ${test.type}`;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function _showTab(tab) {
|
|
|
|
document.getElementById('tabs').selectedItem = document.getElementById(`tab-${tab}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
function _getActiveEditorName() {
|
|
|
|
let activeElement = document.activeElement;
|
|
|
|
if (activeElement && activeElement.id && activeElement.id.startsWith('editor-')) {
|
|
|
|
return activeElement.id.substring(7);
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
window.addEventListener("load", function (e) {
|
|
|
|
Scaffold.onLoad(e);
|
|
|
|
}, false);
|