Merge pull request #466 from fourplusone/cleanup-ace

Cleanup ace
This commit is contained in:
John McLear 2012-02-25 01:34:51 -08:00
commit 54da9fad73
8 changed files with 208 additions and 736 deletions

View file

@ -213,72 +213,6 @@ function _handle(req, res, jsFilename, jsFiles) {
}
}
// find all includes in ace.js and embed them.
function getAceFile(callback) {
fs.readFile(JS_DIR + 'ace.js', "utf8", function(err, data) {
if(ERR(err, callback)) return;
// Find all includes in ace.js and embed them
var founds = data.match(/\$\$INCLUDE_[a-zA-Z_]+\([a-zA-Z0-9.\/_"-]+\)/gi);
if (!settings.minify) {
founds = [];
}
founds.push('$$INCLUDE_JS("../static/js/require-kernel.js")');
data += ';\n';
data += 'Ace2Editor.EMBEDED = Ace2Editor.EMBEDED || {};\n';
//go trough all includes
async.forEach(founds, function (item, callback) {
var filename = item.match(/"([^"]*)"/)[1];
var type = item.match(/INCLUDE_([A-Z]+)/)[1];
var shortFilename = (filename.match(/^..\/static\/js\/(.*)$/, '')||[])[1];
//read the included files
if (shortFilename) {
if (shortFilename == 'require-kernel.js') {
// the kernel isnt actually on the file system.
handleEmbed(null, requireDefinition());
} else {
var contents = '';
tarCode(tar[shortFilename] || shortFilename
, function (content) {
contents += content;
}
, function () {
handleEmbed(null, contents);
}
);
}
} else {
fs.readFile(ROOT_DIR + filename, "utf8", handleEmbed);
}
function handleEmbed(error, data_) {
if (error) {
return; // Don't bother to include it.
}
if (settings.minify) {
if (type == "JS") {
try {
data_ = compressJS([data_]);
} catch (e) {
// Ignore, include uncompresseed, which will break in browser.
}
} else {
data_ = compressCSS([data_]);
}
}
data += 'Ace2Editor.EMBEDED[' + JSON.stringify(filename) + '] = '
+ JSON.stringify(data_) + ';\n';
callback();
}
}, function(error) {
callback(error, data);
});
});
}
exports.requireDefinition = requireDefinition;
function requireDefinition() {
return 'var require = ' + RequireKernel.kernelSource + ';\n';
@ -288,11 +222,7 @@ function tarCode(jsFiles, write, callback) {
write('require.define({');
var initialEntry = true;
async.forEach(jsFiles, function (filename, callback){
if (filename == 'ace.js') {
getAceFile(handleFile);
} else {
fs.readFile(JS_DIR + filename, "utf8", handleFile);
}
function handleFile(err, data) {
if(ERR(err, callback)) return;

View file

@ -170,34 +170,3 @@ p {
}
#overlaysdiv { position: absolute; left: -1000px; top: -1000px; }
/* ---------- Used by JavaScript Lexer ---------- */
.syntax .c { color: #bd3f00; font-style: italic } /* Comment */
.syntax .o { font-weight: bold; } /* Operator */
.syntax .p { font-weight: bold; } /* Punctuation */
.syntax .k { color: blue; } /* Keyword */
.syntax .kc { color: purple } /* Keyword.Constant */
.syntax .nx { } /* Name.Other */
.syntax .mf { color: purple } /* Literal.Number.Float */
.syntax .mh { color: purple } /* Literal.Number.Hex */
.syntax .mi { color: purple } /* Literal.Number.Integer */
.syntax .sr { color: purple } /* Literal.String.Regex */
.syntax .s2 { color: purple } /* Literal.String.Double */
.syntax .s1 { color: purple } /* Literal.String.Single */
.syntax .sd { color: purple } /* Literal.String.Doc */
.syntax .cs { color: #00aa33; font-weight: bold; font-style: italic } /* Comment.Special */
.syntax .err { color: #cc0000; font-weight: bold; text-decoration: underline; } /* Error */
/* css */
.syntax .nt { font-weight: bold; } /* tag */
.syntax .nc { color: #336; } /* class */
.syntax .nf { color: #336; } /* id */
.syntax .nd { color: #999; } /* :foo */
.syntax .m { color: purple } /* number */
.syntax .nb { color: purple } /* built-in */
.syntax .cp { color: #bd3f00; } /* !important */
.syntax .flash { background-color: #adf !important; }
.syntax .flashbad { background-color: #f55 !important; }

View file

@ -49,8 +49,7 @@ function Ace2Editor()
{
var that = this;
var args = arguments;
function action()
var action = function()
{
func.apply(that, args);
}
@ -71,78 +70,47 @@ function Ace2Editor()
function doActionsPendingInit()
{
for (var i = 0; i < actionsPendingInit.length; i++)
{
actionsPendingInit[i]();
}
$.each(actionsPendingInit, function(i,fn){
fn()
});
actionsPendingInit = [];
}
ace2.registry[info.id] = info;
editor.importText = pendingInit(function(newCode, undoable)
{
info.ace_importText(newCode, undoable);
// 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(i,fnName){
var prefix = 'ace_';
var name = prefix + fnName;
editor[fnName] = pendingInit(function(){
info[prefix + fnName].apply(this, arguments);
});
editor.importAText = pendingInit(function(newCode, apoolJsonObj, undoable)
{
info.ace_importAText(newCode, apoolJsonObj, undoable);
});
editor.exportText = function()
{
if (!loaded) return "(awaiting init)\n";
return info.ace_exportText();
};
editor.getFrame = function()
{
return info.frame || null;
};
editor.focus = pendingInit(function()
{
info.ace_focus();
});
editor.setEditable = pendingInit(function(newVal)
{
info.ace_setEditable(newVal);
});
editor.getFormattedCode = function()
{
return info.ace_getFormattedCode();
};
editor.setOnKeyPress = pendingInit(function(handler)
{
info.ace_setOnKeyPress(handler);
});
editor.setOnKeyDown = pendingInit(function(handler)
{
info.ace_setOnKeyDown(handler);
});
editor.setNotifyDirty = pendingInit(function(handler)
{
info.ace_setNotifyDirty(handler);
});
editor.setProperty = pendingInit(function(key, value)
{
info.ace_setProperty(key, value);
});
editor.getDebugProperty = function(prop)
{
return info.ace_getDebugProperty(prop);
};
editor.setBaseText = pendingInit(function(txt)
{
info.ace_setBaseText(txt);
});
editor.setBaseAttributedText = pendingInit(function(atxt, apoolJsonObj)
{
info.ace_setBaseAttributedText(atxt, apoolJsonObj);
});
editor.applyChangesToBase = pendingInit(function(changes, optAuthor, apoolJsonObj)
{
info.ace_applyChangesToBase(changes, optAuthor, apoolJsonObj);
});
// 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).
@ -157,24 +125,6 @@ function Ace2Editor()
if (!loaded) return null;
return info.ace_prepareUserChangeset();
};
editor.applyPreparedChangesetToBase = pendingInit(
function()
{
info.ace_applyPreparedChangesetToBase();
});
editor.setUserChangeNotificationCallback = pendingInit(function(callback)
{
info.ace_setUserChangeNotificationCallback(callback);
});
editor.setAuthorInfo = pendingInit(function(author, authorInfo)
{
info.ace_setAuthorInfo(author, authorInfo);
});
editor.setAuthorSelectionRange = pendingInit(function(author, start, end)
{
info.ace_setAuthorSelectionRange(author, start, end);
});
editor.getUnhandledErrors = function()
{
@ -183,86 +133,6 @@ function Ace2Editor()
return info.ace_getUnhandledErrors();
};
editor.callWithAce = pendingInit(function(fn, callStack, normalize)
{
return info.ace_callWithAce(fn, callStack, normalize);
});
editor.execCommand = pendingInit(function(cmd, arg1)
{
info.ace_execCommand(cmd, arg1);
});
editor.replaceRange = pendingInit(function(start, end, text)
{
info.ace_replaceRange(start, end, text);
});
function sortFilesByEmbeded(files) {
var embededFiles = [];
var remoteFiles = [];
if (Ace2Editor.EMBEDED) {
for (var i = 0, ii = files.length; i < ii; i++) {
var file = files[i];
if (Object.prototype.hasOwnProperty.call(Ace2Editor.EMBEDED, file)) {
embededFiles.push(file);
} else {
remoteFiles.push(file);
}
}
} else {
remoteFiles = files;
}
return {embeded: embededFiles, remote: remoteFiles};
}
function pushRequireScriptTo(buffer) {
var KERNEL_SOURCE = '../static/js/require-kernel.js';
var KERNEL_BOOT = 'require.setRootURI("../minified/");\nrequire.setGlobalKeyPath("require");'
if (Ace2Editor.EMBEDED && Ace2Editor.EMBEDED[KERNEL_SOURCE]) {
buffer.push('<script type="text/javascript">');
buffer.push(Ace2Editor.EMBEDED[KERNEL_SOURCE]);
buffer.push(KERNEL_BOOT);
buffer.push('<\/script>');
}
}
function pushScriptsTo(buffer) {
/* Folling is for packaging regular expression. */
/* $$INCLUDE_JS("../static/js/ace2_inner.js"); */
var ACE_SOURCE = '../static/js/ace2_inner.js';
if (Ace2Editor.EMBEDED && Ace2Editor.EMBEDED[ACE_SOURCE]) {
buffer.push('<script type="text/javascript">');
buffer.push(Ace2Editor.EMBEDED[ACE_SOURCE]);
buffer.push('require("/ace2_inner");');
buffer.push('<\/script>');
} else {
file = ACE_SOURCE;
file = file.replace(/^\.\.\/static\/js\//, '../minified/');
buffer.push('<script type="application/javascript" src="' + file + '"><\/script>');
buffer.push('<script type="text/javascript">');
buffer.push('require("/ace2_inner");');
buffer.push('<\/script>');
}
}
function pushStyleTagsFor(buffer, files) {
var sorted = sortFilesByEmbeded(files);
var embededFiles = sorted.embeded;
var remoteFiles = sorted.remote;
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, '<\\/'));
}
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="' + file + '"\/>');
}
}
editor.destroy = pendingInit(function()
{
info.ace_dispose();
@ -271,6 +141,8 @@ function Ace2Editor()
info = null; // prevent IE 6 closure memory leaks
});
editor.init = function(containerId, initialCode, doneFunc)
{
@ -283,6 +155,7 @@ function Ace2Editor()
doneFunc();
};
// This function builds the DOM structure of the editor which consists of two nested iFrames
(function()
{
var doctype = "<!doctype html>";
@ -303,49 +176,63 @@ function Ace2Editor()
iframeHTML[i] = JSON.parse(iframeHTML[i]);
}
// 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:
var includedCSS = [];
var $$INCLUDE_CSS = function(filename) {includedCSS.push(filename)};
$$INCLUDE_CSS("../static/css/iframe_editor.css");
$$INCLUDE_CSS("../static/css/pad.css");
$$INCLUDE_CSS("../static/custom/pad.css");
pushStyleTagsFor(iframeHTML, includedCSS);
var includedJS = [];
var $$INCLUDE_JS = function(filename) {includedJS.push(filename)};
pushRequireScriptTo(iframeHTML);
// Build HTML of editable iFrame
// Add Stylesheets to iFrame
iframeHTML.push('<link rel="stylesheet" type="text/css" href="../static/css/iframe_editor.css">');
iframeHTML.push('<link rel="stylesheet" type="text/css" href="../static/css/pad.css">');
iframeHTML.push('<link rel="stylesheet" type="text/css" href="../static/custom/pad.css">');
// Include Require Kernel and ace2_innner.js in iFrame;
iframeHTML.push('<script type="text/javascript" src="../static/js/require-kernel.js"></script>');
iframeHTML.push('<script type="text/javascript">');
// Configure reqire
iframeHTML.push('require.setRootURI("../minified/");');
iframeHTML.push('require.setGlobalKeyPath("require");');
// Inject my plugins into my child.
iframeHTML.push('\
<script type="text/javascript">\
require.define("/plugins", null);\n\
require.define("/plugins.js", function (require, exports, module) {\
module.exports = parent.parent.require("/plugins");\
});\
</script>\
');
pushScriptsTo(iframeHTML);
iframeHTML.push('require.define("/plugins", null);');
iframeHTML.push('require.define("/plugins.js", function (require, exports, module) {');
iframeHTML.push('module.exports = parent.parent.require("/plugins");');
iframeHTML.push('});');
iframeHTML.push('<\/script>');
// Require ace2
iframeHTML.push('<script type="text/javascript" src="../minified/ace2_inner.js"></script>');
iframeHTML.push('<script type="text/javascript">');
iframeHTML.push('require("/ace2_inner");');
iframeHTML.push('<\/script>');
iframeHTML.push('<style type="text/css" title="dynamicsyntax"></style>');
iframeHTML.push('</head><body id="innerdocbody" class="syntax" spellcheck="false">&nbsp;</body></html>');
editor.iframeHTML = iframeHTML.join('\n');
// Expose myself to global for my child frame.
var thisFunctionsName = "ChildAccessibleAce2Editor";
(function () {return this}())[thisFunctionsName] = Ace2Editor;
var outerScript = 'editorId = "' + info.id + '"; editorInfo = parent.' + thisFunctionsName + '.registry[editorId]; ' + 'window.onload = function() ' + '{ window.onload = null; setTimeout' + '(function() ' + '{ var iframe = document.createElement("IFRAME"); ' + 'iframe.scrolling = "no"; var outerdocbody = document.getElementById("outerdocbody"); ' + 'iframe.frameBorder = 0; iframe.allowTransparency = true; ' + // for IE
'outerdocbody.insertBefore(iframe, outerdocbody.firstChild); ' + 'iframe.ace_outerWin = window; ' + 'readyFunc = function() { editorInfo.onEditorReady(); readyFunc = null; editorInfo = null; }; ' + 'var doc = iframe.contentWindow.document; doc.open(); var text = (' + JSON.stringify(iframeHTML.join('\n')) + ');doc.write(text); doc.close(); ' + '}, 0); }';
var outerScript = 'editorId = "' + info.id + '"; editorInfo = parent.' + thisFunctionsName + '.registry[editorId]; ' +
'window.onload = function()' +
'{ window.onload = null; setTimeout' + '(function() ' +
'{ var iframe = document.createElement("IFRAME"); ' +
'iframe.scrolling = "no"; var outerdocbody = document.getElementById("outerdocbody"); ' +
'iframe.frameBorder = 0; iframe.allowTransparency = true; ' + // for IE
'outerdocbody.insertBefore(iframe, outerdocbody.firstChild); ' +
'iframe.ace_outerWin = window; ' +
'var doc = iframe.contentWindow.document; doc.open();doc.write(editorInfo.editor.iframeHTML); doc.close();'+
'readyFunc = function() { editorInfo.onEditorReady(); readyFunc = null; editorInfo = null; };' +
'}, 0); }';
var outerHTML = [doctype, '<html><head>']
var includedCSS = [];
var $$INCLUDE_CSS = function(filename) {includedCSS.push(filename)};
$$INCLUDE_CSS("../static/css/iframe_editor.css");
$$INCLUDE_CSS("../static/css/pad.css");
$$INCLUDE_CSS("../static/custom/pad.css");
pushStyleTagsFor(outerHTML, includedCSS);
// Build HTML of editor iFrame;
var outerHTML = [doctype, '<html><head>'];
outerHTML.push('<link rel="stylesheet" type="text/css" href="../static/css/iframe_editor.css">');
outerHTML.push('<link rel="stylesheet" type="text/css" href="../static/css/pad.css">');
outerHTML.push('<link rel="stylesheet" type="text/css" href="../static/custom/pad.css"');
// bizarrely, in FF2, a file with no "external" dependencies won't finish loading properly
// (throbs busy while typing)
@ -358,6 +245,7 @@ function Ace2Editor()
var editorDocument = outerFrame.contentWindow.document;
editorDocument.open();
editorDocument.write(outerHTML.join(''));
editorDocument.close();

View file

@ -141,6 +141,9 @@ function htmlPrettyEscape(str)
return Security.escapeHTML(str).replace(/\r?\n/g, '\\n');
}
var noop = function(){};
var identity = function(x){return x};
exports.isNodeText = isNodeText;
exports.object = object;
exports.extend = extend;
@ -155,3 +158,5 @@ exports.binarySearch = binarySearch;
exports.binarySearchInfinite = binarySearchInfinite;
exports.htmlPrettyEscape = htmlPrettyEscape;
exports.map = map;
exports.noop = noop;
exports.identity = identity;

View file

@ -21,6 +21,7 @@
*/
var Ace2Common = require('/ace2_common');
// Extract useful method defined in the other module.
var isNodeText = Ace2Common.isNodeText;
var object = Ace2Common.object;
@ -32,10 +33,10 @@ var isArray = Ace2Common.isArray;
var browser = Ace2Common.browser;
var getAssoc = Ace2Common.getAssoc;
var setAssoc = Ace2Common.setAssoc;
var binarySearch = Ace2Common.binarySearch;
var binarySearchInfinite = Ace2Common.binarySearchInfinite;
var htmlPrettyEscape = Ace2Common.htmlPrettyEscape;
var map = Ace2Common.map;
var noop = Ace2Common.noop;
var makeChangesetTracker = require('/changesettracker').makeChangesetTracker;
var colorutils = require('/colorutils').colorutils;
@ -49,9 +50,8 @@ var newSkipList = require('/skiplist').newSkipList;
var undoModule = require('/undomodule').undoModule;
var makeVirtualLineView = require('/virtual_lines').makeVirtualLineView;
function OUTER(gscope)
{
function Ace2Inner(){
var DEBUG = false; //$$ build script replaces the string "var DEBUG=true;//$$" with "var DEBUG=false;"
// changed to false
var isSetUp = false;
@ -122,13 +122,13 @@ function OUTER(gscope)
iframePadRight = 0;
var console = (DEBUG && window.console);
if (!window.console)
{
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
console = {};
for (var i = 0; i < names.length; ++i)
console[names[i]] = function()
{};
console[names[i]] = noop;
//console.error = function(str) { alert(str); };
}
@ -147,14 +147,6 @@ function OUTER(gscope)
};
}
function noop()
{}
function identity(x)
{
return x;
}
// "dmesg" is for displaying messages in the in-page output pane
// visible when "?djs=1" is appended to the pad URL. It generally
// remains a no-op unless djs is enabled, but we make a habit of
@ -338,7 +330,7 @@ function OUTER(gscope)
editorInfo.ace_getRep = function()
{
return rep;
}
};
var currentCallStack = null;
@ -460,12 +452,11 @@ function OUTER(gscope)
submitOldEvent(cs.editEvent);
if (cs.domClean && cs.type != "setup")
{
if (cs.isUserChange)
{
if (cs.repChanged) parenModule.notifyChange();
else parenModule.notifyTick();
}
recolorModule.recolorLines();
// if (cs.isUserChange)
// {
// if (cs.repChanged) parenModule.notifyChange();
// else parenModule.notifyTick();
// }
if (cs.selectionAffected)
{
updateBrowserSelectionFromRep();
@ -523,229 +514,6 @@ function OUTER(gscope)
return rep.lines.atOffset(charOffset).key;
}
var recolorModule = (function()
{
var dirtyLineKeys = {};
var module = {};
module.setCharNeedsRecoloring = function(offset)
{
if (offset >= rep.alltext.length)
{
offset = rep.alltext.length - 1;
}
dirtyLineKeys[getLineKeyForOffset(offset)] = true;
}
module.setCharRangeNeedsRecoloring = function(offset1, offset2)
{
if (offset1 >= rep.alltext.length)
{
offset1 = rep.alltext.length - 1;
}
if (offset2 >= rep.alltext.length)
{
offset2 = rep.alltext.length - 1;
}
var firstEntry = rep.lines.atOffset(offset1);
var lastKey = rep.lines.atOffset(offset2).key;
dirtyLineKeys[lastKey] = true;
var entry = firstEntry;
while (entry && entry.key != lastKey)
{
dirtyLineKeys[entry.key] = true;
entry = rep.lines.next(entry);
}
}
module.recolorLines = function()
{
for (var k in dirtyLineKeys)
{
recolorLineByKey(k);
}
dirtyLineKeys = {};
}
return module;
})();
var parenModule = (function()
{
var module = {};
module.notifyTick = function()
{
handleFlashing(false);
};
module.notifyChange = function()
{
handleFlashing(true);
};
module.shouldNormalizeOnChar = function(c)
{
if (parenFlashRep.active)
{
// avoid highlight style from carrying on to typed text
return true;
}
c = String.fromCharCode(c);
return !!(bracketMap[c]);
}
var parenFlashRep = {
active: false,
whichChars: null,
whichLineKeys: null,
expireTime: null
};
var bracketMap = {
'(': 1,
')': -1,
'[': 2,
']': -2,
'{': 3,
'}': -3
};
var bracketRegex = /[{}\[\]()]/g;
function handleFlashing(docChanged)
{
function getSearchRange(aroundLoc)
{
var rng = getVisibleCharRange();
var d = 100; // minimum radius
var e = 3000; // maximum radius;
if (rng[0] > aroundLoc - d) rng[0] = aroundLoc - d;
if (rng[0] < aroundLoc - e) rng[0] = aroundLoc - e;
if (rng[0] < 0) rng[0] = 0;
if (rng[1] < aroundLoc + d) rng[1] = aroundLoc + d;
if (rng[1] > aroundLoc + e) rng[1] = aroundLoc + e;
if (rng[1] > rep.lines.totalWidth()) rng[1] = rep.lines.totalWidth();
return rng;
}
function findMatchingVisibleBracket(startLoc, forwards)
{
var rng = getSearchRange(startLoc);
var str = rep.alltext.substring(rng[0], rng[1]);
var bstr = str.replace(bracketRegex, '('); // handy for searching
var loc = startLoc - rng[0];
var bracketState = [];
var foundParen = false;
var goodParen = false;
function nextLoc()
{
if (loc < 0) return;
if (forwards) loc++;
else loc--;
if (loc < 0 || loc >= str.length) loc = -1;
if (loc >= 0)
{
if (forwards) loc = bstr.indexOf('(', loc);
else loc = bstr.lastIndexOf('(', loc);
}
}
while ((!foundParen) && (loc >= 0))
{
if (getCharType(loc + rng[0]) == "p")
{
var b = bracketMap[str.charAt(loc)]; // -1, 1, -2, 2, -3, 3
var into = forwards;
var typ = b;
if (typ < 0)
{
into = !into;
typ = -typ;
}
if (into) bracketState.push(typ);
else
{
var recent = bracketState.pop();
if (recent != typ)
{
foundParen = true;
goodParen = false;
}
else if (bracketState.length == 0)
{
foundParen = true;
goodParen = true;
}
}
}
//console.log(bracketState.toSource());
if ((!foundParen) && (loc >= 0)) nextLoc();
}
if (!foundParen) return null;
return {
chr: (loc + rng[0]),
good: goodParen
};
}
var r = parenFlashRep;
var charsToHighlight = null;
var linesToUnhighlight = null;
if (r.active && (docChanged || (now() > r.expireTime)))
{
linesToUnhighlight = r.whichLineKeys;
r.active = false;
}
if ((!r.active) && docChanged && isCaret() && caretColumn() > 0)
{
var caret = caretDocChar();
if (caret > 0 && getCharType(caret - 1) == "p")
{
var charBefore = rep.alltext.charAt(caret - 1);
if (bracketMap[charBefore])
{
var lookForwards = (bracketMap[charBefore] > 0);
var findResult = findMatchingVisibleBracket(caret - 1, lookForwards);
if (findResult)
{
var mateLoc = findResult.chr;
var mateGood = findResult.good;
r.active = true;
charsToHighlight = {};
charsToHighlight[caret - 1] = 'flash';
charsToHighlight[mateLoc] = (mateGood ? 'flash' : 'flashbad');
r.whichLineKeys = [];
r.whichLineKeys.push(getLineKeyForOffset(caret - 1));
r.whichLineKeys.push(getLineKeyForOffset(mateLoc));
r.expireTime = now() + 4000;
newlyActive = true;
}
}
}
}
if (linesToUnhighlight)
{
recolorLineByKey(linesToUnhighlight[0]);
recolorLineByKey(linesToUnhighlight[1]);
}
if (r.active && charsToHighlight)
{
function f(txt, cls, next, ofst)
{
var flashClass = charsToHighlight[ofst];
if (cls)
{
next(txt, cls + " " + flashClass);
}
else next(txt, cls);
}
for (var c in charsToHighlight)
{
recolorLinesInRange((+c), (+c) + 1, null, f);
}
}
}
return module;
})();
function dispose()
{
disposed = true;
@ -779,7 +547,7 @@ function OUTER(gscope)
alineLength += o.chars;
if (opIter.hasNext())
{
if (o.lines != 0) error();
if (o.lines !== 0) error();
}
else
{
@ -1099,7 +867,7 @@ function OUTER(gscope)
var wrapper = function()
{
return fn(editorInfo);
}
};
@ -1110,7 +878,7 @@ function OUTER(gscope)
{
editorInfo.ace_fastIncorp(9);
wrapper1();
}
};
}
if (callStack !== undefined)
@ -1121,7 +889,7 @@ function OUTER(gscope)
{
return wrapper();
}
}
};
// This methed exposes a setter for some ace properties
// @param key the name of the parameter
@ -1163,7 +931,7 @@ function OUTER(gscope)
if(setter !== undefined){
setter(value)
}
}
};
editorInfo.ace_setBaseText = function(txt)
{
@ -1262,12 +1030,12 @@ function OUTER(gscope)
lastElapsed = elapsed;
return false;
}
}
};
isTimeUp.elapsed = function()
{
return now() - startTime;
}
};
return isTimeUp;
}
@ -1325,7 +1093,7 @@ function OUTER(gscope)
{
unschedule();
}
}
};
}
function fastIncorp(n)
@ -1517,7 +1285,7 @@ function OUTER(gscope)
}
var text = lineEntry.text;
var width = lineEntry.width; // text.length+1
if (text.length == 0)
if (text.length === 0)
{
// allow getLineStyleFilter to set line-div styles
var func = linestylefilter.getLineStyleFilter(
@ -1536,12 +1304,6 @@ function OUTER(gscope)
}
}
function getCharType(charIndex)
{
return '';
}
var observedChanges;
function clearObservedChanges()
@ -1650,8 +1412,7 @@ function OUTER(gscope)
var p = PROFILER("getSelection", false);
var selection = getSelection();
p.end();
if (selection)
{
function topLevel(n)
{
if ((!n) || n == root) return null;
@ -1661,6 +1422,9 @@ function OUTER(gscope)
}
return n;
}
if (selection)
{
var node1 = topLevel(selection.startPoint.node);
var node2 = topLevel(selection.endPoint.node);
if (node1) observeChangesAroundNode(node1);
@ -1733,7 +1497,7 @@ function OUTER(gscope)
{
a = dirtyRanges[j][0];
b = dirtyRanges[j][1];
if (!((a == 0 || getCleanNodeByKey(rep.lines.atIndex(a - 1).key)) && (b == rep.lines.length() || getCleanNodeByKey(rep.lines.atIndex(b).key))))
if (!((a === 0 || getCleanNodeByKey(rep.lines.atIndex(a - 1).key)) && (b == rep.lines.length() || getCleanNodeByKey(rep.lines.atIndex(b).key))))
{
dirtyRangesCheckOut = false;
break;
@ -1774,7 +1538,7 @@ function OUTER(gscope)
var range = dirtyRanges[i];
a = range[0];
b = range[1];
var firstDirtyNode = (((a == 0) && root.firstChild) || getCleanNodeByKey(rep.lines.atIndex(a - 1).key).nextSibling);
var firstDirtyNode = (((a === 0) && root.firstChild) || getCleanNodeByKey(rep.lines.atIndex(a - 1).key).nextSibling);
firstDirtyNode = (firstDirtyNode && isNodeDirty(firstDirtyNode) && firstDirtyNode);
var lastDirtyNode = (((b == rep.lines.length()) && root.lastChild) || getCleanNodeByKey(rep.lines.atIndex(b).key).previousSibling);
lastDirtyNode = (lastDirtyNode && isNodeDirty(lastDirtyNode) && lastDirtyNode);
@ -2072,7 +1836,7 @@ function OUTER(gscope)
function handleReturnIndentation()
{
// on return, indent to level of previous line
if (isCaret() && caretColumn() == 0 && caretLine() > 0)
if (isCaret() && caretColumn() === 0 && caretLine() > 0)
{
var lineNum = caretLine();
var thisLine = rep.lines.atIndex(lineNum);
@ -2154,10 +1918,10 @@ function OUTER(gscope)
var lineNode = lineEntry.lineNode;
var n = lineNode;
var after = false;
if (charsLeft == 0)
if (charsLeft === 0)
{
var index = 0;
if (browser.msie && line == (rep.lines.length() - 1) && lineNode.childNodes.length == 0)
if (browser.msie && line == (rep.lines.length() - 1) && lineNode.childNodes.length === 0)
{
// best to stay at end of last empty div in IE
index = 1;
@ -2221,7 +1985,7 @@ function OUTER(gscope)
// assuming the point is not in a dirty node.
if (point.node == root)
{
if (point.index == 0)
if (point.index === 0)
{
return [0, 0];
}
@ -2259,7 +2023,7 @@ function OUTER(gscope)
n = parNode;
}
}
if (n.id == "") console.debug("BAD");
if (n.id === "") console.debug("BAD");
if (n.firstChild && isBlockElement(n.firstChild))
{
col += 1; // lineMarker
@ -2484,7 +2248,7 @@ function OUTER(gscope)
function performDocumentReplaceCharRange(startChar, endChar, newText)
{
if (startChar == endChar && newText.length == 0)
if (startChar == endChar && newText.length === 0)
{
return;
}
@ -2501,7 +2265,7 @@ function OUTER(gscope)
endChar--;
newText = '\n' + newText.substring(0, newText.length - 1);
}
else if (newText.length == 0)
else if (newText.length === 0)
{
// a delete at end
startChar--;
@ -2519,8 +2283,8 @@ function OUTER(gscope)
function performDocumentReplaceRange(start, end, newText)
{
if (start == undefined) start = rep.selStart;
if (end == undefined) end = rep.selEnd;
if (start === undefined) start = rep.selStart;
if (end === undefined) end = rep.selEnd;
//dmesg(String([start.toSource(),end.toSource(),newText.toSource()]));
// start[0]: <--- start[1] --->CCCCCCCCCCC\n
@ -2760,7 +2524,7 @@ function OUTER(gscope)
spliceEnd--;
commonEnd++;
}
if (shortOldText.length == 0 && spliceStart == rep.alltext.length && shortNewText.length > 0)
if (shortOldText.length === 0 && spliceStart == rep.alltext.length && shortNewText.length > 0)
{
// inserting after final newline, bad
spliceStart--;
@ -2768,7 +2532,7 @@ function OUTER(gscope)
shortNewText = '\n' + shortNewText.slice(0, -1);
shiftFinalNewlineToBeforeNewText = true;
}
if (spliceEnd == rep.alltext.length && shortOldText.length > 0 && shortNewText.length == 0)
if (spliceEnd == rep.alltext.length && shortOldText.length > 0 && shortNewText.length === 0)
{
// deletion at end of rep.alltext
if (rep.alltext.charAt(spliceStart - 1) == '\n')
@ -2780,7 +2544,7 @@ function OUTER(gscope)
}
}
if (!(shortOldText.length == 0 && shortNewText.length == 0))
if (!(shortOldText.length === 0 && shortNewText.length === 0))
{
var oldDocText = rep.alltext;
var oldLen = oldDocText.length;
@ -2788,15 +2552,15 @@ function OUTER(gscope)
var spliceStartLine = rep.lines.indexOfOffset(spliceStart);
var spliceStartLineStart = rep.lines.offsetOfIndex(spliceStartLine);
function startBuilder()
var startBuilder = function()
{
var builder = Changeset.builder(oldLen);
builder.keep(spliceStartLineStart, spliceStartLine);
builder.keep(spliceStart - spliceStartLineStart);
return builder;
}
};
function eachAttribRun(attribs, func /*(startInNewText, endInNewText, attribs)*/ )
var eachAttribRun = function(attribs, func /*(startInNewText, endInNewText, attribs)*/ )
{
var attribsIter = Changeset.opIterator(attribs);
var textIndex = 0;
@ -2812,7 +2576,7 @@ function OUTER(gscope)
}
textIndex = nextIndex;
}
}
};
var justApplyStyles = (shortNewText == shortOldText);
var theChangeset;
@ -3012,7 +2776,7 @@ function OUTER(gscope)
var newEndIter = attribIterator(newARuns, true);
while (commonEnd < minLen)
{
if (commonEnd == 0)
if (commonEnd === 0)
{
// assume newline in common
oldEndIter();
@ -3155,10 +2919,11 @@ function OUTER(gscope)
lineClass = ''; // non-null to cause update
};
function writeClass()
var writeClass = function()
{
if (lineClass !== null) lineElem.className = lineClass;
}
};
result.prepareForAdd = writeClass;
result.finishUpdate = writeClass;
result.getInnerHTML = function()
@ -3385,7 +3150,7 @@ function OUTER(gscope)
}
}
if (N == 0)
if (N === 0)
{
p.cancel();
if (!isConsecutive(0))
@ -3517,16 +3282,18 @@ function OUTER(gscope)
idleWorkTimer.atMost(200);
});
function isLink(n)
{
return (n.tagName || '').toLowerCase() == "a" && n.href;
}
// only want to catch left-click
if ((!evt.ctrlKey) && (evt.button != 2) && (evt.button != 3))
{
// find A tag with HREF
function isLink(n)
{
return (n.tagName || '').toLowerCase() == "a" && n.href;
}
var n = evt.target;
while (n && n.parentNode && !isLink(n))
{
@ -3601,7 +3368,7 @@ function OUTER(gscope)
var firstLine, lastLine;
firstLine = rep.selStart[0];
lastLine = Math.max(firstLine, rep.selEnd[0] - ((rep.selEnd[1] == 0) ? 1 : 0));
lastLine = Math.max(firstLine, rep.selEnd[0] - ((rep.selEnd[1] === 0) ? 1 : 0));
var mods = [];
for (var n = firstLine; n <= lastLine; n++)
@ -3735,7 +3502,7 @@ function OUTER(gscope)
//separated. If it returns null, it means that the list was not cut, try
//from the current one.
var line = caretLine();
if(line != -1 && renumberList(line+1)==null)
if(line != -1 && renumberList(line+1) === null)
{
renumberList(line);
}
@ -3956,7 +3723,7 @@ function OUTER(gscope)
}
else if (type == "keypress")
{
if ((!specialHandled) && parenModule.shouldNormalizeOnChar(charCode))
if ((!specialHandled) && false /*parenModule.shouldNormalizeOnChar(charCode)*/)
{
idleWorkTimer.atMost(0);
}
@ -3973,7 +3740,7 @@ function OUTER(gscope)
}
// Is part of multi-keystroke international character on Firefox Mac
var isFirefoxHalfCharacter = (browser.mozilla && evt.altKey && charCode == 0 && keyCode == 0);
var isFirefoxHalfCharacter = (browser.mozilla && evt.altKey && charCode === 0 && keyCode === 0);
// Is part of multi-keystroke international character on Safari Mac
var isSafariHalfCharacter = (browser.safari && evt.altKey && keyCode == 229);
@ -4072,7 +3839,7 @@ function OUTER(gscope)
{
var text = entry.text;
var content;
if (text.length == 0)
if (text.length === 0)
{
content = '<span style="color: #aaa">--</span>';
}
@ -4138,27 +3905,27 @@ function OUTER(gscope)
var selectionParent = origSelectionRange.parentElement();
if (selectionParent.ownerDocument != doc) return null;
function newRange()
var newRange = function()
{
return doc.body.createTextRange();
}
};
function rangeForElementNode(nd)
var rangeForElementNode = function(nd)
{
var rng = newRange();
// doesn't work on text nodes
rng.moveToElementText(nd);
return rng;
}
};
function pointFromCollapsedRange(rng)
var pointFromCollapsedRange = function(rng)
{
var parNode = rng.parentElement();
var elemBelow = -1;
var elemAbove = parNode.childNodes.length;
var rangeWithin = rangeForElementNode(parNode);
if (rng.compareEndPoints("StartToStart", rangeWithin) == 0)
if (rng.compareEndPoints("StartToStart", rangeWithin) === 0)
{
return {
node: parNode,
@ -4166,7 +3933,7 @@ function OUTER(gscope)
maxIndex: 1
};
}
else if (rng.compareEndPoints("EndToEnd", rangeWithin) == 0)
else if (rng.compareEndPoints("EndToEnd", rangeWithin) === 0)
{
if (isBlockElement(parNode) && parNode.nextSibling)
{
@ -4184,7 +3951,7 @@ function OUTER(gscope)
maxIndex: 1
};
}
else if (parNode.childNodes.length == 0)
else if (parNode.childNodes.length === 0)
{
return {
node: parNode,
@ -4293,9 +4060,10 @@ function OUTER(gscope)
index: tn.nodeValue.length,
maxIndex: tn.nodeValue.length
};
}
};
var selection = {};
if (origSelectionRange.compareEndPoints("StartToEnd", origSelectionRange) == 0)
if (origSelectionRange.compareEndPoints("StartToEnd", origSelectionRange) === 0)
{
// collapsed
var pnt = pointFromCollapsedRange(origSelectionRange);
@ -4361,7 +4129,7 @@ function OUTER(gscope)
maxIndex: n.nodeValue.length
};
}
else if (childCount == 0)
else if (childCount === 0)
{
return {
node: n,
@ -4487,7 +4255,7 @@ function OUTER(gscope)
setCollapsedBefore(s, n);
s.move("character", point.index);
}
else if (point.index == 0)
else if (point.index === 0)
{
setCollapsedBefore(s, n);
}
@ -4575,7 +4343,7 @@ function OUTER(gscope)
while (p.node.childNodes.length > 0)
{
//&& (p.node == root || p.node.parentNode == root)) {
if (p.index == 0)
if (p.index === 0)
{
p.node = p.node.firstChild;
p.maxIndex = nodeMaxIndex(p.node);
@ -4678,7 +4446,7 @@ function OUTER(gscope)
function fixView()
{
// calling this method repeatedly should be fast
if (getInnerWidth() == 0 || getInnerHeight() == 0)
if (getInnerWidth() === 0 || getInnerHeight() === 0)
{
return;
}
@ -5097,7 +4865,7 @@ function OUTER(gscope)
}
if (!isNodeText(node))
{
if (index == 0) return leftOf(node);
if (index === 0) return leftOf(node);
else return rightOf(node);
}
else
@ -5378,7 +5146,7 @@ function OUTER(gscope)
var firstLine, lastLine;
firstLine = rep.selStart[0];
lastLine = Math.max(firstLine, rep.selEnd[0] - ((rep.selEnd[1] == 0) ? 1 : 0));
lastLine = Math.max(firstLine, rep.selEnd[0] - ((rep.selEnd[1] === 0) ? 1 : 0));
var allLinesAreList = true;
for (var n = firstLine; n <= lastLine; n++)
@ -5588,7 +5356,7 @@ function OUTER(gscope)
// move by "paragraph", a feature that Firefox lacks but IE and Safari both have
if (up)
{
if (focusCaret[1] == 0 && canChangeLines)
if (focusCaret[1] === 0 && canChangeLines)
{
focusCaret[0]--;
focusCaret[1] = 0;
@ -5885,9 +5653,7 @@ function OUTER(gscope)
}
}
}
}
OUTER(this);
exports.OUTER = OUTER; // This is probably unimportant.
exports.editor = new Ace2Inner();

View file

@ -26,47 +26,16 @@ var AttribPool = require('/AttributePoolFactory').createAttributePool;
var Changeset = require('/Changeset');
var linestylefilter = require('/linestylefilter').linestylefilter;
var colorutils = require('/colorutils').colorutils;
var Ace2Common = require('./ace2_common');
var map = Ace2Common.map;
var forEach = Ace2Common.forEach;
// These parameters were global, now they are injected. A reference to the
// Timeslider controller would probably be more appropriate.
function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, BroadcastSlider)
{
var changesetLoader = undefined;
// just in case... (todo: this must be somewhere else in the client code.)
// Below Array#map code was direct pasted by AppJet/Etherpad, licence unknown. Possible source: http://www.tutorialspoint.com/javascript/array_map.htm
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/ )
{
var len = this.length >>> 0;
if (typeof fun != "function") throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this) res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
// Below Array#forEach code was direct pasted by AppJet/Etherpad, licence unknown. Possible source: http://www.tutorialspoint.com/javascript/array_foreach.htm
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun /*, thisp*/ )
{
var len = this.length >>> 0;
if (typeof fun != "function") throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this) fun.call(thisp, this[i], i, this);
}
};
}
// Below Array#indexOf code was direct pasted by AppJet/Etherpad, licence unknown. Possible source: http://www.tutorialspoint.com/javascript/array_indexof.htm
if (!Array.prototype.indexOf)
@ -99,11 +68,6 @@ function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, Bro
}
}
function randomString()
{
return "_" + Math.floor(Math.random() * 1000000);
}
// for IE
if ($.browser.msie)
{
@ -115,7 +79,7 @@ function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, Bro
{}
}
var userId = "hiddenUser" + randomString();
var socketId;
//var socket;
var channelState = "DISCONNECTED";
@ -191,10 +155,7 @@ function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, Bro
// splice the lines
splice: function(start, numRemoved, newLinesVA)
{
var newLines = Array.prototype.slice.call(arguments, 2).map(
function(s)
{
var newLines = map(Array.prototype.slice.call(arguments, 2), function(s) {
return s;
});
@ -316,10 +277,13 @@ function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, Bro
padContents.currentTime += timeDelta * 1000;
debugLog('Time Delta: ', timeDelta)
updateTimer();
BroadcastSlider.setAuthors(padContents.getActiveAuthors().map(function(name)
var authors = map(padContents.getActiveAuthors(), function(name)
{
return authorData[name];
}));
});
BroadcastSlider.setAuthors(authors);
}
function updateTimer()
@ -419,10 +383,11 @@ function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, Bro
changesetLoader.queueUp(start, 1, update);
}
BroadcastSlider.setAuthors(padContents.getActiveAuthors().map(function(name)
{
var authors = map(padContents.getActiveAuthors(), function(name){
return authorData[name];
}));
});
BroadcastSlider.setAuthors(authors);
}
changesetLoader = {
@ -561,10 +526,12 @@ function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, Bro
var authorMap = {};
authorMap[obj.author] = obj.data;
receiveAuthorData(authorMap);
BroadcastSlider.setAuthors(padContents.getActiveAuthors().map(function(name)
{
var authors = map(padContents.getActiveAuthors(),function(name) {
return authorData[name];
}));
});
BroadcastSlider.setAuthors(authors);
}
else if (obj['type'] == "NEW_SAVEDREV")
{
@ -616,53 +583,6 @@ function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, Bro
}));
}
/*function setUpSocket()
{
// required for Comet
if ((!$.browser.msie) && (!($.browser.mozilla && $.browser.version.indexOf("1.8.") == 0)))
{
document.domain = document.domain; // for comet
}
var success = false;
callCatchingErrors("setUpSocket", function ()
{
appLevelDisconnectReason = null;
socketId = String(Math.floor(Math.random() * 1e12));
socket = new WebSocket(socketId);
socket.onmessage = wrapRecordingErrors("socket.onmessage", handleMessageFromServer);
socket.onclosed = wrapRecordingErrors("socket.onclosed", handleSocketClosed);
socket.onopen = wrapRecordingErrors("socket.onopen", function ()
{
setChannelState("CONNECTED");
var msg = {
type: "CLIENT_READY",
roomType: 'padview',
roomName: 'padview/' + clientVars.viewId,
data: {
lastRev: clientVars.revNum,
userInfo: {
userId: userId
}
}
};
sendMessage(msg);
});
// socket.onhiccup = wrapRecordingErrors("socket.onhiccup", handleCometHiccup);
// socket.onlogmessage = function(x) {debugLog(x); };
socket.connect();
success = true;
});
if (success)
{
//initialStartConnectTime = +new Date();
}
else
{
abandonConnection("initsocketfail");
}
}*/
function setChannelState(newChannelState, moreInfo)
{
@ -691,7 +611,7 @@ function loadBroadcastJS(socket, sendSocketMsg, fireWhenAllScriptsAreLoaded, Bro
window.onload = function ()
{
window['isloaded'] = true;
window['onloadFuncts'].forEach(function (funct)
forEach(window['onloadFuncts'],function (funct)
{
funct();
});

View file

@ -27,16 +27,13 @@
// requires: undefined
var Security = require('/security');
var Ace2Common = require('/ace2_common');
var plugins = require('/plugins').plugins;
var map = require('/ace2_common').map;
var map = Ace2Common.map;
var noop = Ace2Common.noop;
var identity = Ace2Common.identity;
var domline = {};
domline.noop = function()
{};
domline.identity = function(x)
{
return x;
};
domline.addToLineClass = function(lineClass, cls)
{
@ -60,11 +57,11 @@ domline.createDomLine = function(nonEmpty, doesWrap, optBrowser, optDocument)
{
var result = {
node: null,
appendSpan: domline.noop,
prepareForAdd: domline.noop,
notifyAdded: domline.noop,
clearSpans: domline.noop,
finishUpdate: domline.noop,
appendSpan: noop,
prepareForAdd: noop,
notifyAdded: noop,
clearSpans: noop,
finishUpdate: noop,
lineMarker: 0
};
@ -91,7 +88,7 @@ domline.createDomLine = function(nonEmpty, doesWrap, optBrowser, optDocument)
{
return domline.processSpaces(s, doesWrap);
}
var identity = domline.identity;
var perTextNodeProcess = (doesWrap ? identity : processSpaces);
var perHtmlLineProcess = (doesWrap ? processSpaces : identity);
var lineClass = 'ace-line';

View file

@ -21,7 +21,7 @@
*/
var noop = require('./ace2_common').noop;
function newSkipList()
@ -41,9 +41,6 @@ function newSkipList()
};
}
function noop()
{}
// if there are N elements in the skiplist, "start" is element -1 and "end" is element N
var start = {
key: null,