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

342 lines
11 KiB
JavaScript
Raw Normal View History

/**
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 KERNEL_SOURCE = '../static/js/require-kernel.js';
2011-07-07 19:59:34 +02:00
Ace2Editor.registry = {
2020-11-23 19:24:19 +01:00
nextId: 1,
2011-07-07 19:59:34 +02:00
};
2011-03-26 14:10:41 +01:00
2020-11-23 19:24:19 +01:00
const hooks = require('./pluginfw/hooks');
const pluginUtils = require('./pluginfw/shared');
const _ = require('./underscore');
function scriptTag(source) {
return (
2020-11-23 19:24:19 +01:00
`<script type="text/javascript">\n${
source.replace(/<\//g, '<\\/')
}</script>`
);
}
function Ace2Editor() {
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
const editor = {};
let info = {
editor,
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
function doActionsPendingInit() {
2020-11-23 19:24:19 +01:00
_.each(actionsPendingInit, (fn, i) => {
fn();
});
2011-03-26 14:10:41 +01:00
actionsPendingInit = [];
}
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
2020-11-23 19:24:19 +01:00
const aceFunctionsPendingInit = ['importText',
'importAText',
'focus',
'setEditable',
'getFormattedCode',
'setOnKeyPress',
'setOnKeyDown',
'setNotifyDirty',
'setProperty',
'setBaseText',
'setBaseAttributedText',
'applyChangesToBase',
'applyPreparedChangesetToBase',
'setUserChangeNotificationCallback',
'setAuthorInfo',
'setAuthorSelectionRange',
'callWithAce',
'execCommand',
'replaceRange'];
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.
editor[fnName] = pendingInit(function (...args) {
info[`ace_${fnName}`].apply(this, args);
});
}
2013-06-14 19:37:41 +02:00
2020-11-23 19:24:19 +01:00
editor.exportText = function () {
if (!loaded) return '(awaiting init)\n';
2011-03-26 14:10:41 +01:00
return info.ace_exportText();
};
2013-06-14 19:37:41 +02:00
2020-11-23 19:24:19 +01:00
editor.getFrame = function () {
2011-07-07 19:59:34 +02:00
return info.frame || null;
};
2013-06-14 19:37:41 +02:00
2020-11-23 19:24:19 +01:00
editor.getDebugProperty = function (prop) {
2011-07-07 19:59:34 +02:00
return info.ace_getDebugProperty(prop);
};
2020-11-23 19:24:19 +01:00
editor.getInInternationalComposition = function () {
if (!loaded) return false;
return info.ace_getInInternationalComposition();
};
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).
// 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.
2020-11-23 19:24:19 +01:00
editor.prepareUserChangeset = function () {
2011-07-07 19:59:34 +02:00
if (!loaded) return null;
2011-03-26 14:10:41 +01:00
return info.ace_prepareUserChangeset();
};
2020-11-23 19:24:19 +01:00
editor.getUnhandledErrors = function () {
2011-07-07 19:59:34 +02:00
if (!loaded) return [];
2011-03-26 14:10:41 +01:00
// returns array of {error: <browser Error object>, time: +new Date()}
return info.ace_getUnhandledErrors();
};
2012-01-15 09:05:26 +01:00
function 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};
}
2012-01-15 09:05:26 +01:00
function 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">');
for (var i = 0, ii = embededFiles.length; i < ii; i++) {
var file = embededFiles[i];
buffer.push((Ace2Editor.EMBEDED[file] || '').replace(/<\//g, '<\\/'));
2012-01-15 09:05:26 +01:00
}
buffer.push('<\/style>');
}
for (var i = 0, ii = remoteFiles.length; i < ii; i++) {
var file = remoteFiles[i];
2020-11-23 19:24:19 +01:00
buffer.push(`<link rel="stylesheet" type="text/css" href="${encodeURI(file)}"\/>`);
2012-01-15 09:05:26 +01:00
}
}
2011-03-26 14:10:41 +01:00
2020-11-23 19:24:19 +01:00
editor.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
});
2020-11-23 19:24:19 +01:00
editor.init = function (containerId, initialCode, doneFunc) {
2011-03-26 14:10:41 +01:00
editor.importText(initialCode);
2020-11-23 19:24:19 +01:00
info.onEditorReady = function () {
2011-03-26 14:10:41 +01:00
loaded = true;
doActionsPendingInit();
doneFunc();
};
2020-11-23 19:24:19 +01:00
(function () {
const doctype = '<!doctype html>';
2011-03-26 14:10:41 +01:00
2020-11-23 19:24:19 +01:00
const iframeHTML = [];
2011-07-07 19:59:34 +02:00
2012-01-15 08:31:23 +01:00
iframeHTML.push(doctype);
2020-11-23 19:24:19 +01:00
iframeHTML.push(`<html class='inner-editor ${clientVars.skinVariants}'><head>`);
2012-01-15 08:31:23 +01:00
2012-01-15 09:05:26 +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.
2013-06-14 19:37:41 +02:00
// these lines must conform to a specific format because they are passed by the build script:
2012-01-15 09:05:26 +01:00
var includedCSS = [];
2020-11-23 19:24:19 +01:00
var $$INCLUDE_CSS = function (filename) { includedCSS.push(filename); };
$$INCLUDE_CSS('../static/css/iframe_editor.css');
2016-05-20 15:42:05 +02:00
// disableCustomScriptsAndStyles can be used to disable loading of custom scripts
2020-11-23 19:24:19 +01:00
if (!clientVars.disableCustomScriptsAndStyles) {
$$INCLUDE_CSS(`../static/css/pad.css?v=${clientVars.randomVersionString}`);
2016-05-20 15:42:05 +02:00
}
2013-06-14 19:37:41 +02:00
2020-11-23 19:24:19 +01:00
var additionalCSS = _(hooks.callAll('aceEditorCSS')).map((path) => {
if (path.match(/\/\//)) { // Allow urls to external CSS - http(s):// and //some/path.css
return path;
}
2020-11-23 19:24:19 +01:00
return `../static/plugins/${path}`;
});
2012-04-07 01:40:13 +02:00
includedCSS = includedCSS.concat(additionalCSS);
2020-11-23 19:24:19 +01:00
$$INCLUDE_CSS(`../static/skins/${clientVars.skinName}/pad.css?v=${clientVars.randomVersionString}`);
2013-06-14 19:37:41 +02:00
2012-01-15 09:05:26 +01:00
pushStyleTagsFor(iframeHTML, includedCSS);
if (!Ace2Editor.EMBEDED && Ace2Editor.EMBEDED[KERNEL_SOURCE]) {
// Remotely src'd script tag will not work in IE; it must be embedded, so
// throw an error if it is not.
2020-11-23 19:24:19 +01:00
throw new Error('Require kernel could not be found.');
}
iframeHTML.push(scriptTag(
2020-11-23 19:24:19 +01:00
`${Ace2Editor.EMBEDED[KERNEL_SOURCE]}\n\
require.setRootURI("../javascripts/src");\n\
require.setLibraryURI("../javascripts/lib");\n\
require.setGlobalKeyPath("require");\n\
\n\
var plugins = require("ep_etherpad-lite/static/js/pluginfw/client_plugins");\n\
plugins.adoptPluginsFromAncestorsOf(window);\n\
\n\
$ = jQuery = require("ep_etherpad-lite/static/js/rjquery").jQuery; // Expose jQuery #HACK\n\
var Ace2Inner = require("ep_etherpad-lite/static/js/ace2_inner");\n\
\n\
plugins.ensure(function () {\n\
Ace2Inner.init();\n\
});\n\
2020-11-23 19:24:19 +01:00
`));
2011-07-07 19:59:34 +02:00
2012-01-15 08:31:23 +01:00
iframeHTML.push('<style type="text/css" title="dynamicsyntax"></style>');
2020-11-23 19:24:19 +01:00
hooks.callAll('aceInitInnerdocbodyHead', {
iframeHTML,
});
iframeHTML.push('</head><body id="innerdocbody" class="innerdocbody" role="application" class="syntax" spellcheck="false">&nbsp;</body></html>');
2011-03-26 14:10:41 +01:00
// eslint-disable-next-line node/no-unsupported-features/es-builtins
const gt = typeof globalThis === 'object' ? globalThis : window;
gt.ChildAccessibleAce2Editor = Ace2Editor;
2020-11-23 19:24:19 +01:00
const outerScript = `\
editorId = ${JSON.stringify(info.id)};\n\
editorInfo = parent.ChildAccessibleAce2Editor.registry[editorId];\n\
window.onload = function () {\n\
window.onload = null;\n\
setTimeout(function () {\n\
var iframe = document.createElement("IFRAME");\n\
iframe.name = "ace_inner";\n\
iframe.title = "pad";\n\
iframe.scrolling = "no";\n\
var outerdocbody = document.getElementById("outerdocbody");\n\
iframe.frameBorder = 0;\n\
iframe.allowTransparency = true; // for IE\n\
outerdocbody.insertBefore(iframe, outerdocbody.firstChild);\n\
iframe.ace_outerWin = window;\n\
readyFunc = function () {\n\
editorInfo.onEditorReady();\n\
readyFunc = null;\n\
editorInfo = null;\n\
};\n\
var doc = iframe.contentWindow.document;\n\
doc.open();\n\
2020-11-23 19:24:19 +01:00
var text = (${JSON.stringify(iframeHTML.join('\n'))});\n\
doc.write(text);\n\
doc.close();\n\
}, 0);\n\
2020-11-23 19:24:19 +01:00
}`;
2011-07-07 19:59:34 +02:00
2020-11-23 19:24:19 +01:00
const outerHTML = [doctype, `<html class="inner-editor outerdoc ${clientVars.skinVariants}"><head>`];
2012-01-15 09:05:26 +01:00
var includedCSS = [];
2020-11-23 19:24:19 +01:00
var $$INCLUDE_CSS = function (filename) { includedCSS.push(filename); };
$$INCLUDE_CSS('../static/css/iframe_editor.css');
$$INCLUDE_CSS(`../static/css/pad.css?v=${clientVars.randomVersionString}`);
2013-06-14 19:37:41 +02:00
2020-11-23 19:24:19 +01:00
var additionalCSS = _(hooks.callAll('aceEditorCSS')).map((path) => {
if (path.match(/\/\//)) { // Allow urls to external CSS - http(s):// and //some/path.css
return path;
}
2020-11-23 19:24:19 +01:00
return `../static/plugins/${path}`;
2020-12-16 22:51:43 +01:00
}
);
2012-04-07 01:40:13 +02:00
includedCSS = includedCSS.concat(additionalCSS);
2020-11-23 19:24:19 +01:00
$$INCLUDE_CSS(`../static/skins/${clientVars.skinName}/pad.css?v=${clientVars.randomVersionString}`);
2013-06-14 19:37:41 +02:00
2012-01-15 09:05:26 +01:00
pushStyleTagsFor(outerHTML, includedCSS);
2011-07-07 19:59:34 +02:00
// bizarrely, in FF2, a file with no "external" dependencies won't finish loading properly
// (throbs busy while typing)
2020-11-23 19:24:19 +01:00
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>');
2011-07-07 19:59:34 +02:00
2020-11-23 19:24:19 +01:00
const outerFrame = document.createElement('IFRAME');
outerFrame.name = 'ace_outer';
2011-03-26 14:10:41 +01:00
outerFrame.frameBorder = 0; // for IE
2020-11-23 19:24:19 +01:00
outerFrame.title = 'Ether';
2011-03-26 14:10:41 +01:00
info.frame = outerFrame;
document.getElementById(containerId).appendChild(outerFrame);
2020-11-23 19:24:19 +01:00
const editorDocument = outerFrame.contentWindow.document;
2011-03-26 14:10:41 +01:00
editorDocument.open();
editorDocument.write(outerHTML.join(''));
editorDocument.close();
})();
};
return editor;
}
exports.Ace2Editor = Ace2Editor;