etherpad-lite/src/static/js/ace.js

291 lines
10 KiB
JavaScript
Raw Normal View History

2021-01-29 06:43:53 +01:00
'use strict';
/**
2013-06-14 19:37:41 +02:00
* 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.
* TL;DR COMMENTS ON THIS FILE ARE HIGHLY APPRECIATED
*/
2011-03-26 14:10:41 +01:00
/**
* Copyright 2009 Google Inc.
2011-07-07 19:59:34 +02:00
*
2011-03-26 14:10:41 +01:00
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
2011-07-07 19:59:34 +02:00
*
2011-03-26 14:10:41 +01:00
* http://www.apache.org/licenses/LICENSE-2.0
2011-07-07 19:59:34 +02:00
*
2011-03-26 14:10:41 +01:00
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// requires: top
// requires: undefined
2020-11-23 19:24:19 +01:00
const hooks = require('./pluginfw/hooks');
const pluginUtils = require('./pluginfw/shared');
// The inner and outer iframe's locations are about:blank, so relative URLs are relative to that.
// Firefox and Chrome seem to do what the developer intends if given a relative URL, but Safari
// errors out unless given an absolute URL for a JavaScript-created element.
const absUrl = (url) => new URL(url, window.location.href).href;
2021-01-29 06:43:53 +01:00
const scriptTag =
(source) => `<script type="text/javascript">\n${source.replace(/<\//g, '<\\/')}</script>`;
2021-01-29 06:43:53 +01:00
const Ace2Editor = function () {
2020-11-23 19:24:19 +01:00
const ace2 = Ace2Editor;
2011-03-26 14:10:41 +01:00
2020-11-23 19:24:19 +01:00
let info = {
2021-01-29 06:43:53 +01:00
editor: this,
2020-11-23 19:24:19 +01:00
id: (ace2.registry.nextId++),
2011-07-07 19:59:34 +02:00
};
2020-11-23 19:24:19 +01:00
let loaded = false;
2011-03-26 14:10:41 +01:00
2020-11-23 19:24:19 +01:00
let actionsPendingInit = [];
2011-07-07 19:59:34 +02:00
const pendingInit = (func) => function (...args) {
const action = () => func.apply(this, args);
if (loaded) return action();
actionsPendingInit.push(action);
};
2011-07-07 19:59:34 +02:00
2021-01-29 06:43:53 +01:00
const doActionsPendingInit = () => {
for (const fn of actionsPendingInit) fn();
2011-03-26 14:10:41 +01:00
actionsPendingInit = [];
2021-01-29 06:43:53 +01:00
};
2013-06-14 19:37:41 +02:00
2011-03-26 14:10:41 +01:00
ace2.registry[info.id] = info;
// The following functions (prefixed by 'ace_') are exposed by editor, but
// execution is delayed until init is complete
2021-01-29 06:43:53 +01:00
const aceFunctionsPendingInit = [
'importText',
2020-11-23 19:24:19 +01:00
'importAText',
'focus',
'setEditable',
'getFormattedCode',
'setOnKeyPress',
'setOnKeyDown',
'setNotifyDirty',
'setProperty',
'setBaseText',
'setBaseAttributedText',
'applyChangesToBase',
'applyPreparedChangesetToBase',
'setUserChangeNotificationCallback',
'setAuthorInfo',
'setAuthorSelectionRange',
'callWithAce',
'execCommand',
2021-01-29 06:43:53 +01:00
'replaceRange',
];
2020-11-23 19:24:19 +01:00
for (const fnName of aceFunctionsPendingInit) {
// Note: info[`ace_${fnName}`] does not exist yet, so it can't be passed directly to
// pendingInit(). A simple wrapper is used to defer the info[`ace_${fnName}`] lookup until
// method invocation.
2021-01-29 06:43:53 +01:00
this[fnName] = pendingInit(function (...args) {
info[`ace_${fnName}`].apply(this, args);
});
}
2013-06-14 19:37:41 +02:00
2021-01-29 06:43:53 +01:00
this.exportText = () => loaded ? info.ace_exportText() : '(awaiting init)\n';
2013-06-14 19:37:41 +02:00
2021-01-29 06:43:53 +01:00
this.getDebugProperty = (prop) => info.ace_getDebugProperty(prop);
2011-07-07 19:59:34 +02:00
2021-01-29 06:43:53 +01:00
this.getInInternationalComposition =
() => loaded ? info.ace_getInInternationalComposition() : false;
2011-03-26 14:10:41 +01:00
// prepareUserChangeset:
// 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).
2021-01-29 06:43:53 +01:00
// If this method returns a truthy value, then applyPreparedChangesetToBase can be called at some
// later point to consider these changes part of the base, after which prepareUserChangeset must
// be called again before applyPreparedChangesetToBase. Multiple consecutive calls to
// prepareUserChangeset will return an updated changeset that takes into account the latest user
// changes, and modify the changeset to be applied by applyPreparedChangesetToBase accordingly.
this.prepareUserChangeset = () => loaded ? info.ace_prepareUserChangeset() : null;
2011-03-26 14:10:41 +01:00
2021-01-29 06:43:53 +01:00
// returns array of {error: <browser Error object>, time: +new Date()}
this.getUnhandledErrors = () => loaded ? info.ace_getUnhandledErrors() : [];
2011-03-26 14:10:41 +01:00
2021-01-29 06:43:53 +01:00
const sortFilesByEmbeded = (files) => {
2020-11-23 19:24:19 +01:00
const embededFiles = [];
let remoteFiles = [];
2012-01-15 09:05:26 +01:00
if (Ace2Editor.EMBEDED) {
2020-11-23 19:24:19 +01:00
for (let i = 0, ii = files.length; i < ii; i++) {
const file = files[i];
2012-01-15 09:05:26 +01:00
if (Object.prototype.hasOwnProperty.call(Ace2Editor.EMBEDED, file)) {
embededFiles.push(file);
} else {
remoteFiles.push(file);
}
}
} else {
2012-01-15 09:05:26 +01:00
remoteFiles = files;
}
2012-01-15 09:05:26 +01:00
return {embeded: embededFiles, remote: remoteFiles};
2021-01-29 06:43:53 +01:00
};
const pushStyleTagsFor = (buffer, files) => {
2020-11-23 19:24:19 +01:00
const sorted = sortFilesByEmbeded(files);
const embededFiles = sorted.embeded;
const remoteFiles = sorted.remote;
2012-01-15 09:05:26 +01:00
if (embededFiles.length > 0) {
buffer.push('<style type="text/css">');
2021-01-29 06:43:53 +01:00
for (const file of embededFiles) {
buffer.push((Ace2Editor.EMBEDED[file] || '').replace(/<\//g, '<\\/'));
2012-01-15 09:05:26 +01:00
}
2021-01-29 06:43:53 +01:00
buffer.push('</style>');
2012-01-15 09:05:26 +01:00
}
2021-01-29 06:43:53 +01:00
for (const file of remoteFiles) {
buffer.push(`<link rel="stylesheet" type="text/css" href="${absUrl(encodeURI(file))}"/>`);
2012-01-15 09:05:26 +01:00
}
2021-01-29 06:43:53 +01:00
};
2011-03-26 14:10:41 +01:00
2021-01-29 06:43:53 +01:00
this.destroy = pendingInit(() => {
2011-03-26 14:10:41 +01:00
info.ace_dispose();
info.frame.parentNode.removeChild(info.frame);
delete ace2.registry[info.id];
info = null; // prevent IE 6 closure memory leaks
});
2021-01-29 06:43:53 +01:00
this.init = function (containerId, initialCode, doneFunc) {
this.importText(initialCode);
2011-03-26 14:10:41 +01:00
2021-01-29 06:43:53 +01:00
info.onEditorReady = () => {
2011-03-26 14:10:41 +01:00
loaded = true;
doActionsPendingInit();
doneFunc();
};
2021-02-26 07:37:33 +01:00
// calls to these functions ($$INCLUDE_...) are replaced when this file is processed
// and compressed, putting the compressed code from the named file directly into the
// source here.
// these lines must conform to a specific format because they are passed by the build script:
const includedCSS = [];
const $$INCLUDE_CSS = (filename) => { includedCSS.push(filename); };
2021-02-26 07:37:33 +01:00
$$INCLUDE_CSS('../static/css/iframe_editor.css');
$$INCLUDE_CSS(`../static/css/pad.css?v=${clientVars.randomVersionString}`);
includedCSS.push(...hooks.callAll('aceEditorCSS').map(
// Allow urls to external CSS - http(s):// and //some/path.css
(p) => /\/\//.test(p) ? p : `../static/plugins/${p}`));
2021-02-26 07:37:33 +01:00
$$INCLUDE_CSS(
`../static/skins/${clientVars.skinName}/pad.css?v=${clientVars.randomVersionString}`);
2013-06-14 19:37:41 +02:00
const doctype = '<!doctype html>';
const iframeHTML = [];
iframeHTML.push(doctype);
iframeHTML.push(`<html class='inner-editor ${clientVars.skinVariants}'><head>`);
2021-02-26 07:37:33 +01:00
pushStyleTagsFor(iframeHTML, includedCSS);
const requireKernelUrl =
absUrl(`../static/js/require-kernel.js?v=${clientVars.randomVersionString}`);
iframeHTML.push(`<script type="text/javascript" src="${requireKernelUrl}"></script>`);
// Pre-fetch modules to improve load performance.
for (const module of ['ace2_inner', 'ace2_common']) {
const url = absUrl(`../javascripts/lib/ep_etherpad-lite/static/js/${module}.js` +
`?callback=require.define&v=${clientVars.randomVersionString}`);
iframeHTML.push(`<script type="text/javascript" src="${url}"></script>`);
}
2011-07-07 19:59:34 +02:00
2021-02-26 07:37:33 +01:00
iframeHTML.push(scriptTag(`(() => {
const require = window.require;
require.setRootURI(${JSON.stringify(absUrl('../javascripts/src'))});
require.setLibraryURI(${JSON.stringify(absUrl('../javascripts/lib'))});
2021-02-26 07:37:33 +01:00
require.setGlobalKeyPath('require');
2012-01-15 09:05:26 +01:00
2021-02-26 07:37:33 +01:00
// intentially moved before requiring client_plugins to save a 307
window.Ace2Inner = require('ep_etherpad-lite/static/js/ace2_inner');
window.plugins = require('ep_etherpad-lite/static/js/pluginfw/client_plugins');
window.plugins.adoptPluginsFromAncestorsOf(window);
2013-06-14 19:37:41 +02:00
2021-02-26 07:37:33 +01:00
window.$ = window.jQuery = require('ep_etherpad-lite/static/js/rjquery').jQuery;
2013-06-14 19:37:41 +02:00
window.plugins.ensure(() => { window.Ace2Inner.init(parent.editorInfo, parent.readyFunc); });
2021-02-26 07:37:33 +01:00
})();`));
iframeHTML.push('<style type="text/css" title="dynamicsyntax"></style>');
hooks.callAll('aceInitInnerdocbodyHead', {
iframeHTML,
});
iframeHTML.push('</head><body id="innerdocbody" class="innerdocbody" role="application" ' +
'spellcheck="false">&nbsp;</body></html>');
// eslint-disable-next-line node/no-unsupported-features/es-builtins
const gt = typeof globalThis === 'object' ? globalThis : window;
gt.ChildAccessibleAce2Editor = Ace2Editor;
const outerScript = `(() => {
window.editorInfo = parent.ChildAccessibleAce2Editor.registry[${JSON.stringify(info.id)}];
window.onload = () => {
window.onload = null;
setTimeout(() => {
const iframe = document.createElement('iframe');
iframe.name = 'ace_inner';
iframe.title = 'pad';
iframe.scrolling = 'no';
iframe.frameBorder = 0;
iframe.allowTransparency = true; // for IE
iframe.ace_outerWin = window;
document.body.insertBefore(iframe, document.body.firstChild);
window.readyFunc = () => {
delete window.readyFunc;
window.editorInfo.onEditorReady();
delete window.editorInfo;
};
const doc = iframe.contentWindow.document;
doc.open();
doc.write(${JSON.stringify(iframeHTML.join('\n'))});
doc.close();
}, 0);
}
})();`;
const outerHTML =
[doctype, `<html class="inner-editor outerdoc ${clientVars.skinVariants}"><head>`];
pushStyleTagsFor(outerHTML, includedCSS);
// bizarrely, in FF2, a file with no "external" dependencies won't finish loading properly
// (throbs busy while typing)
const pluginNames = pluginUtils.clientPluginNames();
outerHTML.push(
'<style type="text/css" title="dynamicsyntax"></style>',
'<link rel="stylesheet" type="text/css" href="data:text/css,"/>',
scriptTag(outerScript),
'</head>',
'<body id="outerdocbody" class="outerdocbody ', pluginNames.join(' '), '">',
'<div id="sidediv" class="sidediv"><!-- --></div>',
'<div id="linemetricsdiv">x</div>',
'</body></html>');
const outerFrame = document.createElement('IFRAME');
outerFrame.name = 'ace_outer';
outerFrame.frameBorder = 0; // for IE
outerFrame.title = 'Ether';
info.frame = outerFrame;
document.getElementById(containerId).appendChild(outerFrame);
const editorDocument = outerFrame.contentWindow.document;
editorDocument.open();
editorDocument.write(outerHTML.join(''));
editorDocument.close();
2011-03-26 14:10:41 +01:00
};
2021-01-29 06:43:53 +01:00
};
2011-03-26 14:10:41 +01:00
2021-01-29 06:43:53 +01:00
Ace2Editor.registry = {
nextId: 1,
};
exports.Ace2Editor = Ace2Editor;