Compare commits

...

3 Commits

Author SHA1 Message Date
Richard Hansen 5b55f3f98a lint: src/static/js/ace.js 2021-02-07 03:23:40 -05:00
Richard Hansen e49341926f ace: Use `globalThis` instead of non-strict default context
This is necessary before `'use strict';` can be added to the top of
the file.
2021-02-07 03:23:40 -05:00
Richard Hansen 7652b7010e ace: Simplify Ace2Editor method creation
* Delete the unused `optDoNow` parameter from `pendingInit()`.
  * Move the `setAuthorInfo()` 1st parameter check out of the wrapper
    and in to the `setAuthorInfo()` function itself.
2021-02-07 03:23:40 -05:00
2 changed files with 75 additions and 116 deletions

View File

@ -1,3 +1,4 @@
'use strict';
/** /**
* This code is mostly from the old Etherpad. Please help us to comment this code. * This code is mostly from the old Etherpad. Please help us to comment this code.
* This helps other people to understand this code better and helps them to improve it. * This helps other people to understand this code better and helps them to improve it.
@ -25,64 +26,40 @@
const KERNEL_SOURCE = '../static/js/require-kernel.js'; const KERNEL_SOURCE = '../static/js/require-kernel.js';
Ace2Editor.registry = {
nextId: 1,
};
const hooks = require('./pluginfw/hooks'); const hooks = require('./pluginfw/hooks');
const pluginUtils = require('./pluginfw/shared'); const pluginUtils = require('./pluginfw/shared');
const _ = require('./underscore');
function scriptTag(source) { const scriptTag =
return ( (source) => `<script type="text/javascript">\n${source.replace(/<\//g, '<\\/')}</script>`;
`<script type="text/javascript">\n${
source.replace(/<\//g, '<\\/')
}</script>`
);
}
function Ace2Editor() { const Ace2Editor = function () {
const ace2 = Ace2Editor; const ace2 = Ace2Editor;
const editor = {};
let info = { let info = {
editor, editor: this,
id: (ace2.registry.nextId++), id: (ace2.registry.nextId++),
}; };
let loaded = false; let loaded = false;
let actionsPendingInit = []; let actionsPendingInit = [];
function pendingInit(func, optDoNow) { const pendingInit = (func) => function (...args) {
return function () { const action = () => func.apply(this, args);
const that = this; if (loaded) return action();
const args = arguments;
const action = function () {
func.apply(that, args);
};
if (optDoNow) {
optDoNow.apply(that, args);
}
if (loaded) {
action();
} else {
actionsPendingInit.push(action); actionsPendingInit.push(action);
}
}; };
}
function doActionsPendingInit() { const doActionsPendingInit = () => {
_.each(actionsPendingInit, (fn, i) => { for (const fn of actionsPendingInit) fn();
fn();
});
actionsPendingInit = []; actionsPendingInit = [];
} };
ace2.registry[info.id] = info; ace2.registry[info.id] = info;
// The following functions (prefixed by 'ace_') are exposed by editor, but // The following functions (prefixed by 'ace_') are exposed by editor, but
// execution is delayed until init is complete // execution is delayed until init is complete
const aceFunctionsPendingInit = ['importText', const aceFunctionsPendingInit = [
'importText',
'importAText', 'importAText',
'focus', 'focus',
'setEditable', 'setEditable',
@ -100,64 +77,41 @@ function Ace2Editor() {
'setAuthorSelectionRange', 'setAuthorSelectionRange',
'callWithAce', 'callWithAce',
'execCommand', 'execCommand',
'replaceRange']; 'replaceRange',
];
_.each(aceFunctionsPendingInit, (fnName, i) => { for (const fnName of aceFunctionsPendingInit) {
const prefix = 'ace_'; // Note: info[`ace_${fnName}`] does not exist yet, so it can't be passed directly to
const name = prefix + fnName; // pendingInit(). A simple wrapper is used to defer the info[`ace_${fnName}`] lookup until
editor[fnName] = pendingInit(function () { // method invocation.
if (fnName === 'setAuthorInfo') { this[fnName] = pendingInit(function (...args) {
if (!arguments[0]) { info[`ace_${fnName}`].apply(this, args);
// setAuthorInfo AuthorId not set for some reason
} else {
info[prefix + fnName].apply(this, arguments);
}
} else {
info[prefix + fnName].apply(this, arguments);
}
});
}); });
}
editor.exportText = function () { this.exportText = () => loaded ? info.ace_exportText() : '(awaiting init)\n';
if (!loaded) return '(awaiting init)\n';
return info.ace_exportText();
};
editor.getFrame = function () { this.getFrame = () => info.frame || null;
return info.frame || null;
};
editor.getDebugProperty = function (prop) { this.getDebugProperty = (prop) => info.ace_getDebugProperty(prop);
return info.ace_getDebugProperty(prop);
};
editor.getInInternationalComposition = function () { this.getInInternationalComposition =
if (!loaded) return false; () => loaded ? info.ace_getInInternationalComposition() : false;
return info.ace_getInInternationalComposition();
};
// prepareUserChangeset: // prepareUserChangeset:
// Returns null if no new changes or ACE not ready. Otherwise, bundles up all user changes // Returns null if no new changes or ACE not ready. Otherwise, bundles up all user changes
// to the latest base text into a Changeset, which is returned (as a string if encodeAsString). // to the latest base text into a Changeset, which is returned (as a string if encodeAsString).
// If this method returns a truthy value, then applyPreparedChangesetToBase can be called // If this method returns a truthy value, then applyPreparedChangesetToBase can be called at some
// at some later point to consider these changes part of the base, after which prepareUserChangeset // later point to consider these changes part of the base, after which prepareUserChangeset must
// must be called again before applyPreparedChangesetToBase. Multiple consecutive calls // be called again before applyPreparedChangesetToBase. Multiple consecutive calls to
// to prepareUserChangeset will return an updated changeset that takes into account the // prepareUserChangeset will return an updated changeset that takes into account the latest user
// latest user changes, and modify the changeset to be applied by applyPreparedChangesetToBase // changes, and modify the changeset to be applied by applyPreparedChangesetToBase accordingly.
// accordingly. this.prepareUserChangeset = () => loaded ? info.ace_prepareUserChangeset() : null;
editor.prepareUserChangeset = function () {
if (!loaded) return null;
return info.ace_prepareUserChangeset();
};
editor.getUnhandledErrors = function () {
if (!loaded) return [];
// returns array of {error: <browser Error object>, time: +new Date()} // returns array of {error: <browser Error object>, time: +new Date()}
return info.ace_getUnhandledErrors(); this.getUnhandledErrors = () => loaded ? info.ace_getUnhandledErrors() : [];
};
const sortFilesByEmbeded = (files) => {
function sortFilesByEmbeded(files) {
const embededFiles = []; const embededFiles = [];
let remoteFiles = []; let remoteFiles = [];
@ -175,43 +129,42 @@ function Ace2Editor() {
} }
return {embeded: embededFiles, remote: remoteFiles}; return {embeded: embededFiles, remote: remoteFiles};
} };
function pushStyleTagsFor(buffer, files) {
const pushStyleTagsFor = (buffer, files) => {
const sorted = sortFilesByEmbeded(files); const sorted = sortFilesByEmbeded(files);
const embededFiles = sorted.embeded; const embededFiles = sorted.embeded;
const remoteFiles = sorted.remote; const remoteFiles = sorted.remote;
if (embededFiles.length > 0) { if (embededFiles.length > 0) {
buffer.push('<style type="text/css">'); buffer.push('<style type="text/css">');
for (var i = 0, ii = embededFiles.length; i < ii; i++) { for (const file of embededFiles) {
var file = embededFiles[i];
buffer.push((Ace2Editor.EMBEDED[file] || '').replace(/<\//g, '<\\/')); buffer.push((Ace2Editor.EMBEDED[file] || '').replace(/<\//g, '<\\/'));
} }
buffer.push('<\/style>'); buffer.push('</style>');
}
for (var i = 0, ii = remoteFiles.length; i < ii; i++) {
var file = remoteFiles[i];
buffer.push(`<link rel="stylesheet" type="text/css" href="${encodeURI(file)}"\/>`);
} }
for (const file of remoteFiles) {
buffer.push(`<link rel="stylesheet" type="text/css" href="${encodeURI(file)}"/>`);
} }
};
editor.destroy = pendingInit(() => { this.destroy = pendingInit(() => {
info.ace_dispose(); info.ace_dispose();
info.frame.parentNode.removeChild(info.frame); info.frame.parentNode.removeChild(info.frame);
delete ace2.registry[info.id]; delete ace2.registry[info.id];
info = null; // prevent IE 6 closure memory leaks info = null; // prevent IE 6 closure memory leaks
}); });
editor.init = function (containerId, initialCode, doneFunc) { this.init = function (containerId, initialCode, doneFunc) {
editor.importText(initialCode); this.importText(initialCode);
info.onEditorReady = function () { info.onEditorReady = () => {
loaded = true; loaded = true;
doActionsPendingInit(); doActionsPendingInit();
doneFunc(); doneFunc();
}; };
(function () { (() => {
const doctype = '<!doctype html>'; const doctype = '<!doctype html>';
const iframeHTML = []; const iframeHTML = [];
@ -223,8 +176,8 @@ function Ace2Editor() {
// and compressed, putting the compressed code from the named file directly into the // and compressed, putting the compressed code from the named file directly into the
// source here. // source here.
// these lines must conform to a specific format because they are passed by the build script: // these lines must conform to a specific format because they are passed by the build script:
var includedCSS = []; let includedCSS = [];
var $$INCLUDE_CSS = function (filename) { includedCSS.push(filename); }; let $$INCLUDE_CSS = (filename) => { includedCSS.push(filename); };
$$INCLUDE_CSS('../static/css/iframe_editor.css'); $$INCLUDE_CSS('../static/css/iframe_editor.css');
// disableCustomScriptsAndStyles can be used to disable loading of custom scripts // disableCustomScriptsAndStyles can be used to disable loading of custom scripts
@ -232,14 +185,15 @@ function Ace2Editor() {
$$INCLUDE_CSS(`../static/css/pad.css?v=${clientVars.randomVersionString}`); $$INCLUDE_CSS(`../static/css/pad.css?v=${clientVars.randomVersionString}`);
} }
var additionalCSS = _(hooks.callAll('aceEditorCSS')).map((path) => { let additionalCSS = hooks.callAll('aceEditorCSS').map((path) => {
if (path.match(/\/\//)) { // Allow urls to external CSS - http(s):// and //some/path.css if (path.match(/\/\//)) { // Allow urls to external CSS - http(s):// and //some/path.css
return path; return path;
} }
return `../static/plugins/${path}`; return `../static/plugins/${path}`;
}); });
includedCSS = includedCSS.concat(additionalCSS); includedCSS = includedCSS.concat(additionalCSS);
$$INCLUDE_CSS(`../static/skins/${clientVars.skinName}/pad.css?v=${clientVars.randomVersionString}`); $$INCLUDE_CSS(
`../static/skins/${clientVars.skinName}/pad.css?v=${clientVars.randomVersionString}`);
pushStyleTagsFor(iframeHTML, includedCSS); pushStyleTagsFor(iframeHTML, includedCSS);
@ -272,15 +226,16 @@ plugins.ensure(function () {\n\
iframeHTML, iframeHTML,
}); });
iframeHTML.push('</head><body id="innerdocbody" class="innerdocbody" role="application" class="syntax" spellcheck="false">&nbsp;</body></html>'); iframeHTML.push('</head><body id="innerdocbody" class="innerdocbody" role="application" ' +
'class="syntax" spellcheck="false">&nbsp;</body></html>');
// Expose myself to global for my child frame. // eslint-disable-next-line node/no-unsupported-features/es-builtins
const thisFunctionsName = 'ChildAccessibleAce2Editor'; const gt = typeof globalThis === 'object' ? globalThis : window;
(function () { return this; }())[thisFunctionsName] = Ace2Editor; gt.ChildAccessibleAce2Editor = Ace2Editor;
const outerScript = `\ const outerScript = `\
editorId = ${JSON.stringify(info.id)};\n\ editorId = ${JSON.stringify(info.id)};\n\
editorInfo = parent[${JSON.stringify(thisFunctionsName)}].registry[editorId];\n\ editorInfo = parent.ChildAccessibleAce2Editor.registry[editorId];\n\
window.onload = function () {\n\ window.onload = function () {\n\
window.onload = null;\n\ window.onload = null;\n\
setTimeout(function () {\n\ setTimeout(function () {\n\
@ -306,23 +261,24 @@ window.onload = function () {\n\
}, 0);\n\ }, 0);\n\
}`; }`;
const outerHTML = [doctype, `<html class="inner-editor outerdoc ${clientVars.skinVariants}"><head>`]; const outerHTML =
[doctype, `<html class="inner-editor outerdoc ${clientVars.skinVariants}"><head>`];
var includedCSS = []; includedCSS = [];
var $$INCLUDE_CSS = function (filename) { includedCSS.push(filename); }; $$INCLUDE_CSS = (filename) => { includedCSS.push(filename); };
$$INCLUDE_CSS('../static/css/iframe_editor.css'); $$INCLUDE_CSS('../static/css/iframe_editor.css');
$$INCLUDE_CSS(`../static/css/pad.css?v=${clientVars.randomVersionString}`); $$INCLUDE_CSS(`../static/css/pad.css?v=${clientVars.randomVersionString}`);
var additionalCSS = _(hooks.callAll('aceEditorCSS')).map((path) => { additionalCSS = hooks.callAll('aceEditorCSS').map((path) => {
if (path.match(/\/\//)) { // Allow urls to external CSS - http(s):// and //some/path.css if (path.match(/\/\//)) { // Allow urls to external CSS - http(s):// and //some/path.css
return path; return path;
} }
return `../static/plugins/${path}`; return `../static/plugins/${path}`;
} });
);
includedCSS = includedCSS.concat(additionalCSS); includedCSS = includedCSS.concat(additionalCSS);
$$INCLUDE_CSS(`../static/skins/${clientVars.skinName}/pad.css?v=${clientVars.randomVersionString}`); $$INCLUDE_CSS(
`../static/skins/${clientVars.skinName}/pad.css?v=${clientVars.randomVersionString}`);
pushStyleTagsFor(outerHTML, includedCSS); pushStyleTagsFor(outerHTML, includedCSS);
@ -353,8 +309,10 @@ window.onload = function () {\n\
editorDocument.close(); editorDocument.close();
})(); })();
}; };
};
return editor; Ace2Editor.registry = {
} nextId: 1,
};
exports.Ace2Editor = Ace2Editor; exports.Ace2Editor = Ace2Editor;

View File

@ -258,6 +258,7 @@ function Ace2Inner() {
}; };
const setAuthorInfo = (author, info) => { const setAuthorInfo = (author, info) => {
if (!author) return; // author ID not set for some reason
if ((typeof author) !== 'string') { if ((typeof author) !== 'string') {
// Potentially caused by: https://github.com/ether/etherpad-lite/issues/2802"); // Potentially caused by: https://github.com/ether/etherpad-lite/issues/2802");
throw new Error(`setAuthorInfo: author (${author}) is not a string`); throw new Error(`setAuthorInfo: author (${author}) is not a string`);