cryptpad/www/code/main.js

655 lines
25 KiB
JavaScript
Raw Normal View History

require.config({ paths: { 'json.sortify': '/bower_components/json.sortify/dist/JSON.sortify' } });
define([
'/api/config?cb=' + Math.random().toString(16).substring(2),
2016-07-12 13:52:36 +00:00
'/customize/messages.js',
2016-06-06 10:14:07 +00:00
'/bower_components/chainpad-crypto/crypto.js',
'/bower_components/chainpad-netflux/chainpad-netflux.js',
'/bower_components/textpatcher/TextPatcher.amd.js',
'/common/toolbar.js',
'json.sortify',
2016-06-06 10:14:07 +00:00
'/bower_components/chainpad-json-validator/json-ot.js',
2016-06-21 13:17:09 +00:00
'/common/cryptpad-common.js',
'/code/modes.js',
2016-06-29 09:51:53 +00:00
'/code/themes.js',
'/common/visible.js',
'/common/notify.js',
'/bower_components/file-saver/FileSaver.min.js',
2016-04-27 13:43:31 +00:00
'/bower_components/jquery/dist/jquery.min.js',
'/customize/pad.js'
], function (Config, /*RTCode,*/ Messages, Crypto, Realtime, TextPatcher, Toolbar, JSONSortify, JsonOT, Cryptpad, Modes, Themes, Visible, Notify) {
var $ = window.jQuery;
var saveAs = window.saveAs;
var module = window.APP = {
Cryptpad: Cryptpad,
spinner: Cryptpad.spinner(document.body),
};
module.spinner.show();
var ifrw = module.ifrw = $('#pad-iframe')[0].contentWindow;
var stringify = function (obj) {
return JSONSortify(obj);
};
$(function () {
var userName = Crypto.rand64(8),
toolbar;
2016-04-22 22:15:39 +00:00
2016-06-21 13:17:09 +00:00
var secret = Cryptpad.getSecrets();
var andThen = function (CMeditor) {
var CodeMirror = module.CodeMirror = CMeditor;
2016-06-23 10:44:30 +00:00
CodeMirror.modeURL = "/code/codemirror-5.16.0/mode/%N/%N.js";
2016-04-22 22:15:39 +00:00
var $pad = $('#pad-iframe');
var $textarea = $pad.contents().find('#editor1');
var editor = module.editor = CMeditor.fromTextArea($textarea[0], {
lineNumbers: true,
lineWrapping: true,
autoCloseBrackets: true,
matchBrackets : true,
showTrailingSpace : true,
styleActiveLine : true,
search: true,
highlightSelectionMatches: {showToken: /\w+/},
extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }},
foldGutter: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
mode: "javascript",
readOnly: true
});
2016-06-29 09:51:53 +00:00
var setMode = module.setMode = function (mode, $select) {
module.highlightMode = mode;
2016-06-23 14:37:51 +00:00
if (mode === 'text') {
editor.setOption('mode', 'text');
return;
}
CodeMirror.autoLoadMode(editor, mode);
editor.setOption('mode', mode);
2016-06-30 12:47:37 +00:00
if ($select && $select.val) { $select.val(mode); }
};
2016-07-11 15:36:53 +00:00
editor.setValue(Messages.codeInitialState); // HERE
2016-06-29 09:51:53 +00:00
var setTheme = module.setTheme = (function () {
var path = './theme/';
var $head = $(ifrw.document.head);
var themeLoaded = module.themeLoaded = function (theme) {
return $head.find('link[href*="'+theme+'"]').length;
};
var loadTheme = module.loadTheme = function (theme) {
$head.append($('<link />', {
rel: 'stylesheet',
href: path + theme + '.css',
}));
};
return function (theme, $select) {
if (!theme) {
editor.setOption('theme', 'default');
} else {
if (!themeLoaded(theme)) {
loadTheme(theme);
}
editor.setOption('theme', theme);
}
2016-06-29 10:00:12 +00:00
if ($select && $select.val) { $select.val(theme || 'default'); }
2016-06-29 09:51:53 +00:00
};
}());
var setEditable = module.setEditable = function (bool) {
editor.setOption('readOnly', !bool);
};
var userList = {}; // List of pretty name of all users (mapped with their server ID)
var toolbarList; // List of users still connected to the channel (server IDs)
var addToUserList = function(data) {
for (var attrname in data) { userList[attrname] = data[attrname]; }
if(toolbarList && typeof toolbarList.onChange === "function") {
toolbarList.onChange(userList);
}
};
var myData = {};
var myUserName = ''; // My "pretty name"
var myID; // My server ID
var setMyID = function(info) {
myID = info.myID || null;
myUserName = myID;
};
2016-05-20 11:39:40 +00:00
var config = {
//initialState: Messages.codeInitialState,
userName: userName,
websocketURL: Config.websocketURL,
2016-06-21 13:17:09 +00:00
channel: secret.channel,
//cryptKey: key,
crypto: Crypto.createEncryptor(secret.key),
2016-05-20 11:39:40 +00:00
setMyID: setMyID,
transformFunction: JsonOT.validate
};
var canonicalize = function (t) { return t.replace(/\r\n/g, '\n'); };
var initializing = true;
var onLocal = config.onLocal = function () {
if (initializing) { return; }
editor.save();
var textValue = canonicalize($textarea.val());
var obj = {content: textValue};
// append the userlist to the hyperjson structure
obj.metadata = userList;
// set mode too...
obj.highlightMode = module.highlightMode;
2016-05-20 11:39:40 +00:00
// stringify the json and send it into chainpad
var shjson = stringify(obj);
module.patchText(shjson);
if (module.realtime.getUserDoc() !== shjson) {
console.error("realtime.getUserDoc() !== shjson");
}
};
var setName = module.setName = function (newName) {
if (!(typeof(newName) === 'string' && newName.trim())) { return; }
var myUserNameTemp = newName.trim();
if(newName.trim().length > 32) {
myUserNameTemp = myUserNameTemp.substr(0, 32);
}
myUserName = myUserNameTemp;
myData[myID] = {
name: myUserName
};
addToUserList(myData);
Cryptpad.setPadAttribute('username', myUserName, function (err, data) {
if (err) {
console.log("Couldn't set username");
console.error(err);
return;
}
onLocal();
});
};
var getLastName = function (cb) {
Cryptpad.getPadAttribute('username', function (err, userName) {
cb(err, userName || '');
});
};
var createChangeName = function(id, $container) {
var buttonElmt = $container.find('#'+id)[0];
getLastName(function (err, lastName) {
buttonElmt.addEventListener("click", function() {
Cryptpad.prompt(Messages.changeNamePrompt, lastName, function (newName) {
setName(newName);
});
2016-07-07 10:47:23 +00:00
});
});
};
var getHeadingText = function () {
var lines = editor.getValue().split(/\n/);
2016-07-20 10:26:57 +00:00
var text = '';
lines.some(function (line) {
// lisps?
var lispy = /^\s*(;|#\|)(.*?)$/;
if (lispy.test(line)) {
line.replace(lispy, function (a, one, two) {
text = two;
});
return true;
}
// lines beginning with a hash are potentially valuable
// works for markdown, python, bash, etc.
var hash = /^#(.*?)$/;
if (hash.test(line)) {
line.replace(hash, function (a, one) {
text = one;
});
return true;
}
// lines including a c-style comment are also valuable
var clike = /^\s*(\/\*|\/\/)(.*?)(\*\/)$/;
if (clike.test(line)) {
line.replace(clike, function (a, one, two) {
text = two;
});
return true;
}
});
return text.trim();
};
var suggestName = function () {
var hash = window.location.hash.slice(1, 9);
if (document.title === hash) {
return getHeadingText() || hash;
} else {
return document.title || getHeadingText() || hash;
}
};
var exportText = module.exportText = function () {
var text = editor.getValue();
var ext = Modes.extensionOf(module.highlightMode);
var title = Cryptpad.fixFileName(suggestName()) + ext;
Cryptpad.prompt(Messages.exportPrompt, title, function (filename) {
if (filename === null) { return; }
var blob = new Blob([text], {
type: 'text/plain;charset=utf-8'
});
saveAs(blob, filename);
});
};
2016-04-22 22:15:39 +00:00
var onInit = config.onInit = function (info) {
var $bar = $('#pad-iframe')[0].contentWindow.$('#cme_toolbox');
toolbarList = info.userList;
var config = {
userData: userList,
changeNameID: Toolbar.constants.changeName,
};
toolbar = module.toolbar = Toolbar.create($bar, info.myID, info.realtime, info.getLag, info.userList, config);
createChangeName(Toolbar.constants.changeName, $bar);
2016-06-29 10:00:12 +00:00
var $rightside = $bar.find('.' + Toolbar.constants.rightside);
/* add an export button */
2016-07-16 10:38:21 +00:00
var $export = $('<button>', {
title: Messages.exportButtonTitle,
})
2016-07-11 15:36:53 +00:00
.text(Messages.exportButton)
.addClass('rightside-button')
.click(exportText);
$rightside.append($export);
/* add an import button */
2016-07-16 10:38:21 +00:00
var $import = $('<button>',{
title: Messages.importButtonTitle
})
2016-07-11 15:36:53 +00:00
.text(Messages.importButton)
.addClass('rightside-button')
2016-06-23 14:37:51 +00:00
.click(Cryptpad.importContent('text/plain', function (content, file) {
var mode;
2016-06-23 14:37:51 +00:00
var mime = CodeMirror.findModeByMIME(file.type);
if (!mime) {
2016-08-05 13:55:00 +00:00
var ext = /.+\.([^.]+)$/.exec(file.name);
if (ext[1]) {
mode = CodeMirror.findModeByExtension(ext[1]);
}
} else {
mode = mime && mime.mode || null;
}
2016-06-23 14:37:51 +00:00
if (mode && Modes.list.some(function (o) { return o.mode === mode; })) {
2016-06-23 14:37:51 +00:00
setMode(mode);
$bar.find('#language-mode').val(mode);
} else {
console.log("Couldn't find a suitable highlighting mode: %s", mode);
setMode('text');
$bar.find('#language-mode').val('text');
}
editor.setValue(content);
2016-06-23 14:37:51 +00:00
onLocal();
}));
$rightside.append($import);
/* add a rename button */
2016-06-30 08:51:19 +00:00
var $setTitle = $('<button>', {
2016-07-16 10:38:21 +00:00
id: 'name-pad',
title: Messages.renameButtonTitle,
2016-06-30 08:51:19 +00:00
})
.addClass('rightside-button')
2016-07-11 15:36:53 +00:00
.text(Messages.renameButton)
2016-06-30 08:51:19 +00:00
.click(function () {
var suggestion = suggestName();
2016-07-11 15:36:53 +00:00
Cryptpad.prompt(Messages.renamePrompt,
suggestion, function (title, ev) {
2016-07-07 10:47:23 +00:00
if (title === null) { return; }
Cryptpad.causesNamingConflict(title, function (err, conflicts) {
if (err) {
console.log("Unable to determine if name caused a conflict");
console.error(err);
return;
}
if (conflicts) {
Cryptpad.alert(Messages.renameConflict);
return;
}
Cryptpad.setPadTitle(title, function (err, data) {
if (err) {
console.log("unable to set pad title");
console.log(err);
return;
}
document.title = title;
});
});
2016-07-07 10:47:23 +00:00
});
2016-06-30 08:51:19 +00:00
});
$rightside.append($setTitle);
/* add a forget button */
var $forgetPad = $('<button>', {
id: 'cryptpad-forget',
2016-07-16 10:38:21 +00:00
title: Messages.forgetButtonTitle,
})
2016-07-11 15:36:53 +00:00
.text(Messages.forgetButton)
.addClass('cryptpad-forget rightside-button')
.click(function () {
var href = window.location.href;
2016-07-11 15:36:53 +00:00
Cryptpad.confirm(Messages.forgetPrompt, function (yes) {
2016-07-07 10:47:23 +00:00
if (!yes) { return; }
Cryptpad.forgetPad(href, function (err, data) {
if (err) {
console.log("unable to forget pad");
console.error(err);
return;
}
document.title = window.location.hash.slice(1,9);
});
2016-07-07 10:47:23 +00:00
});
});
$rightside.append($forgetPad);
2016-06-30 08:51:19 +00:00
var configureLanguage = function (cb) {
// FIXME this is async so make it happen as early as possible
/* Let the user select different syntax highlighting modes */
var $language = module.$language = $('<select>', {
title: 'syntax highlighting',
id: 'language-mode',
}).on('change', function () {
setMode($language.val());
onLocal();
});
Modes.list.map(function (o) {
$language.append($('<option>', {
value: o.mode,
}).text(o.language));
});
$rightside.append($language);
cb();
};
var configureTheme = function () {
/* Remember the user's last choice of theme using localStorage */
var themeKey = 'CRYPTPAD_CODE_THEME';
var lastTheme = localStorage.getItem(themeKey) || 'default';
/* Let the user select different themes */
var $themeDropdown = $('<select>', {
title: 'color theme',
id: 'display-theme',
});
Themes.forEach(function (o) {
$themeDropdown.append($('<option>', {
selected: o.name === lastTheme,
}).val(o.name).text(o.name));
});
2016-06-29 09:51:53 +00:00
$rightside.append($themeDropdown);
2016-06-29 10:00:12 +00:00
var $theme = $bar.find('select#display-theme');
setTheme(lastTheme, $theme);
$theme.on('change', function () {
var theme = $theme.val();
console.log("Setting theme to %s", theme);
setTheme(theme, $theme);
// remember user choices
localStorage.setItem(themeKey, theme);
});
};
2016-06-29 09:51:53 +00:00
configureLanguage(function () {
configureTheme();
2016-06-29 09:51:53 +00:00
});
2016-06-21 13:17:09 +00:00
window.location.hash = info.channel + secret.key;
Cryptpad.getPadTitle(function (err, title) {
if (err) {
console.log("Unable to get pad title");
console.error(err);
return;
}
document.title = title || window.location.hash.slice(1,9);
Cryptpad.rememberPad(title, function (err, data) {
if (err) {
console.log("Unable to set pad title");
console.error(err);
return;
}
});
});
2016-04-22 22:15:39 +00:00
};
var updateUserList = function(shjson) {
// Extract the user list (metadata) from the hyperjson
var hjson = (shjson === "") ? "" : JSON.parse(shjson);
if(hjson && hjson.metadata) {
var userData = hjson.metadata;
// Update the local user data
addToUserList(userData);
}
2016-05-20 11:39:40 +00:00
};
var unnotify = module.unnotify = function () {
if (module.tabNotification &&
typeof(module.tabNotification.cancel) === 'function') {
module.tabNotification.cancel();
}
};
var notify = module.notify = function () {
if (Visible.isSupported() && !Visible.currently()) {
unnotify();
module.tabNotification = Notify.tab(document.title, 1000, 10);
}
};
2016-04-22 22:15:39 +00:00
var onReady = config.onReady = function (info) {
var realtime = module.realtime = info.realtime;
module.patchText = TextPatcher.create({
realtime: realtime,
2016-04-27 13:30:53 +00:00
//logging: true
});
var userDoc = module.realtime.getUserDoc();
var newDoc = "";
if(userDoc !== "") {
var hjson = JSON.parse(userDoc);
newDoc = hjson.content;
if (hjson.highlightMode) {
setMode(hjson.highlightMode, module.$language);
}
}
if (!module.highlightMode) {
setMode('javascript', module.$language);
console.log("%s => %s", module.highlightMode, module.$language.val());
}
// Update the user list (metadata) from the hyperjson
//updateUserList(shjson);
2016-07-11 15:36:53 +00:00
editor.setValue(newDoc || Messages.codeInitialState);
if (Visible.isSupported()) {
Visible.onChange(function (yes) {
if (yes) { unnotify(); }
});
}
$(module.spinner.get().el).fadeOut(750);
setEditable(true);
2016-04-22 22:15:39 +00:00
initializing = false;
//Cryptpad.log("Your document is ready");
getLastName(function (err, lastName) {
if (err) {
console.log("Could not get previous name");
console.error(err);
return;
}
if (typeof(lastName) === 'string' && lastName.length) {
setName(lastName);
}
});
2016-04-22 22:15:39 +00:00
};
var cursorToPos = function(cursor, oldText) {
var cLine = cursor.line;
var cCh = cursor.ch;
var pos = 0;
var textLines = oldText.split("\n");
for (var line = 0; line <= cLine; line++) {
if(line < cLine) {
pos += textLines[line].length+1;
}
else if(line === cLine) {
pos += cCh;
}
}
return pos;
2016-05-20 11:39:40 +00:00
};
var posToCursor = function(position, newText) {
var cursor = {
line: 0,
ch: 0
};
var textLines = newText.substr(0, position).split("\n");
cursor.line = textLines.length - 1;
cursor.ch = textLines[cursor.line].length;
return cursor;
2016-05-20 11:39:40 +00:00
};
2016-04-22 22:15:39 +00:00
var onRemote = config.onRemote = function (info) {
if (initializing) { return; }
var scroll = editor.getScrollInfo();
var oldDoc = canonicalize($textarea.val());
var shjson = module.realtime.getUserDoc();
// Update the user list (metadata) from the hyperjson
updateUserList(shjson);
var hjson = JSON.parse(shjson);
var remoteDoc = hjson.content;
var highlightMode = hjson.highlightMode;
if (highlightMode && highlightMode !== module.highlightMode) {
setMode(highlightMode, module.$language);
}
//get old cursor here
var oldCursor = {};
oldCursor.selectionStart = cursorToPos(editor.getCursor('from'), oldDoc);
oldCursor.selectionEnd = cursorToPos(editor.getCursor('to'), oldDoc);
editor.setValue(remoteDoc);
editor.save();
var op = TextPatcher.diff(oldDoc, remoteDoc);
var selects = ['selectionStart', 'selectionEnd'].map(function (attr) {
return TextPatcher.transformCursor(oldCursor[attr], op);
});
if(selects[0] === selects[1]) {
editor.setCursor(posToCursor(selects[0], remoteDoc));
}
else {
editor.setSelection(posToCursor(selects[0], remoteDoc), posToCursor(selects[1], remoteDoc));
}
editor.scrollTo(scroll.left, scroll.top);
var localDoc = canonicalize($textarea.val());
var hjson2 = {
content: localDoc,
metadata: userList,
highlightMode: highlightMode,
};
var shjson2 = stringify(hjson2);
if (shjson2 !== shjson) {
console.error("shjson2 !== shjson");
TextPatcher.log(shjson, TextPatcher.diff(shjson, shjson2));
module.patchText(shjson2);
}
notify();
2016-04-22 22:15:39 +00:00
};
var onAbort = config.onAbort = function (info) {
// inform of network disconnect
setEditable(false);
2016-07-11 15:36:53 +00:00
Cryptpad.alert(Messages.disconnectAlert);
2016-04-22 22:15:39 +00:00
};
Cryptpad.styleAlerts();
2016-04-22 22:15:39 +00:00
var realtime = module.realtime = Realtime.start(config);
editor.on('change', onLocal);
};
var interval = 100;
var second = function (CM) {
Cryptpad.ready(function (err, env) {
// TODO handle error
andThen(CM);
});
};
var first = function () {
if (ifrw.CodeMirror) {
// it exists, call your continuation
//andThen(ifrw.CodeMirror);
second(ifrw.CodeMirror);
} else {
console.log("CodeMirror was not defined. Trying again in %sms", interval);
// try again in 'interval' ms
setTimeout(first, interval);
}
};
first();
});
});