ace.js AMDification

This commit is contained in:
Egil Moeller 2015-04-12 18:10:17 +02:00
parent 2f12fc0229
commit 2472cd365e
3 changed files with 296 additions and 298 deletions

View file

@ -24,278 +24,277 @@
// requires: plugins // requires: plugins
// requires: undefined // requires: undefined
Ace2Editor.registry = { define(['ep_etherpad-lite/static/js/pluginfw/hooks', 'underscore'], function (hooks, _) {
nextId: 1 Ace2Editor.registry = {
}; nextId: 1
var hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks');
var _ = require('./underscore');
function scriptTag(source) {
return (
'<script type="text/javascript">\n'
+ source.replace(/<\//g, '<\\/') +
'</script>'
)
}
function Ace2Editor()
{
var ace2 = Ace2Editor;
var editor = {};
var info = {
editor: editor,
id: (ace2.registry.nextId++)
}; };
var loaded = false;
var actionsPendingInit = []; function scriptTag(source) {
return (
'<script type="text/javascript">\n'
+ source.replace(/<\//g, '<\\/') +
'</script>'
)
}
function pendingInit(func, optDoNow) function Ace2Editor()
{ {
return function() var ace2 = Ace2Editor;
{
var that = this; var editor = {};
var args = arguments; var info = {
var action = function() editor: editor,
{ id: (ace2.registry.nextId++)
func.apply(that, args);
}
if (optDoNow)
{
optDoNow.apply(that, args);
}
if (loaded)
{
action();
}
else
{
actionsPendingInit.push(action);
}
}; };
} var loaded = false;
function doActionsPendingInit() var actionsPendingInit = [];
{
_.each(actionsPendingInit, function(fn,i){
fn()
});
actionsPendingInit = [];
}
ace2.registry[info.id] = info; function pendingInit(func, optDoNow)
{
// The following functions (prefixed by 'ace_') are exposed by editor, but return function()
// execution is delayed until init is complete {
var aceFunctionsPendingInit = ['importText', 'importAText', 'focus', var that = this;
'setEditable', 'getFormattedCode', 'setOnKeyPress', 'setOnKeyDown', var args = arguments;
'setNotifyDirty', 'setProperty', 'setBaseText', 'setBaseAttributedText', var action = function()
'applyChangesToBase', 'applyPreparedChangesetToBase', {
'setUserChangeNotificationCallback', 'setAuthorInfo', func.apply(that, args);
'setAuthorSelectionRange', 'callWithAce', 'execCommand', 'replaceRange']; }
if (optDoNow)
_.each(aceFunctionsPendingInit, function(fnName,i){ {
var prefix = 'ace_'; optDoNow.apply(that, args);
var name = prefix + fnName; }
editor[fnName] = pendingInit(function(){ if (loaded)
info[prefix + fnName].apply(this, arguments); {
}); action();
}); }
else
editor.exportText = function() {
{ actionsPendingInit.push(action);
if (!loaded) return "(awaiting init)\n"; }
return info.ace_exportText(); };
};
editor.getFrame = function()
{
return info.frame || null;
};
editor.getDebugProperty = function(prop)
{
return info.ace_getDebugProperty(prop);
};
editor.getInInternationalComposition = function()
{
if (!loaded) return false;
return info.ace_getInInternationalComposition();
};
// 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.
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()}
return info.ace_getUnhandledErrors();
};
function pushStyleTagsFor(buffer, files) {
for (var i = 0, ii = files.length; i < ii; i++) {
var file = files[i];
buffer.push('<link rel="stylesheet" type="text/css" href="' + file + '"\/>');
} }
}
editor.destroy = pendingInit(function() function doActionsPendingInit()
{
info.ace_dispose();
info.frame.parentNode.removeChild(info.frame);
delete ace2.registry[info.id];
info = null; // prevent IE 6 closure memory leaks
});
editor.init = function(containerId, initialCode, doneFunc)
{
editor.importText(initialCode);
info.onEditorReady = function()
{ {
loaded = true; _.each(actionsPendingInit, function(fn,i){
doActionsPendingInit(); fn()
doneFunc(); });
actionsPendingInit = [];
}
ace2.registry[info.id] = info;
// The following functions (prefixed by 'ace_') are exposed by editor, but
// execution is delayed until init is complete
var aceFunctionsPendingInit = ['importText', 'importAText', 'focus',
'setEditable', 'getFormattedCode', 'setOnKeyPress', 'setOnKeyDown',
'setNotifyDirty', 'setProperty', 'setBaseText', 'setBaseAttributedText',
'applyChangesToBase', 'applyPreparedChangesetToBase',
'setUserChangeNotificationCallback', 'setAuthorInfo',
'setAuthorSelectionRange', 'callWithAce', 'execCommand', 'replaceRange'];
_.each(aceFunctionsPendingInit, function(fnName,i){
var prefix = 'ace_';
var name = prefix + fnName;
editor[fnName] = pendingInit(function(){
info[prefix + fnName].apply(this, arguments);
});
});
editor.exportText = function()
{
if (!loaded) return "(awaiting init)\n";
return info.ace_exportText();
}; };
(function() editor.getFrame = function()
{ {
var doctype = "<!doctype html>"; return info.frame || null;
};
var iframeHTML = []; editor.getDebugProperty = function(prop)
{
return info.ace_getDebugProperty(prop);
};
iframeHTML.push(doctype); editor.getInInternationalComposition = function()
iframeHTML.push("<html><head>"); {
if (!loaded) return false;
return info.ace_getInInternationalComposition();
};
var includedCSS = ["../static/css/iframe_editor.css", // prepareUserChangeset:
"../static/css/pad.css", // Returns null if no new changes or ACE not ready. Otherwise, bundles up all user changes
"../static/custom/pad.css"] // 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
var additionalCSS = _(hooks.callAll("aceEditorCSS")).map(function(path){ return '../static/plugins/' + path }); // at some later point to consider these changes part of the base, after which prepareUserChangeset
includedCSS = includedCSS.concat(additionalCSS); // 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.
editor.prepareUserChangeset = function()
{
if (!loaded) return null;
return info.ace_prepareUserChangeset();
};
pushStyleTagsFor(iframeHTML, includedCSS); editor.getUnhandledErrors = function()
{
if (!loaded) return [];
// returns array of {error: <browser Error object>, time: +new Date()}
return info.ace_getUnhandledErrors();
};
iframeHTML.push('<script type="text/javascript" src="../static/js/require-kernel.js"></script>'); function pushStyleTagsFor(buffer, files) {
iframeHTML.push(scriptTag('\n\ for (var i = 0, ii = files.length; i < ii; i++) {
require.setRootURI("../javascripts/src");\n\ var file = files[i];
require.setLibraryURI("../javascripts/lib");\n\ buffer.push('<link rel="stylesheet" type="text/css" href="' + file + '"\/>');
require.setGlobalKeyPath("require");\n\ }
')); }
iframeHTML.push('<script type="text/javascript" src="../static/plugins/requirejs/require.js"></script>'); editor.destroy = pendingInit(function()
{
info.ace_dispose();
info.frame.parentNode.removeChild(info.frame);
delete ace2.registry[info.id];
info = null; // prevent IE 6 closure memory leaks
});
iframeHTML.push(scriptTag('\n\ editor.init = function(containerId, initialCode, doneFunc)
var pathComponents = parent.parent.location.pathname.split("/");\n\ {
var baseURL = pathComponents.slice(0,pathComponents.length-2).join("/") + "/";\n\
requirejs.config({\n\ editor.importText(initialCode);
baseUrl: baseURL + "static/plugins",\n\
paths: {underscore: baseURL + "static/plugins/underscore/underscore"}\n\ info.onEditorReady = function()
});\n\ {
\n\ loaded = true;
requirejs(["ep_etherpad-lite/static/js/rjquery", "ep_etherpad-lite/static/js/pluginfw/client_plugins", "ep_etherpad-lite/static/js/ace2_inner"], function (j, plugins, Ace2Inner) {\n\ doActionsPendingInit();
jQuery = $ = window.jQuery = window.$ = j; // Expose jQuery #HACK\n\ doneFunc();
};
(function()
{
var doctype = "<!doctype html>";
var iframeHTML = [];
iframeHTML.push(doctype);
iframeHTML.push("<html><head>");
var includedCSS = ["../static/css/iframe_editor.css",
"../static/css/pad.css",
"../static/custom/pad.css"]
var additionalCSS = _(hooks.callAll("aceEditorCSS")).map(function(path){ return '../static/plugins/' + path });
includedCSS = includedCSS.concat(additionalCSS);
pushStyleTagsFor(iframeHTML, includedCSS);
iframeHTML.push('<script type="text/javascript" src="../static/js/require-kernel.js"></script>');
iframeHTML.push(scriptTag('\n\
require.setRootURI("../javascripts/src");\n\
require.setLibraryURI("../javascripts/lib");\n\
require.setGlobalKeyPath("require");\n\
'));
iframeHTML.push('<script type="text/javascript" src="../static/plugins/requirejs/require.js"></script>');
iframeHTML.push(scriptTag('\n\
var pathComponents = parent.parent.location.pathname.split("/");\n\
var baseURL = pathComponents.slice(0,pathComponents.length-2).join("/") + "/";\n\
requirejs.config({\n\
baseUrl: baseURL + "static/plugins",\n\
paths: {underscore: baseURL + "static/plugins/underscore/underscore"}\n\
});\n\
\n\ \n\
plugins.adoptPluginsFromAncestorsOf(window, function () {\n\ requirejs(["ep_etherpad-lite/static/js/rjquery", "ep_etherpad-lite/static/js/pluginfw/client_plugins", "ep_etherpad-lite/static/js/ace2_inner"], function (j, plugins, Ace2Inner) {\n\
var hooks = require("ep_etherpad-lite/static/js/pluginfw/hooks");\n\ jQuery = $ = window.jQuery = window.$ = j; // Expose jQuery #HACK\n\
hooks.plugins = plugins;\n\
\n\ \n\
plugins.ensure(function () {\n\ plugins.adoptPluginsFromAncestorsOf(window, function () {\n\
Ace2Inner.init();\n\ var hooks = require("ep_etherpad-lite/static/js/pluginfw/hooks");\n\
hooks.plugins = plugins;\n\
\n\
plugins.ensure(function () {\n\
Ace2Inner.init();\n\
});\n\
});\n\ });\n\
});\n\ });\n\
});\n\ '));
'));
iframeHTML.push('<style type="text/css" title="dynamicsyntax"></style>'); iframeHTML.push('<style type="text/css" title="dynamicsyntax"></style>');
hooks.callAll("aceInitInnerdocbodyHead", { hooks.callAll("aceInitInnerdocbodyHead", {
iframeHTML: iframeHTML iframeHTML: iframeHTML
}); });
iframeHTML.push('</head><body id="innerdocbody" role="application" class="syntax" spellcheck="false">&nbsp;</body></html>'); iframeHTML.push('</head><body id="innerdocbody" role="application" class="syntax" spellcheck="false">&nbsp;</body></html>');
// Expose myself to global for my child frame. // Expose myself to global for my child frame.
var thisFunctionsName = "ChildAccessibleAce2Editor"; var thisFunctionsName = "ChildAccessibleAce2Editor";
(function () {return this}())[thisFunctionsName] = Ace2Editor; (function () {return this}())[thisFunctionsName] = Ace2Editor;
var outerScript = '\ var outerScript = '\
editorId = ' + JSON.stringify(info.id) + ';\n\ editorId = ' + JSON.stringify(info.id) + ';\n\
editorInfo = parent[' + JSON.stringify(thisFunctionsName) + '].registry[editorId];\n\ editorInfo = parent[' + JSON.stringify(thisFunctionsName) + '].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\
var iframe = document.createElement("IFRAME");\n\ var iframe = document.createElement("IFRAME");\n\
iframe.name = "ace_inner";\n\ iframe.name = "ace_inner";\n\
iframe.title = "pad";\n\ iframe.title = "pad";\n\
iframe.scrolling = "no";\n\ iframe.scrolling = "no";\n\
var outerdocbody = document.getElementById("outerdocbody");\n\ var outerdocbody = document.getElementById("outerdocbody");\n\
iframe.frameBorder = 0;\n\ iframe.frameBorder = 0;\n\
iframe.allowTransparency = true; // for IE\n\ iframe.allowTransparency = true; // for IE\n\
outerdocbody.insertBefore(iframe, outerdocbody.firstChild);\n\ outerdocbody.insertBefore(iframe, outerdocbody.firstChild);\n\
iframe.ace_outerWin = window;\n\ iframe.ace_outerWin = window;\n\
readyFunc = function () {\n\ readyFunc = function () {\n\
editorInfo.onEditorReady();\n\ editorInfo.onEditorReady();\n\
readyFunc = null;\n\ readyFunc = null;\n\
editorInfo = null;\n\ editorInfo = null;\n\
};\n\ };\n\
var doc = iframe.contentWindow.document;\n\ var doc = iframe.contentWindow.document;\n\
doc.open();\n\ doc.open();\n\
var text = (' + JSON.stringify(iframeHTML.join('\n')) + ');\n\ var text = (' + JSON.stringify(iframeHTML.join('\n')) + ');\n\
doc.write(text);\n\ doc.write(text);\n\
doc.close();\n\ doc.close();\n\
}, 0);\n\ }, 0);\n\
}'; }';
var outerHTML = [doctype, '<html><head>'] var outerHTML = [doctype, '<html><head>']
var includedCSS = [ var includedCSS = [
"../static/css/iframe_editor.css", "../static/css/iframe_editor.css",
"../static/css/pad.css", "../static/css/pad.css",
"../static/custom/pad.css"]; "../static/custom/pad.css"];
var additionalCSS = _(hooks.callAll("aceEditorCSS")).map(function(path){ return '../static/plugins/' + path }); var additionalCSS = _(hooks.callAll("aceEditorCSS")).map(function(path){ return '../static/plugins/' + path });
includedCSS = includedCSS.concat(additionalCSS); includedCSS = includedCSS.concat(additionalCSS);
pushStyleTagsFor(outerHTML, includedCSS); pushStyleTagsFor(outerHTML, includedCSS);
// bizarrely, in FF2, a file with no "external" dependencies won't finish loading properly // bizarrely, in FF2, a file with no "external" dependencies won't finish loading properly
// (throbs busy while typing) // (throbs busy while typing)
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"><div id="sidediv"><!-- --></div><div id="linemetricsdiv">x</div></body></html>'); 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"><div id="sidediv"><!-- --></div><div id="linemetricsdiv">x</div></body></html>');
var outerFrame = document.createElement("IFRAME"); var outerFrame = document.createElement("IFRAME");
outerFrame.name = "ace_outer"; outerFrame.name = "ace_outer";
outerFrame.frameBorder = 0; // for IE outerFrame.frameBorder = 0; // for IE
outerFrame.title = "Ether"; outerFrame.title = "Ether";
info.frame = outerFrame; info.frame = outerFrame;
document.getElementById(containerId).appendChild(outerFrame); document.getElementById(containerId).appendChild(outerFrame);
var editorDocument = outerFrame.contentWindow.document; var editorDocument = outerFrame.contentWindow.document;
editorDocument.open(); editorDocument.open();
editorDocument.write(outerHTML.join('')); editorDocument.write(outerHTML.join(''));
editorDocument.close(); editorDocument.close();
})(); })();
}; };
return editor; return editor;
} }
exports.Ace2Editor = Ace2Editor; return {Ace2Editor: Ace2Editor};
});

