cryptpad/www/pad/main.js

810 lines
32 KiB
JavaScript
Raw Normal View History

require.config({ paths: { 'json.sortify': '/bower_components/json.sortify/dist/JSON.sortify' } });
2014-10-31 15:42:58 +00:00
define([
2016-06-06 10:14:07 +00:00
'/bower_components/chainpad-crypto/crypto.js',
'/bower_components/chainpad-netflux/chainpad-netflux.js',
2016-06-20 16:39:13 +00:00
'/bower_components/hyperjson/hyperjson.js',
'/common/toolbar.js',
'/common/cursor.js',
2016-06-03 14:23:25 +00:00
'/bower_components/chainpad-json-validator/json-ot.js',
'/common/TypingTests.js',
'json.sortify',
'/bower_components/textpatcher/TextPatcher.amd.js',
2016-06-16 14:20:51 +00:00
'/common/cryptpad-common.js',
2016-07-06 20:19:22 +00:00
'/common/visible.js',
'/common/notify.js',
2016-06-22 15:00:07 +00:00
'/bower_components/file-saver/FileSaver.min.js',
'/bower_components/diff-dom/diffDOM.js',
2015-01-29 16:55:18 +00:00
'/bower_components/jquery/dist/jquery.min.js',
], function (Crypto, realtimeInput, Hyperjson,
2016-07-06 20:19:22 +00:00
Toolbar, Cursor, JsonOT, TypingTest, JSONSortify, TextPatcher, Cryptpad,
Visible, Notify) {
var $ = window.jQuery;
2016-06-22 15:00:07 +00:00
var saveAs = window.saveAs;
var Messages = Cryptpad.Messages;
2017-02-17 14:39:34 +00:00
$(function () {
var ifrw = $('#pad-iframe')[0].contentWindow;
var Ckeditor; // to be initialized later...
var DiffDom = window.diffDOM;
2016-09-13 15:43:56 +00:00
Cryptpad.styleAlerts();
2016-12-21 17:33:21 +00:00
Cryptpad.addLoadingScreen();
2016-09-13 15:43:56 +00:00
var stringify = function (obj) {
return JSONSortify(obj);
};
window.Toolbar = Toolbar;
window.Hyperjson = Hyperjson;
2016-12-06 15:21:11 +00:00
var slice = function (coll) {
return Array.prototype.slice.call(coll);
};
var removeListeners = function (root) {
slice(root.attributes).map(function (attr) {
if (/^on/.test(attr.name)) {
root.attributes.removeNamedItem(attr.name);
}
});
slice(root.children).forEach(removeListeners);
};
var hjsonToDom = function (H) {
2016-12-06 15:21:11 +00:00
var dom = Hyperjson.toDOM(H);
removeListeners(dom);
return dom;
};
2016-07-07 10:47:56 +00:00
var module = window.REALTIME_MODULE = window.APP = {
Hyperjson: Hyperjson,
2016-05-09 09:41:02 +00:00
TextPatcher: TextPatcher,
2016-04-27 09:10:31 +00:00
logFights: true,
2016-07-07 10:47:56 +00:00
fights: [],
Cryptpad: Cryptpad,
};
2017-01-09 17:07:45 +00:00
var emitResize = module.emitResize = function () {
var cw = $('#pad-iframe')[0].contentWindow;
var evt = cw.document.createEvent('UIEvents');
evt.initUIEvent('resize', true, false, cw, 0);
cw.dispatchEvent(evt);
};
2016-06-16 14:20:51 +00:00
var toolbar;
2014-10-31 15:42:58 +00:00
var isNotMagicLine = function (el) {
return !(el && typeof(el.getAttribute) === 'function' &&
el.getAttribute('class') &&
el.getAttribute('class').split(' ').indexOf('non-realtime') !== -1);
};
2016-04-13 14:46:31 +00:00
/* catch `type="_moz"` before it goes over the wire */
var brFilter = function (hj) {
if (hj[1].type === '_moz') { hj[1].type = undefined; }
return hj;
};
var onConnectError = function (info) {
2016-12-21 17:33:21 +00:00
Cryptpad.errorLoadingScreen(Messages.websocketError);
};
2016-02-12 15:21:17 +00:00
var andThen = function (Ckeditor) {
2016-06-16 14:20:51 +00:00
var secret = Cryptpad.getSecrets();
2016-09-20 16:22:40 +00:00
var readOnly = secret.keys && !secret.keys.editKeyStr;
if (!secret.keys) {
secret.keys = secret.key;
}
var editor = window.editor = Ckeditor.replace('editor1', {
2017-02-21 17:21:30 +00:00
customConfig: '/customize/ckeditor-config.js',
2014-10-31 15:42:58 +00:00
});
editor.on('instanceReady', function (Ckeditor) {
2016-10-21 16:16:27 +00:00
var $bar = $('#pad-iframe')[0].contentWindow.$('#cke_1_toolbox');
var parsedHash = Cryptpad.parsePadUrl(window.location.href);
var defaultName = Cryptpad.getDefaultName(parsedHash);
2016-10-21 16:16:27 +00:00
if (readOnly) {
$('#pad-iframe')[0].contentWindow.$('#cke_1_toolbox > .cke_toolbar').hide();
}
/* add a class to the magicline plugin so we can pick it out more easily */
var ml = $('iframe')[0].contentWindow.CKEDITOR.instances.editor1.plugins.magicline
.backdoor.that.line.$;
[ml, ml.parentElement].forEach(function (el) {
el.setAttribute('class', 'non-realtime');
});
var documentBody = ifrw.$('iframe')[0].contentDocument.body;
var inner = window.inner = documentBody;
// hide all content until the realtime doc is ready
$(inner).css({
2016-12-16 14:31:22 +00:00
color: '#fff',
});
documentBody.innerHTML = Messages.initialState;
var cursor = window.cursor = Cursor(inner);
2016-04-21 17:04:15 +00:00
var setEditable = module.setEditable = function (bool) {
if (bool) {
$(inner).css({
2016-12-16 14:31:22 +00:00
color: '#333',
});
}
if (!readOnly || !bool) {
inner.setAttribute('contenteditable', bool);
}
};
// don't let the user edit until the pad is ready
setEditable(false);
var forbiddenTags = [
'SCRIPT',
'IFRAME',
'OBJECT',
'APPLET',
'VIDEO',
'AUDIO'
];
var diffOptions = {
preDiffApply: function (info) {
/*
Don't accept attributes that begin with 'on'
these are probably listeners, and we don't want to
send scripts over the wire.
*/
if (['addAttribute', 'modifyAttribute'].indexOf(info.diff.action) !== -1) {
if (/^on/.test(info.diff.name)) {
console.log("Rejecting forbidden element attribute with name (%s)", info.diff.name);
return true;
}
}
/*
Also reject any elements which would insert any one of
our forbidden tag types: script, iframe, object,
applet, video, or audio
*/
if (['addElement', 'replaceElement'].indexOf(info.diff.action) !== -1) {
if (info.diff.element && forbiddenTags.indexOf(info.diff.element.nodeName) !== -1) {
console.log("Rejecting forbidden tag of type (%s)", info.diff.element.nodeName);
return true;
} else if (info.diff.newValue && forbiddenTags.indexOf(info.diff.newValue.nodeType) !== -1) {
console.log("Rejecting forbidden tag of type (%s)", info.diff.newValue.nodeName);
return true;
}
}
2016-06-22 15:00:07 +00:00
if (info.node && info.node.tagName === 'BODY') {
if (info.diff.action === 'removeAttribute' &&
['class', 'spellcheck'].indexOf(info.diff.name) !== -1) {
return true;
}
}
/* DiffDOM will filter out magicline plugin elements
in practice this will make it impossible to use it
while someone else is typing, which could be annoying.
we should check when such an element is going to be
removed, and prevent that from happening. */
if (info.node && info.node.tagName === 'SPAN' &&
info.node.getAttribute('contentEditable') === "false") {
// it seems to be a magicline plugin element...
if (info.diff.action === 'removeElement') {
// and you're about to remove it...
// this probably isn't what you want
/*
I have never seen this in the console, but the
magic line is still getting removed on remote
edits. This suggests that it's getting removed
by something other than diffDom.
*/
console.log("preventing removal of the magic line!");
// return true to prevent diff application
return true;
}
}
// Do not change the contenteditable value in view mode
if (readOnly && info.node && info.node.tagName === 'BODY' &&
info.diff.action === 'modifyAttribute' && info.diff.name === 'contenteditable') {
return true;
}
// no use trying to recover the cursor if it doesn't exist
if (!cursor.exists()) { return; }
/* frame is either 0, 1, 2, or 3, depending on which
cursor frames were affected: none, first, last, or both
*/
var frame = info.frame = cursor.inNode(info.node);
if (!frame) { return; }
if (typeof info.diff.oldValue === 'string' && typeof info.diff.newValue === 'string') {
var pushes = cursor.pushDelta(info.diff.oldValue, info.diff.newValue);
if (frame & 1) {
// push cursor start if necessary
if (pushes.commonStart < cursor.Range.start.offset) {
cursor.Range.start.offset += pushes.delta;
}
}
if (frame & 2) {
// push cursor end if necessary
if (pushes.commonStart < cursor.Range.end.offset) {
cursor.Range.end.offset += pushes.delta;
}
}
}
},
postDiffApply: function (info) {
if (info.frame) {
if (info.node) {
if (info.frame & 1) { cursor.fixStart(info.node); }
if (info.frame & 2) { cursor.fixEnd(info.node); }
} else { console.error("info.node did not exist"); }
var sel = cursor.makeSelection();
var range = cursor.makeRange();
cursor.fixSelection(sel, range);
}
}
};
var initializing = true;
var userData = module.userData = {}; // List of pretty names for all users (mapped with their ID)
var userList; // List of users still connected to the channel (server IDs)
var addToUserData = function(data) {
2016-10-19 10:30:25 +00:00
var users = module.users;
for (var attrname in data) { userData[attrname] = data[attrname]; }
2016-10-19 10:30:25 +00:00
if (users && users.length) {
for (var userKey in userData) {
2016-10-26 15:50:59 +00:00
if (users.indexOf(userKey) === -1) { delete userData[userKey]; }
2016-10-19 10:30:25 +00:00
}
}
if(userList && typeof userList.onChange === "function") {
userList.onChange(userData);
}
};
var myData = {};
var myUserName = ''; // My "pretty name"
var myID; // My server ID
var setMyID = function(info) {
myID = info.myID || null;
};
2016-07-25 09:09:25 +00:00
var setName = module.setName = function (newName) {
2016-09-23 15:53:24 +00:00
if (typeof(newName) !== 'string') { return; }
2016-08-25 16:01:03 +00:00
var myUserNameTemp = Cryptpad.fixHTML(newName.trim());
2016-07-25 09:09:25 +00:00
if(myUserNameTemp.length > 32) {
myUserNameTemp = myUserNameTemp.substr(0, 32);
}
myUserName = myUserNameTemp;
myData[myID] = {
name: myUserName
};
addToUserData(myData);
2016-09-22 15:12:46 +00:00
Cryptpad.setAttribute('username', newName, function (err, data) {
if (err) {
console.error("Couldn't set username");
return;
}
editor.fire('change');
});
2016-07-25 09:09:25 +00:00
};
var isDefaultTitle = function () {
var parsed = Cryptpad.parsePadUrl(window.location.href);
return Cryptpad.isDefaultName(parsed, document.title);
};
var getHeadingText = function () {
var text;
if (['h1', 'h2', 'h3'].some(function (t) {
var $header = $(inner).find(t + ':first-of-type');
if ($header.length && $header.text()) {
text = $header.text();
return true;
}
})) { return text; }
};
var suggestName = function (fallback) {
2016-10-25 15:29:13 +00:00
if (document.title === defaultName) {
return getHeadingText() || fallback || "";
} else {
return document.title || getHeadingText() || defaultName;
}
};
var DD = new DiffDom(diffOptions);
// apply patches, and try not to lose the cursor in the process!
var applyHjson = function (shjson) {
var userDocStateDom = hjsonToDom(JSON.parse(shjson));
if (!readOnly) {
userDocStateDom.setAttribute("contenteditable", "true"); // lol wtf
}
var patch = (DD).diff(inner, userDocStateDom);
(DD).apply(inner, patch);
};
var stringifyDOM = module.stringifyDOM = function (dom) {
2016-04-26 15:16:58 +00:00
var hjson = Hyperjson.fromDOM(dom, isNotMagicLine, brFilter);
hjson[3] = {
metadata: {
users: userData,
2016-10-25 15:29:13 +00:00
defaultTitle: defaultName
}
};
2017-01-12 14:15:10 +00:00
if (!initializing) {
hjson[3].metadata.title = document.title;
2017-02-21 16:42:58 +00:00
} else if (Cryptpad.initialName) {
hjson[3].metadata.title = Cryptpad.initialName;
2017-01-12 14:15:10 +00:00
}
2016-04-26 15:16:58 +00:00
return stringify(hjson);
};
var realtimeOptions = {
// provide initialstate...
2016-04-13 14:46:31 +00:00
initialState: stringifyDOM(inner) || '{}',
// the websocket URL
2016-10-03 17:28:36 +00:00
websocketURL: Cryptpad.getWebsocketURL(),
// the channel we will communicate over
2016-06-16 14:20:51 +00:00
channel: secret.channel,
// the nework used for the file store if it exists
network: Cryptpad.getNetwork(),
// our public key
2016-09-16 16:45:40 +00:00
validateKey: secret.keys.validateKey || undefined,
readOnly: readOnly,
// method which allows us to get the id of the user
setMyID: setMyID,
2016-06-21 13:17:09 +00:00
// Pass in encrypt and decrypt methods
2016-09-16 16:45:40 +00:00
crypto: Crypto.createEncryptor(secret.keys),
// really basic operational transform
2017-02-09 16:20:13 +00:00
transformFunction : JsonOT.validate,
// cryptpad debug logging (default is 1)
// logLevel: 0,
2016-06-21 13:17:09 +00:00
validateContent: function (content) {
try {
JSON.parse(content);
return true;
} catch (e) {
console.log("Failed to parse, rejecting patch");
return false;
}
}
};
var updateTitle = function (newTitle) {
if (newTitle === document.title) { return; }
// Change the title now, and set it back to the old value if there is an error
var oldTitle = document.title;
document.title = newTitle;
Cryptpad.renamePad(newTitle, function (err, data) {
if (err) {
console.log("Couldn't set pad title");
console.error(err);
document.title = oldTitle;
return;
}
document.title = data;
$bar.find('.' + Toolbar.constants.title).find('span.title').text(data);
$bar.find('.' + Toolbar.constants.title).find('input').val(data);
});
};
2016-10-25 15:29:13 +00:00
var updateDefaultTitle = function (defaultTitle) {
defaultName = defaultTitle;
$bar.find('.' + Toolbar.constants.title).find('input').attr("placeholder", defaultName);
};
var updateMetadata = function(shjson) {
// Extract the user list (metadata) from the hyperjson
var hjson = JSON.parse(shjson);
var peerMetadata = hjson[3];
2017-01-12 14:15:10 +00:00
var titleUpdated = false;
if (peerMetadata && peerMetadata.metadata) {
if (peerMetadata.metadata.users) {
var userData = peerMetadata.metadata.users;
// Update the local user data
addToUserData(userData);
}
2016-10-25 15:29:13 +00:00
if (peerMetadata.metadata.defaultTitle) {
updateDefaultTitle(peerMetadata.metadata.defaultTitle);
}
if (typeof peerMetadata.metadata.title !== "undefined") {
2017-01-12 13:26:10 +00:00
updateTitle(peerMetadata.metadata.title || defaultName);
2017-01-12 14:15:10 +00:00
titleUpdated = true;
}
}
2017-01-12 14:15:10 +00:00
if (!titleUpdated) {
updateTitle(defaultName);
}
2016-05-20 11:39:40 +00:00
};
2016-07-06 20:19:22 +00:00
var unnotify = function () {
if (module.tabNotification &&
typeof(module.tabNotification.cancel) === 'function') {
module.tabNotification.cancel();
}
};
var notify = function () {
if (Visible.isSupported() && !Visible.currently()) {
unnotify();
module.tabNotification = Notify.tab(1000, 10);
2016-07-06 20:19:22 +00:00
}
};
var onRemote = realtimeOptions.onRemote = function (info) {
if (initializing) { return; }
var oldShjson = stringifyDOM(inner);
var shjson = info.realtime.getUserDoc();
// remember where the cursor is
cursor.update();
2016-04-26 15:16:58 +00:00
// Update the user list (metadata) from the hyperjson
updateMetadata(shjson);
var newInner = JSON.parse(shjson);
2017-01-25 09:21:31 +00:00
var newSInner;
if (newInner.length > 2) {
2017-01-25 09:21:31 +00:00
newSInner = stringify(newInner[2]);
}
// build a dom from HJSON, diff, and patch the editor
applyHjson(shjson);
if (!readOnly) {
var shjson2 = stringifyDOM(inner);
if (shjson2 !== shjson) {
console.error("shjson2 !== shjson");
module.patchText(shjson2);
/* pushing back over the wire is necessary, but it can
result in a feedback loop, which we call a browser
fight */
if (module.logFights) {
// what changed?
var op = TextPatcher.diff(shjson, shjson2);
// log the changes
TextPatcher.log(shjson, op);
var sop = JSON.stringify(TextPatcher.format(shjson, op));
var index = module.fights.indexOf(sop);
if (index === -1) {
module.fights.push(sop);
console.log("Found a new type of browser disagreement");
console.log("You can inspect the list in your " +
"console at `REALTIME_MODULE.fights`");
console.log(module.fights);
} else {
console.log("Encountered a known browser disagreement: " +
"available at `REALTIME_MODULE.fights[%s]`", index);
}
2016-04-27 09:10:31 +00:00
}
}
}
// Notify only when the content has changed, not when someone has joined/left
var oldSInner = stringify(JSON.parse(oldShjson)[2]);
2017-01-25 09:21:31 +00:00
if (newSInner && newSInner !== oldSInner) {
notify();
}
};
2016-06-22 15:00:07 +00:00
var getHTML = function (Dom) {
var data = inner.innerHTML;
Dom = Dom || (new DOMParser()).parseFromString(data,"text/html");
return ('<!DOCTYPE html>\n' +
'<html>\n' +
(typeof(Hyperjson.toString) === 'function'?
Hyperjson.toString(Hyperjson.fromDOM(Dom.body)):
Dom.head.outerHTML) + '\n');
2016-06-22 15:00:07 +00:00
};
var domFromHTML = function (html) {
return new DOMParser().parseFromString(html, 'text/html');
};
var exportFile = function () {
var html = getHTML();
var suggestion = suggestName('cryptpad-document');
2016-07-11 15:36:53 +00:00
Cryptpad.prompt(Messages.exportPrompt,
Cryptpad.fixFileName(suggestion) + '.html', function (filename) {
2016-07-07 10:47:56 +00:00
if (!(typeof(filename) === 'string' && filename)) { return; }
2016-06-22 15:00:07 +00:00
var blob = new Blob([html], {type: "text/html;charset=utf-8"});
saveAs(blob, filename);
2016-07-07 10:47:56 +00:00
});
2016-06-22 15:00:07 +00:00
};
var importFile = function (content, file) {
var shjson = stringify(Hyperjson.fromDOM(domFromHTML(content).body));
applyHjson(shjson);
realtimeOptions.onLocal();
};
2016-06-22 15:00:07 +00:00
2016-10-21 16:16:27 +00:00
var renameCb = function (err, title) {
if (err) { return; }
document.title = title;
editor.fire('change');
};
var onInit = realtimeOptions.onInit = function (info) {
userList = info.userList;
var config = {
2017-01-18 10:00:46 +00:00
displayed: ['useradmin', 'language', 'spinner', 'lag', 'state', 'share', 'userlist', 'newpad'],
userData: userData,
readOnly: readOnly,
2016-10-21 16:16:27 +00:00
ifrw: ifrw,
title: {
onRename: renameCb,
2016-10-25 15:29:13 +00:00
defaultName: defaultName,
suggestName: suggestName
},
common: Cryptpad
};
if (readOnly) {delete config.changeNameID; }
toolbar = info.realtime.toolbar = Toolbar.create($bar, info.myID, info.realtime, info.getLag, userList, config);
2016-04-21 17:04:15 +00:00
var $rightside = $bar.find('.' + Toolbar.constants.rightside);
var $userBlock = $bar.find('.' + Toolbar.constants.username);
var $editShare = $bar.find('.' + Toolbar.constants.editShare);
var $viewShare = $bar.find('.' + Toolbar.constants.viewShare);
var $usernameButton = module.$userNameButton = $($bar.find('.' + Toolbar.constants.changeUsername));
2016-09-20 09:35:57 +00:00
var editHash;
var viewHash = Cryptpad.getViewHashFromKeys(info.channel, secret.keys);
if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
}
// Expand / collapse the toolbar
var $existingButton = $bar.find('#cke_1_toolbar_collapser');
var $collapse = Cryptpad.createButton(null, true);
$existingButton.hide();
$collapse.removeClass('fa-question');
var updateIcon = function () {
$collapse.removeClass('fa-caret-down').removeClass('fa-caret-up');
var isCollapsed = !$bar.find('.cke_toolbox_main').is(':visible');
2017-02-10 13:25:02 +00:00
if (isCollapsed) { $collapse.addClass('fa-caret-down'); }
else { $collapse.addClass('fa-caret-up'); }
};
updateIcon();
$collapse.click(function () {
$existingButton.click();
updateIcon();
});
$rightside.append($collapse);
2016-09-27 16:33:03 +00:00
/* add an export button */
var $export = Cryptpad.createButton('export', true, {}, exportFile);
$rightside.append($export);
2016-06-22 15:00:07 +00:00
if (!readOnly) {
/* add an import button */
var $import = Cryptpad.createButton('import', true, {}, importFile);
$rightside.append($import);
2016-06-22 15:00:07 +00:00
/* add a rename button */
//var $setTitle = Cryptpad.createButton('rename', true, {suggestName: suggestName}, renameCb);
//$rightside.append($setTitle);
}
2016-06-30 08:51:19 +00:00
/* add a forget button */
var forgetCb = function (err, title) {
if (err) { return; }
document.title = title;
};
var $forgetPad = Cryptpad.createButton('forget', true, {}, forgetCb);
$rightside.append($forgetPad);
if (!readOnly) {
$editShare.append(Cryptpad.createButton('editshare', false, {editHash: editHash}));
if (viewHash) {
$editShare.append($('<hr>'));
}
}
if (viewHash) {
2016-09-20 16:22:40 +00:00
/* add a 'links' button */
$viewShare.append(Cryptpad.createButton('viewshare', false, {viewHash: viewHash}));
if (!readOnly) {
$viewShare.append(Cryptpad.createButton('viewopen', false, {viewHash: viewHash}));
}
2016-09-20 16:22:40 +00:00
}
2016-09-20 09:35:57 +00:00
2016-04-21 17:04:15 +00:00
// set the hash
if (!readOnly) { Cryptpad.replaceHash(editHash); }
Cryptpad.onDisplayNameChanged(setName);
};
// this should only ever get called once, when the chain syncs
var onReady = realtimeOptions.onReady = function (info) {
2017-01-09 17:07:45 +00:00
if (!module.isMaximized) {
editor.execCommand('maximize');
2017-01-09 17:07:45 +00:00
module.isMaximized = true;
// We have to call it 3 times in Safari
// in order to have the editor fully maximized -_-
if ((''+window.navigator.vendor).indexOf('Apple') !== -1) {
editor.execCommand('maximize');
editor.execCommand('maximize');
}
}
2016-12-22 10:02:12 +00:00
module.patchText = TextPatcher.create({
realtime: info.realtime,
2016-04-27 13:40:48 +00:00
//logging: true,
});
2016-10-19 10:30:25 +00:00
module.users = info.userList.users;
module.realtime = info.realtime;
var shjson = info.realtime.getUserDoc();
applyHjson(shjson);
// Update the user list (metadata) from the hyperjson
2016-09-22 14:34:06 +00:00
updateMetadata(shjson);
2016-07-06 20:19:22 +00:00
if (Visible.isSupported()) {
Visible.onChange(function (yes) {
if (yes) { unnotify(); }
});
}
Cryptpad.getLastName(function (err, lastName) {
console.log("Unlocking editor");
setEditable(true);
initializing = false;
Cryptpad.removeLoadingScreen(emitResize);
// Update the toolbar list:
// Add the current user in the metadata if he has edit rights
if (readOnly) { return; }
if (typeof(lastName) === 'string') {
setName(lastName);
} else {
myData[myID] = {
name: ""
};
addToUserData(myData);
realtimeOptions.onLocal();
module.$userNameButton.click();
}
});
};
var onAbort = realtimeOptions.onAbort = function (info) {
console.log("Aborting the session!");
// stop the user from continuing to edit
setEditable(false);
// TODO inform them that the session was torn down
toolbar.failed();
Cryptpad.alert(Messages.common_connectionLost);
};
var onConnectionChange = realtimeOptions.onConnectionChange = function (info) {
setEditable(info.state);
toolbar.failed();
if (info.state) {
initializing = true;
toolbar.reconnecting(info.myId);
Cryptpad.findOKButton().click();
} else {
Cryptpad.alert(Messages.common_connectionLost);
}
};
var onError = realtimeOptions.onError = onConnectError;
2016-12-08 15:01:46 +00:00
var onLocal = realtimeOptions.onLocal = function () {
if (initializing) { return; }
if (readOnly) { return; }
2016-04-12 15:17:14 +00:00
// stringify the json and send it into chainpad
2016-04-26 15:16:58 +00:00
var shjson = stringifyDOM(inner);
module.patchText(shjson);
if (module.realtime.getUserDoc() !== shjson) {
console.error("realtime.getUserDoc() !== shjson");
}
};
var rti = module.realtimeInput = realtimeInput.start(realtimeOptions);
Cryptpad.onLogout(function () { setEditable(false); });
/* hitting enter makes a new line, but places the cursor inside
of the <br> instead of the <p>. This makes it such that you
cannot type until you click, which is rather unnacceptable.
If the cursor is ever inside such a <br>, you probably want
to push it out to the parent element, which ought to be a
paragraph tag. This needs to be done on keydown, otherwise
the first such keypress will not be inserted into the P. */
inner.addEventListener('keydown', cursor.brFix);
editor.on('change', onLocal);
// export the typing tests to the window.
// call like `test = easyTest()`
// terminate the test like `test.cancel()`
var easyTest = window.easyTest = function () {
cursor.update();
var start = cursor.Range.start;
var test = TypingTest.testInput(inner, start.el, start.offset, onLocal);
onLocal();
return test;
};
2014-10-31 15:42:58 +00:00
});
};
var interval = 100;
var second = function (Ckeditor) {
Cryptpad.ready(function (err, env) {
// TODO handle error
andThen(Ckeditor);
});
Cryptpad.onError(function (info) {
if (info && info.type === "store") {
onConnectError();
}
});
};
var first = function () {
2016-02-12 15:21:17 +00:00
Ckeditor = ifrw.CKEDITOR;
if (Ckeditor) {
//andThen(Ckeditor);
2017-01-12 01:09:36 +00:00
// mobile configuration
Ckeditor.config.toolbarCanCollapse = true;
2017-01-12 02:02:57 +00:00
Ckeditor.config.height = '72vh';
2017-01-12 01:09:36 +00:00
if (screen.height < 800) {
Ckeditor.config.toolbarStartupExpanded = false;
2017-01-12 02:39:41 +00:00
$('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1.0, user-scalable=no');
} else {
$('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1.0, user-scalable=yes');
2017-01-12 01:09:36 +00:00
}
second(Ckeditor);
} else {
console.log("Ckeditor was not defined. Trying again in %sms",interval);
setTimeout(first, interval);
}
};
$(first);
2017-02-17 14:39:34 +00:00
});
2014-10-31 15:42:58 +00:00
});