View file

@ -474,7 +474,10 @@ var pad = {
// start the custom js // start the custom js
if (typeof customStart == "function") customStart(); if (typeof customStart == "function") customStart();
getParams(); getParams();
handshake();
padeditor.init(function () {
handshake();
}, pad.padOptions.view || {}, pad);
// To use etherpad you have to allow cookies. // To use etherpad you have to allow cookies.
// This will check if the creation of a test-cookie has success. // This will check if the creation of a test-cookie has success.
@ -525,12 +528,9 @@ var pad = {
padimpexp.init(this); padimpexp.init(this);
padsavedrevs.init(this); padsavedrevs.init(this);
padeditor.init(postAceInit, pad.padOptions.view || {}, this);
paduserlist.init(pad.myUserInfo, this); paduserlist.init(pad.myUserInfo, this);
padconnectionstatus.init(); padconnectionstatus.init();
padmodals.init(this); padmodals.init(this);
pad.collabClient = getCollabClient(padeditor.ace, clientVars.collab_client_vars, pad.myUserInfo, { pad.collabClient = getCollabClient(padeditor.ace, clientVars.collab_client_vars, pad.myUserInfo, {
colorPalette: pad.getColorPalette() colorPalette: pad.getColorPalette()
}, pad); }, pad);
@ -554,44 +554,41 @@ var pad = {
$("#chatloadmessagesbutton").css("display", "none"); $("#chatloadmessagesbutton").css("display", "none");
} }
function postAceInit() padeditbar.init();
setTimeout(function()
{ {
padeditbar.init(); padeditor.ace.focus();
setTimeout(function() }, 0);
{ if(padcookie.getPref("chatAlwaysVisible")){ // if we have a cookie for always showing chat then show it
padeditor.ace.focus(); chat.stickToScreen(true); // stick it to the screen
}, 0); $('#options-stickychat').prop("checked", true); // set the checkbox to on
if(padcookie.getPref("chatAlwaysVisible")){ // if we have a cookie for always showing chat then show it
chat.stickToScreen(true); // stick it to the screen
$('#options-stickychat').prop("checked", true); // set the checkbox to on
}
if(padcookie.getPref("chatAndUsers")){ // if we have a cookie for always showing chat then show it
chat.chatAndUsers(true); // stick it to the screen
$('#options-chatandusers').prop("checked", true); // set the checkbox to on
}
if(padcookie.getPref("showAuthorshipColors") == false){
pad.changeViewOption('showAuthorColors', false);
}
if(padcookie.getPref("showLineNumbers") == false){
pad.changeViewOption('showLineNumbers', false);
}
if(padcookie.getPref("rtlIsTrue") == true){
pad.changeViewOption('rtlIsTrue', true);
}
var fonts = ['useMonospaceFont', 'useOpenDyslexicFont', 'useComicSansFont', 'useCourierNewFont', 'useGeorgiaFont', 'useImpactFont',
'useLucidaFont', 'useLucidaSansFont', 'usePalatinoFont', 'useTahomaFont', 'useTimesNewRomanFont',
'useTrebuchetFont', 'useVerdanaFont', 'useSymbolFont', 'useWebdingsFont', 'useWingDingsFont', 'useSansSerifFont',
'useSerifFont'];
$.each(fonts, function(i, font){
if(padcookie.getPref(font) == true){
pad.changeViewOption(font, true);
}
})
hooks.aCallAll("postAceInit", {ace: padeditor.ace, pad: pad});
} }
if(padcookie.getPref("chatAndUsers")){ // if we have a cookie for always showing chat then show it
chat.chatAndUsers(true); // stick it to the screen
$('#options-chatandusers').prop("checked", true); // set the checkbox to on
}
if(padcookie.getPref("showAuthorshipColors") == false){
pad.changeViewOption('showAuthorColors', false);
}
if(padcookie.getPref("showLineNumbers") == false){
pad.changeViewOption('showLineNumbers', false);
}
if(padcookie.getPref("rtlIsTrue") == true){
pad.changeViewOption('rtlIsTrue', true);
}
var fonts = ['useMonospaceFont', 'useOpenDyslexicFont', 'useComicSansFont', 'useCourierNewFont', 'useGeorgiaFont', 'useImpactFont',
'useLucidaFont', 'useLucidaSansFont', 'usePalatinoFont', 'useTahomaFont', 'useTimesNewRomanFont',
'useTrebuchetFont', 'useVerdanaFont', 'useSymbolFont', 'useWebdingsFont', 'useWingDingsFont', 'useSansSerifFont',
'useSerifFont'];
$.each(fonts, function(i, font){
if(padcookie.getPref(font) == true){
pad.changeViewOption(font, true);
}
})
hooks.aCallAll("postAceInit", {ace: padeditor.ace, pad: pad});
}, },
dispose: function() dispose: function()
{ {

View file

@ -39,33 +39,35 @@ var padeditor = (function()
ace: null, ace: null,
// this is accessed directly from other files // this is accessed directly from other files
viewZoom: 100, viewZoom: 100,
init: function(readyFunc, initialViewOptions, _pad) init: function(readyFunc, initialViewOptions, _pad) {
{ requirejs(['ep_etherpad-lite/static/js/ace'], function (ace) {
Ace2Editor = require('./ace').Ace2Editor;
pad = _pad;
settings = pad.settings;
function aceReady() Ace2Editor = ace.Ace2Editor;
{ pad = _pad;
$("#editorloadingbox").hide(); settings = pad.settings;
if (readyFunc)
function aceReady()
{ {
readyFunc(); $("#editorloadingbox").hide();
if (readyFunc)
{
readyFunc();
}
} }
}
self.ace = new Ace2Editor(); self.ace = new Ace2Editor();
self.ace.init("editorcontainer", "", aceReady); self.ace.init("editorcontainer", "", aceReady);
self.ace.setProperty("wraps", true); self.ace.setProperty("wraps", true);
if (pad.getIsDebugEnabled()) if (pad.getIsDebugEnabled())
{ {
self.ace.setProperty("dmesg", pad.dmesg); self.ace.setProperty("dmesg", pad.dmesg);
} }
self.initViewOptions(); self.initViewOptions();
self.setViewOptions(initialViewOptions); self.setViewOptions(initialViewOptions);
// view bar // view bar
$("#viewbarcontents").show(); $("#viewbarcontents").show();
});
}, },
initViewOptions: function() initViewOptions: function()
{ {