remove unused variables

pull/1/head
ansuz 8 years ago
parent 5739c3d973
commit 78b11584f8

@ -10,7 +10,7 @@
"notypeof": true, "notypeof": true,
"shadow": false, "shadow": false,
"undef": true, "undef": true,
"unused": false, "unused": true,
"futurehostile":true, "futurehostile":true,
"browser": true, "browser": true,
"predef": [ "predef": [

@ -4,7 +4,7 @@ define([
'/common/cryptpad-common.js' '/common/cryptpad-common.js'
], function ($, Config, Cryptpad) { ], function ($, Config, Cryptpad) {
var APP = window.APP = { window.APP = {
Cryptpad: Cryptpad, Cryptpad: Cryptpad,
}; };
@ -118,7 +118,7 @@ define([
$('button.login').click(); $('button.login').click();
}); });
$('button.login').click(function (e) { $('button.login').click(function () {
Cryptpad.addLoadingScreen(Messages.login_hashing); Cryptpad.addLoadingScreen(Messages.login_hashing);
// We need a setTimeout(cb, 0) otherwise the loading screen is only displayed after hashing the password // We need a setTimeout(cb, 0) otherwise the loading screen is only displayed after hashing the password
window.setTimeout(function () { window.setTimeout(function () {
@ -171,15 +171,14 @@ define([
/* End Log in UI */ /* End Log in UI */
var addButtonHandlers = function () { var addButtonHandlers = function () {
$('button.register').click(function (e) { $('button.register').click(function () {
var username = $('#name').val(); var username = $('#name').val();
var passwd = $('#password').val(); var passwd = $('#password').val();
var remember = $('#rememberme').is(':checked');
sessionStorage.login_user = username; sessionStorage.login_user = username;
sessionStorage.login_pass = passwd; sessionStorage.login_pass = passwd;
document.location.href = '/register/'; document.location.href = '/register/';
}); });
$('button.gotodrive').click(function (e) { $('button.gotodrive').click(function () {
document.location.href = '/drive/'; document.location.href = '/drive/';
}); });
}; };

@ -112,9 +112,7 @@ define(req, function($, Default, Language) {
if (!selector.length) { return; } if (!selector.length) { return; }
var $button = $(selector).find('button .buttonTitle');
// Select the current language in the list // Select the current language in the list
var option = $(selector).find('[data-value="' + language + '"]');
selector.setValue(language || 'English'); selector.setValue(language || 'English');
// Listen for language change // Listen for language change
@ -137,12 +135,12 @@ define(req, function($, Default, Language) {
var key = $el.data('localization-append'); var key = $el.data('localization-append');
$el.append(messages[key]); $el.append(messages[key]);
}; };
var translateTitle = function (i, e) { var translateTitle = function () {
var $el = $(this); var $el = $(this);
var key = $el.data('localization-title'); var key = $el.data('localization-title');
$el.attr('title', messages[key]); $el.attr('title', messages[key]);
}; };
var translatePlaceholder = function (i, e) { var translatePlaceholder = function () {
var $el = $(this); var $el = $(this);
var key = $el.data('localization-placeholder'); var key = $el.data('localization-placeholder');
$el.attr('placeholder', messages[key]); $el.attr('placeholder', messages[key]);

@ -10,7 +10,7 @@
// create an invisible iframe with a given source // create an invisible iframe with a given source
// append it to a parent element // append it to a parent element
// execute a callback when it has loaded // execute a callback when it has loaded
var create = Frame.create = function (parent, src, onload, timeout) { Frame.create = function (parent, src, onload, timeout) {
var iframe = document.createElement('iframe'); var iframe = document.createElement('iframe');
timeout = timeout || 10000; timeout = timeout || 10000;
@ -34,7 +34,7 @@
/* given an iframe with an rpc script loaded, create a frame object /* given an iframe with an rpc script loaded, create a frame object
with an asynchronous 'send' method */ with an asynchronous 'send' method */
var open = Frame.open = function (e, A, timeout) { Frame.open = function (e, A, timeout) {
var win = e.contentWindow; var win = e.contentWindow;
var frame = {}; var frame = {};
@ -44,7 +44,7 @@
timeout = timeout || 5000; timeout = timeout || 5000;
var accepts = frame.accepts = function (o) { frame.accepts = function (o) {
return A.some(function (e) { return A.some(function (e) {
switch (typeof(e)) { switch (typeof(e)) {
case 'string': return e === o; case 'string': return e === o;
@ -55,7 +55,7 @@
var changeHandlers = frame.changeHandlers = []; var changeHandlers = frame.changeHandlers = [];
var change = frame.change = function (f) { frame.change = function (f) {
if (typeof(f) !== 'function') { if (typeof(f) !== 'function') {
throw new Error('[Frame.change] expected callback'); throw new Error('[Frame.change] expected callback');
} }
@ -94,7 +94,7 @@
}; };
window.addEventListener('message', _listener); window.addEventListener('message', _listener);
var close = frame.close = function () { frame.close = function () {
window.removeEventListener('message', _listener); window.removeEventListener('message', _listener);
}; };
@ -130,31 +130,31 @@
win.postMessage(JSON.stringify(req), '*'); win.postMessage(JSON.stringify(req), '*');
}; };
var set = frame.set = function (key, val, cb) { frame.set = function (key, val, cb) {
send('set', key, val, cb); send('set', key, val, cb);
}; };
var batchset = frame.setBatch = function (map, cb) { frame.setBatch = function (map, cb) {
send('batchset', void 0, map, cb); send('batchset', void 0, map, cb);
}; };
var get = frame.get = function (key, cb) { frame.get = function (key, cb) {
send('get', key, void 0, cb); send('get', key, void 0, cb);
}; };
var batchget = frame.getBatch = function (keys, cb) { frame.getBatch = function (keys, cb) {
send('batchget', void 0, keys, cb); send('batchget', void 0, keys, cb);
}; };
var remove = frame.remove = function (key, cb) { frame.remove = function (key, cb) {
send('remove', key, void 0, cb); send('remove', key, void 0, cb);
}; };
var batchremove = frame.removeBatch = function (keys, cb) { frame.removeBatch = function (keys, cb) {
send('batchremove', void 0, keys, cb); send('batchremove', void 0, keys, cb);
}; };
var keys = frame.keys = function (cb) { frame.keys = function (cb) {
send('keys', void 0, void 0, cb); send('keys', void 0, void 0, cb);
}; };
@ -164,7 +164,7 @@
if (typeof(module) !== 'undefined' && module.exports) { if (typeof(module) !== 'undefined' && module.exports) {
module.exports = Frame; module.exports = Frame;
} else if (typeof(define) === 'function' && define.amd) { } else if (typeof(define) === 'function' && define.amd) {
define(['jquery'], function ($) { define(['jquery'], function () {
return Frame; return Frame;
}); });
} else { } else {

@ -39,7 +39,7 @@ define([
return !keys.some(function (k) { return data[k] !== null; }); return !keys.some(function (k) { return data[k] !== null; });
}; };
Frame.create(document.body, domain + path, function (err, iframe, loadEvent) { Frame.create(document.body, domain + path, function (err, iframe) {
if (handleErr(err)) { return; } if (handleErr(err)) { return; }
console.log("Created iframe"); console.log("Created iframe");
@ -50,7 +50,7 @@ define([
[function (i) { // test #1 [function (i) { // test #1
var pew = randInt(); var pew = randInt();
frame.set('pew', pew, function (err, data) { frame.set('pew', pew, function (err) {
if (handleErr(err)) { return; } if (handleErr(err)) { return; }
frame.get('pew', function (err, num) { frame.get('pew', function (err, num) {
if (handleErr(err)) { return; } if (handleErr(err)) { return; }
@ -76,9 +76,9 @@ define([
var keys = Object.keys(map); var keys = Object.keys(map);
frame.setBatch(map, function (err, data) { frame.setBatch(map, function (err) {
if (handleErr(err)) { return; } if (handleErr(err)) { return; }
frame.getBatch(keys, function (err, data) { frame.getBatch(keys, function (err) {
if (handleErr(err)) { return; } if (handleErr(err)) { return; }
frame.removeBatch(Object.keys(map), function (err) { frame.removeBatch(Object.keys(map), function (err) {
if (handleErr(err)) { return; } if (handleErr(err)) { return; }

@ -18,7 +18,7 @@ var isValidChannel = function (chan) {
var uint8ArrayToHex = function (a) { var uint8ArrayToHex = function (a) {
// call slice so Uint8Arrays work as expected // call slice so Uint8Arrays work as expected
return Array.prototype.slice.call(a).map(function (e, i) { return Array.prototype.slice.call(a).map(function (e) {
var n = Number(e & 0xff).toString(16); var n = Number(e & 0xff).toString(16);
if (n === 'NaN') { if (n === 'NaN') {
throw new Error('invalid input resulted in NaN'); throw new Error('invalid input resulted in NaN');
@ -127,7 +127,6 @@ var isValidCookie = function (Sessions, publicKey, cookie) {
var idx = user.tokens.indexOf(parsed.seq); var idx = user.tokens.indexOf(parsed.seq);
if (idx === -1) { return false; } if (idx === -1) { return false; }
var next;
if (idx > 0) { if (idx > 0) {
// make a new token // make a new token
addTokenForKey(Sessions, publicKey, makeToken()); addTokenForKey(Sessions, publicKey, makeToken());
@ -325,9 +324,9 @@ var getHash = function (store, Sessions, publicKey, cb) {
}); });
}; };
var storeMessage = function (store, publicKey, msg, cb) { /* var storeMessage = function (store, publicKey, msg, cb) {
store.message(publicKey, JSON.stringify(msg), cb); store.message(publicKey, JSON.stringify(msg), cb);
}; }; */
var pinChannel = function (store, Sessions, publicKey, channels, cb) { var pinChannel = function (store, Sessions, publicKey, channels, cb) {
if (!channels && channels.filter) { if (!channels && channels.filter) {
@ -407,7 +406,7 @@ var resetUserPins = function (store, Sessions, publicKey, channelList, cb) {
}; };
var getLimit = function (cb) { var getLimit = function (cb) {
cb = cb; // TODO
}; };
var safeMkdir = function (path, cb) { var safeMkdir = function (path, cb) {
@ -649,6 +648,7 @@ RPC.create = function (config /*:typeof(ConfigType)*/, cb /*:(?Error, ?Function)
return void getFileSize(ctx.store, msg[1], Respond); return void getFileSize(ctx.store, msg[1], Respond);
case 'GET_LIMIT': // TODO implement this and cache it per-user case 'GET_LIMIT': // TODO implement this and cache it per-user
return void getLimit(function (e, limit) { return void getLimit(function (e, limit) {
limit = limit;
Respond('NOT_IMPLEMENTED'); Respond('NOT_IMPLEMENTED');
}); });
case 'GET_MULTIPLE_FILE_SIZE': case 'GET_MULTIPLE_FILE_SIZE':

@ -28,7 +28,8 @@ var readMessages = function (path, msgHandler, cb) {
}; };
var checkPath = function (path, callback) { var checkPath = function (path, callback) {
Fs.stat(path, function (err, stats) { // TODO check if we actually need to use stat at all
Fs.stat(path, function (err) {
if (!err) { if (!err) {
callback(undefined, true); callback(undefined, true);
return; return;
@ -166,7 +167,7 @@ var getChannel = function (env, id, callback) {
}); });
} }
}); });
}).nThen(function (waitFor) { }).nThen(function () {
if (errorState) { return; } if (errorState) { return; }
complete(); complete();
}); });

@ -38,8 +38,6 @@ define([
}); });
}; };
var $body = $('body');
var HJSON_list = [ var HJSON_list = [
'["DIV",{"id":"target"},[["P",{"class":" alice bob charlie has.dot","id":"bang"},["pewpewpew"]]]]', '["DIV",{"id":"target"},[["P",{"class":" alice bob charlie has.dot","id":"bang"},["pewpewpew"]]]]',

@ -3,7 +3,7 @@ define(['jquery'], function ($) {
// copy arbitrary text to the clipboard // copy arbitrary text to the clipboard
// return boolean indicating success // return boolean indicating success
var copy = Clipboard.copy = function (text) { Clipboard.copy = function (text) {
var $ta = $('<input>', { var $ta = $('<input>', {
type: 'text', type: 'text',
}).val(text); }).val(text);

@ -49,7 +49,7 @@ define([
return ret; return ret;
} }
var hash = href.replace(patt, function (a, domain, type, hash) { var hash = href.replace(patt, function (a, domain, type) {
ret.domain = domain; ret.domain = domain;
ret.type = type; ret.type = type;
return ''; return '';
@ -70,7 +70,7 @@ define([
* - no argument: use the URL hash or create one if it doesn't exist * - no argument: use the URL hash or create one if it doesn't exist
* - secretHash provided: use secretHash to find the keys * - secretHash provided: use secretHash to find the keys
*/ */
var getSecrets = Hash.getSecrets = function (secretHash) { Hash.getSecrets = function (secretHash) {
var secret = {}; var secret = {};
var generate = function () { var generate = function () {
secret.keys = Crypto.createEditCryptor(); secret.keys = Crypto.createEditCryptor();
@ -130,7 +130,7 @@ define([
return secret; return secret;
}; };
var getHashes = Hash.getHashes = function (channel, secret) { Hash.getHashes = function (channel, secret) {
var hashes = {}; var hashes = {};
if (secret.keys.editKeyStr) { if (secret.keys.editKeyStr) {
hashes.editHash = getEditHashFromKeys(channel, secret.keys); hashes.editHash = getEditHashFromKeys(channel, secret.keys);
@ -152,7 +152,7 @@ define([
return id; return id;
}; };
var createRandomHash = Hash.createRandomHash = function () { Hash.createRandomHash = function () {
// 16 byte channel Id // 16 byte channel Id
var channelId = Util.hexToBase64(createChannelId()); var channelId = Util.hexToBase64(createChannelId());
// 18 byte encryption key // 18 byte encryption key
@ -197,7 +197,7 @@ Version 2
}; };
// STORAGE // STORAGE
var findWeaker = Hash.findWeaker = function (href, recents) { Hash.findWeaker = function (href, recents) {
var rHref = href || getRelativeHref(window.location.href); var rHref = href || getRelativeHref(window.location.href);
var parsed = parsePadUrl(rHref); var parsed = parsePadUrl(rHref);
if (!parsed.hash) { return false; } if (!parsed.hash) { return false; }
@ -241,11 +241,11 @@ Version 2
}); });
return stronger; return stronger;
}; };
var isNotStrongestStored = Hash.isNotStrongestStored = function (href, recents) { Hash.isNotStrongestStored = function (href, recents) {
return findStronger(href, recents); return findStronger(href, recents);
}; };
var hrefToHexChannelId = Hash.hrefToHexChannelId = function (href) { Hash.hrefToHexChannelId = function (href) {
var parsed = Hash.parsePadUrl(href); var parsed = Hash.parsePadUrl(href);
if (!parsed || !parsed.hash) { return; } if (!parsed || !parsed.hash) { return; }
@ -266,11 +266,11 @@ Version 2
return hex; return hex;
}; };
var getBlobPath = Hash.getBlobPathFromHex = function (id) { Hash.getBlobPathFromHex = function (id) {
return '/blob/' + id.slice(0,2) + '/' + id; return '/blob/' + id.slice(0,2) + '/' + id;
}; };
var serializeHash = Hash.serializeHash = function (hash) { Hash.serializeHash = function (hash) {
if (hash && hash.slice(-1) !== "/") { hash += "/"; } if (hash && hash.slice(-1) !== "/") { hash += "/"; }
return hash; return hash;
}; };

@ -25,7 +25,7 @@ define([
var wcId = common.hrefToHexChannelId(config.href || window.location.href); var wcId = common.hrefToHexChannelId(config.href || window.location.href);
console.log(wcId); console.log(wcId);
var createRealtime = function(chan) { var createRealtime = function () {
return ChainPad.create({ return ChainPad.create({
userName: 'history', userName: 'history',
initialState: '', initialState: '',
@ -68,14 +68,14 @@ define([
} }
}; };
network.on('message', function (msg, sender) { network.on('message', function (msg) {
onMsg(msg); onMsg(msg);
}); });
network.sendto(hkn, JSON.stringify(['GET_FULL_HISTORY', wcId, secret.keys.validateKey])); network.sendto(hkn, JSON.stringify(['GET_FULL_HISTORY', wcId, secret.keys.validateKey]));
}; };
var create = History.create = function (common, config) { History.create = function (common, config) {
if (!config.$toolbar) { return void console.error("config.$toolbar is undefined");} if (!config.$toolbar) { return void console.error("config.$toolbar is undefined");}
if (History.loading) { return void console.error("History is already being loaded..."); } if (History.loading) { return void console.error("History is already being loaded..."); }
History.loading = true; History.loading = true;
@ -145,7 +145,7 @@ define([
title: Messages.history_next title: Messages.history_next
}).appendTo($hist); }).appendTo($hist);
var $label = $('<label>').text(Messages.history_version).appendTo($nav); $('<label>').text(Messages.history_version).appendTo($nav);
var $cur = $('<input>', { var $cur = $('<input>', {
'class' : 'gotoInput', 'class' : 'gotoInput',
'type' : 'number', 'type' : 'number',

@ -48,7 +48,7 @@ define([
UI.alert = function (msg, cb, force) { UI.alert = function (msg, cb, force) {
cb = cb || function () {}; cb = cb || function () {};
if (force !== true) { msg = Util.fixHTML(msg); } if (force !== true) { msg = Util.fixHTML(msg); }
var close = function (e) { var close = function () {
findOKButton().click(); findOKButton().click();
}; };
var keyHandler = listenForKeys(close, close); var keyHandler = listenForKeys(close, close);
@ -66,9 +66,9 @@ define([
cb = cb || function () {}; cb = cb || function () {};
if (force !== true) { msg = Util.fixHTML(msg); } if (force !== true) { msg = Util.fixHTML(msg); }
var keyHandler = listenForKeys(function (e) { // yes var keyHandler = listenForKeys(function () { // yes
findOKButton().click(); findOKButton().click();
}, function (e) { // no }, function () { // no
findCancelButton().click(); findCancelButton().click();
}); });
@ -90,9 +90,9 @@ define([
cb = cb || function () {}; cb = cb || function () {};
if (force !== true) { msg = Util.fixHTML(msg); } if (force !== true) { msg = Util.fixHTML(msg); }
var keyHandler = listenForKeys(function (e) { var keyHandler = listenForKeys(function () {
findOKButton().click(); findOKButton().click();
}, function (e) { }, function () {
findCancelButton().click(); findCancelButton().click();
}); });
@ -183,7 +183,7 @@ define([
} }
if (Messages.tips && !hideTips) { if (Messages.tips && !hideTips) {
var $loadingTip = $('<div>', {'id': 'loadingTip'}); var $loadingTip = $('<div>', {'id': 'loadingTip'});
var $tip = $('<span>', {'class': 'tips'}).text(getRandomTip()).appendTo($loadingTip); $('<span>', {'class': 'tips'}).text(getRandomTip()).appendTo($loadingTip);
$loadingTip.css({ $loadingTip.css({
'top': $('body').height()/2 + $container.height()/2 + 20 + 'px' 'top': $('body').height()/2 + $container.height()/2 + 20 + 'px'
}); });
@ -204,7 +204,7 @@ define([
$('#' + LOADING).find('p').html(error || Messages.error); $('#' + LOADING).find('p').html(error || Messages.error);
}; };
var importContent = UI.importContent = function (type, f) { UI.importContent = function (type, f) {
return function () { return function () {
var $files = $('<input type="file">').click(); var $files = $('<input type="file">').click();
$files.on('change', function (e) { $files.on('change', function (e) {

@ -1,20 +1,20 @@
define([], function () { define([], function () {
var Util = {}; var Util = {};
var find = Util.find = function (map, path) { Util.find = function (map, path) {
return (map && path.reduce(function (p, n) { return (map && path.reduce(function (p, n) {
return typeof(p[n]) !== 'undefined' && p[n]; return typeof(p[n]) !== 'undefined' && p[n];
}, map)); }, map));
}; };
var fixHTML = Util.fixHTML = function (str) { Util.fixHTML = function (str) {
if (!str) { return ''; } if (!str) { return ''; }
return str.replace(/[<>&"']/g, function (x) { return str.replace(/[<>&"']/g, function (x) {
return ({ "<": "&lt;", ">": "&gt", "&": "&amp;", '"': "&#34;", "'": "&#39;" })[x]; return ({ "<": "&lt;", ">": "&gt", "&": "&amp;", '"': "&#34;", "'": "&#39;" })[x];
}); });
}; };
var hexToBase64 = Util.hexToBase64 = function (hex) { Util.hexToBase64 = function (hex) {
var hexArray = hex var hexArray = hex
.replace(/\r|\n/g, "") .replace(/\r|\n/g, "")
.replace(/([\da-fA-F]{2}) ?/g, "0x$1 ") .replace(/([\da-fA-F]{2}) ?/g, "0x$1 ")
@ -24,7 +24,7 @@ define([], function () {
return window.btoa(byteString).replace(/\//g, '-').slice(0,-2); return window.btoa(byteString).replace(/\//g, '-').slice(0,-2);
}; };
var base64ToHex = Util.base64ToHex = function (b64String) { Util.base64ToHex = function (b64String) {
var hexArray = []; var hexArray = [];
atob(b64String.replace(/-/g, '/')).split("").forEach(function(e){ atob(b64String.replace(/-/g, '/')).split("").forEach(function(e){
var h = e.charCodeAt(0).toString(16); var h = e.charCodeAt(0).toString(16);
@ -34,9 +34,9 @@ define([], function () {
return hexArray.join(""); return hexArray.join("");
}; };
var uint8ArrayToHex = Util.uint8ArrayToHex = function (a) { Util.uint8ArrayToHex = function (a) {
// call slice so Uint8Arrays work as expected // call slice so Uint8Arrays work as expected
return Array.prototype.slice.call(a).map(function (e, i) { return Array.prototype.slice.call(a).map(function (e) {
var n = Number(e & 0xff).toString(16); var n = Number(e & 0xff).toString(16);
if (n === 'NaN') { if (n === 'NaN') {
throw new Error('invalid input resulted in NaN'); throw new Error('invalid input resulted in NaN');
@ -51,7 +51,7 @@ define([], function () {
}).join(''); }).join('');
}; };
var deduplicateString = Util.deduplicateString = function (array) { Util.deduplicateString = function (array) {
var a = array.slice(); var a = array.slice();
for(var i=0; i<a.length; i++) { for(var i=0; i<a.length; i++) {
for(var j=i+1; j<a.length; j++) { for(var j=i+1; j<a.length; j++) {
@ -61,11 +61,11 @@ define([], function () {
return a; return a;
}; };
var getHash = Util.getHash = function () { Util.getHash = function () {
return window.location.hash.slice(1); return window.location.hash.slice(1);
}; };
var replaceHash = Util.replaceHash = function (hash) { Util.replaceHash = function (hash) {
if (window.history && window.history.replaceState) { if (window.history && window.history.replaceState) {
if (!/^#/.test(hash)) { hash = '#' + hash; } if (!/^#/.test(hash)) { hash = '#' + hash; }
return void window.history.replaceState({}, window.document.title, hash); return void window.history.replaceState({}, window.document.title, hash);
@ -76,16 +76,16 @@ define([], function () {
/* /*
* Saving files * Saving files
*/ */
var fixFileName = Util.fixFileName = function (filename) { Util.fixFileName = function (filename) {
return filename.replace(/ /g, '-').replace(/[\/\?]/g, '_') return filename.replace(/ /g, '-').replace(/[\/\?]/g, '_')
.replace(/_+/g, '_'); .replace(/_+/g, '_');
}; };
var bytesToMegabytes = Util.bytesToMegabytes = function (bytes) { Util.bytesToMegabytes = function (bytes) {
return Math.floor((bytes / (1024 * 1024) * 100)) / 100; return Math.floor((bytes / (1024 * 1024) * 100)) / 100;
}; };
var bytesToKilobytes = Util.bytesToKilobytes = function (bytes) { Util.bytesToKilobytes = function (bytes) {
return Math.floor(bytes / 1024 * 100) / 100; return Math.floor(bytes / 1024 * 100) / 100;
}; };

@ -8,20 +8,19 @@ define([
return typeof(x) === 'string'; return typeof(x) === 'string';
}; };
var isValidUsername = Cred.isValidUsername = function (name) { Cred.isValidUsername = function (name) {
return !!(name && isString(name)); return !!(name && isString(name));
}; };
var isValidPassword = Cred.isValidPassword = function (passwd) { Cred.isValidPassword = function (passwd) {
return !!(passwd && isString(passwd)); return !!(passwd && isString(passwd));
}; };
var passwordsMatch = Cred.passwordsMatch = function (a, b) { Cred.passwordsMatch = function (a, b) {
return isString(a) && isString(b) && a === b; return isString(a) && isString(b) && a === b;
}; };
var deriveFromPassphrase = Cred.deriveFromPassphrase = function Cred.deriveFromPassphrase = function (username, password, len, cb) {
(username, password, len, cb) {
Scrypt(password, Scrypt(password,
username, username,
8, // memoryCost (n) 8, // memoryCost (n)
@ -32,7 +31,7 @@ define([
undefined); // format, could be 'base64' undefined); // format, could be 'base64'
}; };
var dispenser = Cred.dispenser = function (bytes) { Cred.dispenser = function (bytes) {
var entropy = { var entropy = {
used: 0, used: 0,
}; };

@ -5,8 +5,8 @@ define([
'/common/cryptpad-common.js', '/common/cryptpad-common.js',
'/bower_components/textpatcher/TextPatcher.js' '/bower_components/textpatcher/TextPatcher.js'
], function ($, Crypto, Realtime, Cryptpad, TextPatcher) { ], function ($, Crypto, Realtime, Cryptpad, TextPatcher) {
var Messages = Cryptpad.Messages; //var Messages = Cryptpad.Messages;
var noop = function () {}; //var noop = function () {};
var finish = function (S, err, doc) { var finish = function (S, err, doc) {
if (S.done) { return; } if (S.done) { return; }
S.cb(err, doc); S.cb(err, doc);
@ -50,14 +50,14 @@ define([
var Session = { cb: cb, }; var Session = { cb: cb, };
var config = makeConfig(hash); var config = makeConfig(hash);
var onReady = config.onReady = function (info) { config.onReady = function (info) {
var rt = Session.session = info.realtime; var rt = Session.session = info.realtime;
Session.network = info.network; Session.network = info.network;
finish(Session, void 0, rt.getUserDoc()); finish(Session, void 0, rt.getUserDoc());
}; };
overwrite(config, opt); overwrite(config, opt);
var realtime = Session.realtime = Realtime.start(config); Session.realtime = Realtime.start(config);
}; };
var put = function (hash, doc, cb, opt) { var put = function (hash, doc, cb, opt) {
@ -87,7 +87,7 @@ define([
}; };
overwrite(config, opt); overwrite(config, opt);
var realtime = Session.session = Realtime.start(config); Session.session = Realtime.start(config);
}; };
return { return {

@ -29,7 +29,7 @@ define([
var userHashKey = common.userHashKey = 'User_hash'; var userHashKey = common.userHashKey = 'User_hash';
var userNameKey = common.userNameKey = 'User_name'; var userNameKey = common.userNameKey = 'User_name';
var fileHashKey = common.fileHashKey = 'FS_hash'; var fileHashKey = common.fileHashKey = 'FS_hash';
var displayNameKey = common.displayNameKey = 'cryptpad.username'; common.displayNameKey = 'cryptpad.username';
var newPadNameKey = common.newPadNameKey = "newPadName"; var newPadNameKey = common.newPadNameKey = "newPadName";
var newPadPathKey = common.newPadPathKey = "newPadPath"; var newPadPathKey = common.newPadPathKey = "newPadPath";
var storageKey = common.storageKey = 'CryptPad_RECENTPADS'; var storageKey = common.storageKey = 'CryptPad_RECENTPADS';
@ -39,10 +39,10 @@ define([
var rpc; var rpc;
// import UI elements // import UI elements
var findCancelButton = common.findCancelButton = UI.findCancelButton; common.findCancelButton = UI.findCancelButton;
var findOKButton = common.findOKButton = UI.findOKButton; common.findOKButton = UI.findOKButton;
var listenForKeys = common.listenForKeys = UI.listenForKeys; common.listenForKeys = UI.listenForKeys;
var stopListening = common.stopListening = UI.stopListening; common.stopListening = UI.stopListening;
common.prompt = UI.prompt; common.prompt = UI.prompt;
common.confirm = UI.confirm; common.confirm = UI.confirm;
common.alert = UI.alert; common.alert = UI.alert;
@ -54,15 +54,15 @@ define([
common.errorLoadingScreen = UI.errorLoadingScreen; common.errorLoadingScreen = UI.errorLoadingScreen;
// import common utilities for export // import common utilities for export
var find = common.find = Util.find; common.find = Util.find;
var fixHTML = common.fixHTML = Util.fixHTML; var fixHTML = common.fixHTML = Util.fixHTML;
var hexToBase64 = common.hexToBase64 = Util.hexToBase64; common.hexToBase64 = Util.hexToBase64;
var base64ToHex = common.base64ToHex = Util.base64ToHex; common.base64ToHex = Util.base64ToHex;
var deduplicateString = common.deduplicateString = Util.deduplicateString; var deduplicateString = common.deduplicateString = Util.deduplicateString;
var uint8ArrayToHex = common.uint8ArrayToHex = Util.uint8ArrayToHex; common.uint8ArrayToHex = Util.uint8ArrayToHex;
var replaceHash = common.replaceHash = Util.replaceHash; common.replaceHash = Util.replaceHash;
var getHash = common.getHash = Util.getHash; var getHash = common.getHash = Util.getHash;
var fixFileName = common.fixFileName = Util.fixFileName; common.fixFileName = Util.fixFileName;
common.bytesToMegabytes = Util.bytesToMegabytes; common.bytesToMegabytes = Util.bytesToMegabytes;
common.bytesToKilobytes = Util.bytesToKilobytes; common.bytesToKilobytes = Util.bytesToKilobytes;
@ -121,13 +121,13 @@ define([
}); });
}; };
var reportAppUsage = common.reportAppUsage = function () { common.reportAppUsage = function () {
var pattern = window.location.pathname.split('/') var pattern = window.location.pathname.split('/')
.filter(function (x) { return x; }).join('.'); .filter(function (x) { return x; }).join('.');
feedback(pattern); feedback(pattern);
}; };
var getUid = common.getUid = function () { common.getUid = function () {
if (store && store.getProxy() && store.getProxy().proxy) { if (store && store.getProxy() && store.getProxy().proxy) {
return store.getProxy().proxy.uid; return store.getProxy().proxy.uid;
} }
@ -152,7 +152,7 @@ define([
}, 0); }, 0);
}; };
var getWebsocketURL = common.getWebsocketURL = function () { common.getWebsocketURL = function () {
if (!Config.websocketPath) { return Config.websocketURL; } if (!Config.websocketPath) { return Config.websocketURL; }
var path = Config.websocketPath; var path = Config.websocketPath;
if (/^ws{1,2}:\/\//.test(path)) { return path; } if (/^ws{1,2}:\/\//.test(path)) { return path; }
@ -164,7 +164,7 @@ define([
return url; return url;
}; };
var login = common.login = function (hash, name, cb) { common.login = function (hash, name, cb) {
if (!hash) { throw new Error('expected a user hash'); } if (!hash) { throw new Error('expected a user hash'); }
if (!name) { throw new Error('expected a user name'); } if (!name) { throw new Error('expected a user name'); }
hash = common.serializeHash(hash); hash = common.serializeHash(hash);
@ -188,7 +188,7 @@ define([
}; };
var logoutHandlers = []; var logoutHandlers = [];
var logout = common.logout = function (cb) { common.logout = function (cb) {
[ [
userNameKey, userNameKey,
userHashKey, userHashKey,
@ -211,7 +211,7 @@ define([
if (cb) { cb(); } if (cb) { cb(); }
}; };
var onLogout = common.onLogout = function (h) { common.onLogout = function (h) {
if (typeof (h) !== "function") { return; } if (typeof (h) !== "function") { return; }
if (logoutHandlers.indexOf(h) !== -1) { return; } if (logoutHandlers.indexOf(h) !== -1) { return; }
logoutHandlers.push(h); logoutHandlers.push(h);
@ -232,7 +232,7 @@ define([
return typeof getUserHash() === "string"; return typeof getUserHash() === "string";
}; };
var hasSigningKeys = common.hasSigningKeys = function (proxy) { common.hasSigningKeys = function (proxy) {
return typeof(proxy) === 'object' && return typeof(proxy) === 'object' &&
typeof(proxy.edPrivate) === 'string' && typeof(proxy.edPrivate) === 'string' &&
typeof(proxy.edPublic) === 'string'; typeof(proxy.edPublic) === 'string';
@ -308,7 +308,7 @@ define([
}; };
// Get the pads from localStorage to migrate them to the object store // Get the pads from localStorage to migrate them to the object store
var getLegacyPads = common.getLegacyPads = function (cb) { common.getLegacyPads = function (cb) {
require(['/customize/store.js'], function(Legacy) { // TODO DEPRECATE_F require(['/customize/store.js'], function(Legacy) { // TODO DEPRECATE_F
Legacy.ready(function (err, legacy) { Legacy.ready(function (err, legacy) {
if (err) { cb(err, null); return; } if (err) { cb(err, null); return; }
@ -328,7 +328,6 @@ define([
// Create untitled documents when no name is given // Create untitled documents when no name is given
var getDefaultName = common.getDefaultName = function (parsed) { var getDefaultName = common.getDefaultName = function (parsed) {
var type = parsed.type; var type = parsed.type;
var untitledIndex = 1;
var name = (Messages.type)[type] + ' - ' + new Date().toString().split(' ').slice(0,4).join(' '); var name = (Messages.type)[type] + ' - ' + new Date().toString().split(' ').slice(0,4).join(' ');
return name; return name;
}; };
@ -348,37 +347,37 @@ define([
}; };
/* Sort pads according to how recently they were accessed */ /* Sort pads according to how recently they were accessed */
var mostRecent = common.mostRecent = function (a, b) { common.mostRecent = function (a, b) {
return new Date(b.atime).getTime() - new Date(a.atime).getTime(); return new Date(b.atime).getTime() - new Date(a.atime).getTime();
}; };
// STORAGE // STORAGE
var setPadAttribute = common.setPadAttribute = function (attr, value, cb) { common.setPadAttribute = function (attr, value, cb) {
getStore().setDrive([getHash(), attr].join('.'), value, function (err, data) { getStore().setDrive([getHash(), attr].join('.'), value, function (err, data) {
cb(err, data); cb(err, data);
}); });
}; };
var setAttribute = common.setAttribute = function (attr, value, cb) { common.setAttribute = function (attr, value, cb) {
getStore().set(["cryptpad", attr].join('.'), value, function (err, data) { getStore().set(["cryptpad", attr].join('.'), value, function (err, data) {
cb(err, data); cb(err, data);
}); });
}; };
var setLSAttribute = common.setLSAttribute = function (attr, value) { common.setLSAttribute = function (attr, value) {
localStorage[attr] = value; localStorage[attr] = value;
}; };
// STORAGE // STORAGE
var getPadAttribute = common.getPadAttribute = function (attr, cb) { common.getPadAttribute = function (attr, cb) {
getStore().getDrive([getHash(), attr].join('.'), function (err, data) { getStore().getDrive([getHash(), attr].join('.'), function (err, data) {
cb(err, data); cb(err, data);
}); });
}; };
var getAttribute = common.getAttribute = function (attr, cb) { common.getAttribute = function (attr, cb) {
getStore().get(["cryptpad", attr].join('.'), function (err, data) { getStore().get(["cryptpad", attr].join('.'), function (err, data) {
cb(err, data); cb(err, data);
}); });
}; };
var getLSAttribute = common.getLSAttribute = function (attr) { common.getLSAttribute = function (attr) {
return localStorage[attr]; return localStorage[attr];
}; };
@ -393,19 +392,19 @@ define([
}); });
return templates; return templates;
}; };
var addTemplate = common.addTemplate = function (data) { common.addTemplate = function (data) {
getStore().pushData(data); getStore().pushData(data);
getStore().addPad(data.href, ['template']); getStore().addPad(data.href, ['template']);
}; };
var isTemplate = common.isTemplate = function (href) { common.isTemplate = function (href) {
var rhref = getRelativeHref(href); var rhref = getRelativeHref(href);
var templates = listTemplates(); var templates = listTemplates();
return templates.some(function (t) { return templates.some(function (t) {
return t.href === rhref; return t.href === rhref;
}); });
}; };
var selectTemplate = common.selectTemplate = function (type, rt, Crypt) { common.selectTemplate = function (type, rt, Crypt) {
if (!AppConfig.enableTemplates) { return; } if (!AppConfig.enableTemplates) { return; }
var temps = listTemplates(type); var temps = listTemplates(type);
if (temps.length === 0) { return; } if (temps.length === 0) { return; }
@ -423,7 +422,7 @@ define([
Crypt.get(parsed.hash, function (err, val) { Crypt.get(parsed.hash, function (err, val) {
if (err) { throw new Error(err); } if (err) { throw new Error(err); }
var p = parsePadUrl(window.location.href); var p = parsePadUrl(window.location.href);
Crypt.put(p.hash, val, function (e) { Crypt.put(p.hash, val, function () {
common.findOKButton().click(); common.findOKButton().click();
common.removeLoadingScreen(); common.removeLoadingScreen();
}); });
@ -448,28 +447,28 @@ define([
}; };
// STORAGE: Display Name // STORAGE: Display Name
var getLastName = common.getLastName = function (cb) { common.getLastName = function (cb) {
common.getAttribute('username', function (err, userName) { common.getAttribute('username', function (err, userName) {
cb(err, userName); cb(err, userName);
}); });
}; };
var _onDisplayNameChanged = []; var _onDisplayNameChanged = [];
var onDisplayNameChanged = common.onDisplayNameChanged = function (h) { common.onDisplayNameChanged = function (h) {
if (typeof(h) !== "function") { return; } if (typeof(h) !== "function") { return; }
if (_onDisplayNameChanged.indexOf(h) !== -1) { return; } if (_onDisplayNameChanged.indexOf(h) !== -1) { return; }
_onDisplayNameChanged.push(h); _onDisplayNameChanged.push(h);
}; };
var changeDisplayName = common.changeDisplayName = function (newName) { common.changeDisplayName = function (newName) {
_onDisplayNameChanged.forEach(function (h) { _onDisplayNameChanged.forEach(function (h) {
h(newName); h(newName);
}); });
}; };
// STORAGE // STORAGE
var forgetPad = common.forgetPad = function (href, cb) { common.forgetPad = function (href, cb) {
var parsed = parsePadUrl(href); var parsed = parsePadUrl(href);
var callback = function (err, data) { var callback = function (err) {
if (err) { if (err) {
cb(err); cb(err);
return; return;
@ -511,7 +510,7 @@ define([
} }
}); });
}; };
var setPadTitle = common.setPadTitle = function (name, cb) { common.setPadTitle = function (name, cb) {
var href = window.location.href; var href = window.location.href;
var parsed = parsePadUrl(href); var parsed = parsePadUrl(href);
href = getRelativeHref(href); href = getRelativeHref(href);
@ -525,7 +524,7 @@ define([
var updateWeaker = []; var updateWeaker = [];
var contains; var contains;
var renamed = recent.map(function (pad) { recent.forEach(function (pad) {
var p = parsePadUrl(pad.href); var p = parsePadUrl(pad.href);
if (p.type !== parsed.type) { return pad; } if (p.type !== parsed.type) { return pad; }
@ -610,7 +609,7 @@ define([
/* /*
* Buttons * Buttons
*/ */
var renamePad = common.renamePad = function (title, callback) { common.renamePad = function (title, callback) {
if (title === null) { return; } if (title === null) { return; }
if (title.trim() === "") { if (title.trim() === "") {
@ -618,7 +617,7 @@ define([
title = getDefaultName(parsed); title = getDefaultName(parsed);
} }
common.setPadTitle(title, function (err, data) { common.setPadTitle(title, function (err) {
if (err) { if (err) {
console.log("unable to set pad title"); console.log("unable to set pad title");
console.log(err); console.log(err);
@ -668,7 +667,7 @@ define([
return true; return true;
}; };
var arePinsSynced = common.arePinsSynced = function (cb) { common.arePinsSynced = function (cb) {
if (!pinsReady()) { return void cb ('[RPC_NOT_READY]'); } if (!pinsReady()) { return void cb ('[RPC_NOT_READY]'); }
var list = getCanonicalChannelList(); var list = getCanonicalChannelList();
@ -679,7 +678,7 @@ define([
}); });
}; };
var resetPins = common.resetPins = function (cb) { common.resetPins = function (cb) {
if (!pinsReady()) { return void cb ('[RPC_NOT_READY]'); } if (!pinsReady()) { return void cb ('[RPC_NOT_READY]'); }
var list = getCanonicalChannelList(); var list = getCanonicalChannelList();
@ -689,7 +688,7 @@ define([
}); });
}; };
var pinPads = common.pinPads = function (pads, cb) { common.pinPads = function (pads, cb) {
if (!pinsReady()) { return void cb ('[RPC_NOT_READY]'); } if (!pinsReady()) { return void cb ('[RPC_NOT_READY]'); }
rpc.pin(pads, function (e, hash) { rpc.pin(pads, function (e, hash) {
@ -698,7 +697,7 @@ define([
}); });
}; };
var unpinPads = common.unpinPads = function (pads, cb) { common.unpinPads = function (pads, cb) {
if (!pinsReady()) { return void cb ('[RPC_NOT_READY]'); } if (!pinsReady()) { return void cb ('[RPC_NOT_READY]'); }
rpc.unpin(pads, function (e, hash) { rpc.unpin(pads, function (e, hash) {
@ -707,12 +706,12 @@ define([
}); });
}; };
var getPinnedUsage = common.getPinnedUsage = function (cb) { common.getPinnedUsage = function (cb) {
if (!pinsReady()) { return void cb('[RPC_NOT_READY]'); } if (!pinsReady()) { return void cb('[RPC_NOT_READY]'); }
rpc.getFileListSize(cb); rpc.getFileListSize(cb);
}; };
var getFileSize = common.getFileSize = function (href, cb) { common.getFileSize = function (href, cb) {
var channelId = Hash.hrefToHexChannelId(href); var channelId = Hash.hrefToHexChannelId(href);
rpc.getFileSize(channelId, function (e, bytes) { rpc.getFileSize(channelId, function (e, bytes) {
if (e) { return void cb(e); } if (e) { return void cb(e); }
@ -720,11 +719,11 @@ define([
}); });
}; };
var getPinLimit = common.getPinLimit = function (cb) { common.getPinLimit = function (cb) {
cb(void 0, typeof(AppConfig.pinLimit) === 'number'? AppConfig.pinLimit: 1000); cb(void 0, typeof(AppConfig.pinLimit) === 'number'? AppConfig.pinLimit: 1000);
}; };
var isOverPinLimit = common.isOverPinLimit = function (cb) { common.isOverPinLimit = function (cb) {
if (!common.isLoggedIn() || !AppConfig.enablePinLimit) { return void cb(null, false); } if (!common.isLoggedIn() || !AppConfig.enablePinLimit) { return void cb(null, false); }
var usage; var usage;
var andThen = function (e, limit) { var andThen = function (e, limit) {
@ -743,7 +742,7 @@ define([
common.getPinnedUsage(todo); common.getPinnedUsage(todo);
}; };
var createButton = common.createButton = function (type, rightside, data, callback) { common.createButton = function (type, rightside, data, callback) {
var button; var button;
var size = "17px"; var size = "17px";
switch (type) { switch (type) {
@ -832,7 +831,7 @@ define([
var href = window.location.href; var href = window.location.href;
common.confirm(Messages.forgetPrompt, function (yes) { common.confirm(Messages.forgetPrompt, function (yes) {
if (!yes) { return; } if (!yes) { return; }
common.forgetPad(href, function (err, data) { common.forgetPad(href, function (err) {
if (err) { if (err) {
console.log("unable to forget pad"); console.log("unable to forget pad");
console.error(err); console.error(err);
@ -1051,7 +1050,7 @@ define([
// Provide $container if you want to put the generated block in another element // Provide $container if you want to put the generated block in another element
// Provide $initBlock if you already have the menu block and you want the content inserted in it // Provide $initBlock if you already have the menu block and you want the content inserted in it
var createLanguageSelector = common.createLanguageSelector = function ($container, $initBlock) { common.createLanguageSelector = function ($container, $initBlock) {
var options = []; var options = [];
var languages = Messages._languages; var languages = Messages._languages;
var keys = Object.keys(languages).sort(); var keys = Object.keys(languages).sort();
@ -1085,7 +1084,7 @@ define([
return $block; return $block;
}; };
var createUserAdminMenu = common.createUserAdminMenu = function (config) { common.createUserAdminMenu = function (config) {
var $displayedName = $('<span>', {'class': config.displayNameCls || 'displayName'}); var $displayedName = $('<span>', {'class': config.displayNameCls || 'displayName'});
var accountName = localStorage[common.userNameKey]; var accountName = localStorage[common.userNameKey];
var account = isLoggedIn(); var account = isLoggedIn();
@ -1172,24 +1171,24 @@ define([
}; };
var $userAdmin = createDropdown(dropdownConfigUser); var $userAdmin = createDropdown(dropdownConfigUser);
$userAdmin.find('a.logout').click(function (e) { $userAdmin.find('a.logout').click(function () {
common.logout(); common.logout();
window.location.href = '/'; window.location.href = '/';
}); });
$userAdmin.find('a.settings').click(function (e) { $userAdmin.find('a.settings').click(function () {
if (parsed && parsed.type) { if (parsed && parsed.type) {
window.open('/settings/'); window.open('/settings/');
} else { } else {
window.location.href = '/settings/'; window.location.href = '/settings/';
} }
}); });
$userAdmin.find('a.login').click(function (e) { $userAdmin.find('a.login').click(function () {
if (window.location.pathname !== "/") { if (window.location.pathname !== "/") {
sessionStorage.redirectTo = window.location.href; sessionStorage.redirectTo = window.location.href;
} }
window.location.href = '/login/'; window.location.href = '/login/';
}); });
$userAdmin.find('a.register').click(function (e) { $userAdmin.find('a.register').click(function () {
if (window.location.pathname !== "/") { if (window.location.pathname !== "/") {
sessionStorage.redirectTo = window.location.href; sessionStorage.redirectTo = window.location.href;
} }
@ -1281,7 +1280,8 @@ define([
common.arePinsSynced(function (err, yes) { common.arePinsSynced(function (err, yes) {
if (!yes) { if (!yes) {
common.resetPins(function (err, hash) { common.resetPins(function (err) {
if (err) { console.error(err); }
console.log('RESET DONE'); console.log('RESET DONE');
}); });
} }

@ -1,9 +1,7 @@
define([ define([
'/common/treesome.js', '/common/treesome.js',
'/bower_components/rangy/rangy-core.min.js' '/bower_components/rangy/rangy-core.min.js'
], function (Tree, Rangy, saveRestore) { ], function (Tree, Rangy) {
var log = function (x) { console.log(x); };
var error = function (x) { console.log(x); };
var verbose = function (x) { if (window.verboseMode) { console.log(x); } }; var verbose = function (x) { if (window.verboseMode) { console.log(x); } };
/* accepts the document used by the editor */ /* accepts the document used by the editor */
@ -45,7 +43,7 @@ define([
}); });
}; };
var exists = cursor.exists = function () { cursor.exists = function () {
return (Range.start.el?1:0) | (Range.end.el?2:0); return (Range.start.el?1:0) | (Range.end.el?2:0);
}; };
@ -55,7 +53,7 @@ define([
2 if end 2 if end
3 if start and end 3 if start and end
*/ */
var inNode = cursor.inNode = function (el) { cursor.inNode = function (el) {
var state = ['start', 'end'].map(function (pos, i) { var state = ['start', 'end'].map(function (pos, i) {
return Tree.contains(el, Range[pos].el)? i +1: 0; return Tree.contains(el, Range[pos].el)? i +1: 0;
}); });
@ -122,7 +120,7 @@ define([
} }
}; };
var pushDelta = cursor.pushDelta = function (oldVal, newVal, offset) { cursor.pushDelta = function (oldVal, newVal) {
if (oldVal === newVal) { return; } if (oldVal === newVal) { return; }
var commonStart = 0; var commonStart = 0;
while (oldVal.charAt(commonStart) === newVal.charAt(commonStart)) { while (oldVal.charAt(commonStart) === newVal.charAt(commonStart)) {

@ -1,7 +1,7 @@
define([], function () { define([], function () {
var exports = {}; var exports = {};
var hexToUint8Array = exports.hexToUint8Array = function (s) { exports.hexToUint8Array = function (s) {
// if not hex or odd number of characters // if not hex or odd number of characters
if (!/[a-fA-F0-9]+/.test(s) || s.length % 2) { throw new Error("string is not hex"); } if (!/[a-fA-F0-9]+/.test(s) || s.length % 2) { throw new Error("string is not hex"); }
return s.split(/([0-9a-fA-F]{2})/) return s.split(/([0-9a-fA-F]{2})/)
@ -9,7 +9,7 @@ define([], function () {
.map(function (x) { return Number('0x' + x); }); .map(function (x) { return Number('0x' + x); });
}; };
var uint8ArrayToHex = exports.uint8ArrayToHex = function (a) { exports.uint8ArrayToHex = function (a) {
return a.reduce(function(memo, i) { return a.reduce(function(memo, i) {
return memo + ((i < 16) ? '0' : '') + i.toString(16); return memo + ((i < 16) ? '0' : '') + i.toString(16);
}, ''); }, '');

@ -10,7 +10,7 @@ define([
var TRASH = module.TRASH = "trash"; var TRASH = module.TRASH = "trash";
var TEMPLATE = module.TEMPLATE = "template"; var TEMPLATE = module.TEMPLATE = "template";
var init = module.init = function (files, config) { module.init = function (files, config) {
var Cryptpad = config.Cryptpad; var Cryptpad = config.Cryptpad;
Messages = Cryptpad.Messages; Messages = Cryptpad.Messages;
@ -18,7 +18,7 @@ define([
var NEW_FOLDER_NAME = Messages.fm_newFolder; var NEW_FOLDER_NAME = Messages.fm_newFolder;
var NEW_FILE_NAME = Messages.fm_newFile; var NEW_FILE_NAME = Messages.fm_newFile;
var DEBUG = config.DEBUG || false; //var DEBUG = config.DEBUG || false;
var logging = function () { var logging = function () {
console.log.apply(console, arguments); console.log.apply(console, arguments);
}; };
@ -34,7 +34,7 @@ define([
console.error.apply(console, arguments); console.error.apply(console, arguments);
}; };
var getStructure = exp.getStructure = function () { exp.getStructure = function () {
var a = {}; var a = {};
a[ROOT] = {}; a[ROOT] = {};
a[UNSORTED] = []; a[UNSORTED] = [];
@ -92,7 +92,7 @@ define([
return path[0] === TRASH && path.length === 4; return path[0] === TRASH && path.length === 4;
}; };
var isPathInFilesData = exp.isPathInFilesData = function (path) { exp.isPathInFilesData = function (path) {
return path[0] && path[0] === FILES_DATA; return path[0] && path[0] === FILES_DATA;
}; };
@ -100,7 +100,7 @@ define([
return typeof(element) === "string"; return typeof(element) === "string";
}; };
var isReadOnlyFile = exp.isReadOnlyFile = function (element) { exp.isReadOnlyFile = function (element) {
if (!isFile(element)) { return false; } if (!isFile(element)) { return false; }
var parsed = Cryptpad.parsePadUrl(element); var parsed = Cryptpad.parsePadUrl(element);
if (!parsed) { return false; } if (!parsed) { return false; }
@ -114,15 +114,15 @@ define([
return typeof(element) !== "string"; return typeof(element) !== "string";
}; };
var isFolderEmpty = exp.isFolderEmpty = function (element) { exp.isFolderEmpty = function (element) {
if (typeof(element) !== "object") { return false; } if (typeof(element) !== "object") { return false; }
return Object.keys(element).length === 0; return Object.keys(element).length === 0;
}; };
var hasSubfolder = exp.hasSubfolder = function (element, trashRoot) { exp.hasSubfolder = function (element, trashRoot) {
if (typeof(element) !== "object") { return false; } if (typeof(element) !== "object") { return false; }
var subfolder = 0; var subfolder = 0;
var addSubfolder = function (el, idx) { var addSubfolder = function (el) {
subfolder += isFolder(el.element) ? 1 : 0; subfolder += isFolder(el.element) ? 1 : 0;
}; };
for (var f in element) { for (var f in element) {
@ -137,10 +137,10 @@ define([
return subfolder; return subfolder;
}; };
var hasFile = exp.hasFile = function (element, trashRoot) { exp.hasFile = function (element, trashRoot) {
if (typeof(element) !== "object") { return false; } if (typeof(element) !== "object") { return false; }
var file = 0; var file = 0;
var addFile = function (el, idx) { var addFile = function (el) {
file += isFile(el.element) ? 1 : 0; file += isFile(el.element) ? 1 : 0;
}; };
for (var f in element) { for (var f in element) {
@ -189,10 +189,10 @@ define([
return inTree; return inTree;
}; };
var isFileInTrash = function (file) { /* var isFileInTrash = function (file) {
var inTrash = false; var inTrash = false;
var root = files[TRASH]; var root = files[TRASH];
var filter = function (trashEl, idx) { var filter = function (trashEl) {
inTrash = isFileInTree(file, trashEl.element); inTrash = isFileInTree(file, trashEl.element);
return inTrash; return inTrash;
}; };
@ -205,11 +205,7 @@ define([
if (inTrash) { break; } if (inTrash) { break; }
} }
return inTrash; return inTrash;
}; };*/
var isFileInUnsorted = function (file) {
return files[UNSORTED].indexOf(file) !== -1;
};
var getUnsortedFiles = exp.getUnsortedFiles = function () { var getUnsortedFiles = exp.getUnsortedFiles = function () {
if (!files[UNSORTED]) { if (!files[UNSORTED]) {
@ -244,7 +240,7 @@ define([
var getTrashFiles = exp.getTrashFiles = function () { var getTrashFiles = exp.getTrashFiles = function () {
var root = files[TRASH]; var root = files[TRASH];
var ret = []; var ret = [];
var addFiles = function (el, idx) { var addFiles = function (el) {
if (isFile(el.element)) { if (isFile(el.element)) {
if(ret.indexOf(el.element) === -1) { ret.push(el.element); } if(ret.indexOf(el.element) === -1) { ret.push(el.element); }
} else { } else {
@ -261,7 +257,7 @@ define([
return ret; return ret;
}; };
var getFilesDataFiles = exp.getFilesDataFiles = function () { exp.getFilesDataFiles = function () {
var ret = []; var ret = [];
files[FILES_DATA].forEach(function (el) { files[FILES_DATA].forEach(function (el) {
if (el.href && ret.indexOf(el.href) === -1) { if (el.href && ret.indexOf(el.href) === -1) {
@ -351,7 +347,7 @@ define([
return rootpaths.concat(unsortedpaths, templatepaths, trashpaths); return rootpaths.concat(unsortedpaths, templatepaths, trashpaths);
}; };
var search = exp.search = function (value) { exp.search = function (value) {
if (typeof(value) !== "string") { return []; } if (typeof(value) !== "string") { return []; }
var res = []; var res = [];
// Search in ROOT // Search in ROOT
@ -402,7 +398,7 @@ define([
var ret = []; var ret = [];
res.forEach(function (l) { res.forEach(function (l) {
var paths = findFile(l); //var paths = findFile(l);
ret.push({ ret.push({
paths: findFile(l), paths: findFile(l),
data: exp.getFileData(l) data: exp.getFileData(l)
@ -509,7 +505,7 @@ define([
files[TRASH][obj.name].splice(idx, 1); files[TRASH][obj.name].splice(idx, 1);
}); });
}; };
var deleteMultiplePermanently = exp.deletePathsPermanently = function (paths) { exp.deletePathsPermanently = function (paths) {
var hrefPaths = paths.filter(isPathInHrefArray); var hrefPaths = paths.filter(isPathInHrefArray);
var rootPaths = paths.filter(isPathInRoot); var rootPaths = paths.filter(isPathInRoot);
var trashPaths = paths.filter(isPathInTrash); var trashPaths = paths.filter(isPathInTrash);
@ -723,7 +719,7 @@ define([
if (cb) { cb(); } if (cb) { cb(); }
}; };
var moveElements = exp.moveElements = function (paths, newParentPath, cb) { exp.moveElements = function (paths, newParentPath, cb) {
var unsortedPaths = paths.filter(isPathInHrefArray); var unsortedPaths = paths.filter(isPathInHrefArray);
moveHrefArrayElements(unsortedPaths, newParentPath); moveHrefArrayElements(unsortedPaths, newParentPath);
// Copy the elements to their new location // Copy the elements to their new location
@ -735,7 +731,7 @@ define([
}; };
// Import elements in the file manager // Import elements in the file manager
var importElements = exp.importElements = function (elements, path, cb) { exp.importElements = function (elements, path, cb) {
if (!elements || elements.length === 0) { return; } if (!elements || elements.length === 0) { return; }
var newParent = findElement(files, path); var newParent = findElement(files, path);
if (!newParent) { debug("Trying to import elements into a non-existing folder"); return; } if (!newParent) { debug("Trying to import elements into a non-existing folder"); return; }
@ -748,7 +744,7 @@ define([
if(cb) { cb(); } if(cb) { cb(); }
}; };
var createNewFolder = exp.createNewFolder = function (folderPath, name, cb) { exp.createNewFolder = function (folderPath, name, cb) {
var parentEl = findElement(files, folderPath); var parentEl = findElement(files, folderPath);
var folderName = getAvailableName(parentEl, name || NEW_FOLDER_NAME); var folderName = getAvailableName(parentEl, name || NEW_FOLDER_NAME);
parentEl[folderName] = {}; parentEl[folderName] = {};
@ -767,7 +763,7 @@ define([
ctime: +new Date() ctime: +new Date()
}); });
}; };
var createNewFile = exp.createNewFile = function (filePath, name, type, cb) { exp.createNewFile = function (filePath, name, type, cb) {
var parentEl = findElement(files, filePath); var parentEl = findElement(files, filePath);
var fileName = getAvailableName(parentEl, name || NEW_FILE_NAME); var fileName = getAvailableName(parentEl, name || NEW_FILE_NAME);
var href = '/' + type + '/#' + Cryptpad.createRandomHash(); var href = '/' + type + '/#' + Cryptpad.createRandomHash();
@ -799,7 +795,7 @@ define([
}; };
// Restore an element (copy it elsewhere and remove from the trash root) // Restore an element (copy it elsewhere and remove from the trash root)
var restoreTrash = exp.restoreTrash = function (path, cb) { exp.restoreTrash = function (path, cb) {
if (!path || path.length !== 4 || path[0] !== TRASH) { if (!path || path.length !== 4 || path[0] !== TRASH) {
debug("restoreTrash was called from an element not in the trash root: ", path); debug("restoreTrash was called from an element not in the trash root: ", path);
return; return;
@ -838,7 +834,7 @@ define([
// Remove the last element from the path to get the parent path and the element name // Remove the last element from the path to get the parent path and the element name
var parentPath = path.slice(); var parentPath = path.slice();
var name; var name;
var element = findElement(files, path); //var element = findElement(files, path);
if (path.length === 4) { // Trash root if (path.length === 4) { // Trash root
name = path[1]; name = path[1];
parentPath.pop(); parentPath.pop();
@ -860,13 +856,13 @@ define([
if(cb) { cb(); } if(cb) { cb(); }
}; };
var emptyTrash = exp.emptyTrash = function (cb) { exp.emptyTrash = function (cb) {
files[TRASH] = {}; files[TRASH] = {};
checkDeletedFiles(); checkDeletedFiles();
if(cb) { cb(); } if(cb) { cb(); }
}; };
var deleteFileData = exp.deleteFileData = function (href, cb) { exp.deleteFileData = function (href, cb) {
if (workgroup) { return; } if (workgroup) { return; }
var toRemove = []; var toRemove = [];
@ -889,7 +885,7 @@ define([
if(cb) { cb(); } if(cb) { cb(); }
}; };
var renameElement = exp.renameElement = function (path, newName, cb) { exp.renameElement = function (path, newName, cb) {
if (path.length <= 1) { if (path.length <= 1) {
logError('Renaming `root` is forbidden'); logError('Renaming `root` is forbidden');
return; return;
@ -914,7 +910,7 @@ define([
}; };
var forgetPad = exp.forgetPad = function (href) { exp.forgetPad = function (href) {
if (workgroup) { return; } if (workgroup) { return; }
if (!href || !isFile(href)) { return; } if (!href || !isFile(href)) { return; }
var path; var path;
@ -985,7 +981,7 @@ define([
}; };
// Replace a href by a stronger one everywhere in the drive (except FILES_DATA) // Replace a href by a stronger one everywhere in the drive (except FILES_DATA)
var replaceHref = exp.replaceHref = function (o, n) { exp.replaceHref = function (o, n) {
if (!isFile(o) || !isFile(n)) { return; } if (!isFile(o) || !isFile(n)) { return; }
var paths = findFile(o); var paths = findFile(o);
@ -1012,7 +1008,7 @@ define([
// addTemplate is called when we want to add a new pad, never visited, to the templates list // addTemplate is called when we want to add a new pad, never visited, to the templates list
// first, we must add it to FILES_DATA, so the input has to be an fileDAta object // first, we must add it to FILES_DATA, so the input has to be an fileDAta object
var addTemplate = exp.addTemplate = function (fileData) { exp.addTemplate = function (fileData) {
if (workgroup) { return; } if (workgroup) { return; }
if (typeof fileData !== "object" || !fileData.href || !fileData.title) { if (typeof fileData !== "object" || !fileData.href || !fileData.title) {
console.error("filedata object expected to add a new template"); console.error("filedata object expected to add a new template");
@ -1031,7 +1027,7 @@ define([
} }
}; };
var listTemplates = exp.listTemplates = function (type) { exp.listTemplates = function () {
if (workgroup) { return; } if (workgroup) { return; }
var templateFiles = getTemplateFiles(); var templateFiles = getTemplateFiles();
var res = []; var res = [];
@ -1049,7 +1045,7 @@ define([
}); });
}; };
var fixFiles = exp.fixFiles = function () { exp.fixFiles = function () {
// Explore the tree and check that everything is correct: // Explore the tree and check that everything is correct:
// * 'root', 'trash', 'unsorted' and 'filesData' exist and are objects // * 'root', 'trash', 'unsorted' and 'filesData' exist and are objects
// * ROOT: Folders are objects, files are href // * ROOT: Folders are objects, files are href
@ -1138,7 +1134,7 @@ define([
var templateFiles = getTemplateFiles(); var templateFiles = getTemplateFiles();
var trashFiles = getTrashFiles(); var trashFiles = getTrashFiles();
var toClean = []; var toClean = [];
fd.forEach(function (el, idx) { fd.forEach(function (el) {
if (!el || typeof(el) !== "object") { if (!el || typeof(el) !== "object") {
debug("An element in filesData was not an object.", el); debug("An element in filesData was not an object.", el);
toClean.push(el); toClean.push(el);

@ -127,9 +127,9 @@ define([
return filesOp.replace(o, n); return filesOp.replace(o, n);
}; };
var changeHandlers = ret.changeHandlers = []; ret.changeHandlers = [];
ret.change = function (f) {}; ret.change = function () {};
return ret; return ret;
}; };
@ -166,7 +166,7 @@ define([
return; return;
} }
proxy.on('change', [Cryptpad.displayNameKey], function (o, n, p) { proxy.on('change', [Cryptpad.displayNameKey], function (o, n) {
if (typeof(n) !== "string") { return; } if (typeof(n) !== "string") { return; }
Cryptpad.changeDisplayName(n); Cryptpad.changeDisplayName(n);
}); });
@ -197,7 +197,6 @@ define([
var exp = {}; var exp = {};
window.addEventListener('storage', function (e) { window.addEventListener('storage', function (e) {
var key = e.key;
if (e.key !== Cryptpad.userHashKey) { return; } if (e.key !== Cryptpad.userHashKey) { return; }
var o = e.oldValue; var o = e.oldValue;
var n = e.newValue; var n = e.newValue;

@ -22,7 +22,7 @@ define([
// 16 bytes for a deterministic channel key // 16 bytes for a deterministic channel key
var channelSeed = dispense(16); var channelSeed = dispense(16);
// 32 bytes for a curve key // 32 bytes for a curve key
var curveSeed = opt.curveSeed = dispense(32); opt.curveSeed = dispense(32);
// 32 more for a signing key // 32 more for a signing key
var edSeed = opt.edSeed = dispense(32); var edSeed = opt.edSeed = dispense(32);
@ -43,9 +43,9 @@ define([
// should never happen // should never happen
if (channelHex.length !== 32) { throw new Error('invalid channel id'); } if (channelHex.length !== 32) { throw new Error('invalid channel id'); }
var channel64 = opt.channel64 = Cryptpad.hexToBase64(channelHex); opt.channel64 = Cryptpad.hexToBase64(channelHex);
var userHash = opt.userHash = '/1/edit/' + [opt.channel64, opt.keys.editKeyStr].join('/'); opt.userHash = '/1/edit/' + [opt.channel64, opt.keys.editKeyStr].join('/');
return opt; return opt;
}; };
@ -62,7 +62,7 @@ define([
var rt = opt.rt = Listmap.create(config); var rt = opt.rt = Listmap.create(config);
rt.proxy rt.proxy
.on('ready', function (info) { .on('ready', function () {
cb(void 0, rt); cb(void 0, rt);
}) })
.on('disconnect', function (info) { .on('disconnect', function (info) {

@ -46,7 +46,7 @@ define([
var merge = function (obj1, obj2, keepOld) { var merge = function (obj1, obj2, keepOld) {
if (typeof (obj1) !== "object" || typeof (obj2) !== "object") { return; } if (typeof (obj1) !== "object" || typeof (obj2) !== "object") { return; }
Object.keys(obj2).forEach(function (k) { Object.keys(obj2).forEach(function (k) {
var v = obj2[k]; //var v = obj2[k];
// If one of them is not an object or if we have a map and a array, don't override, create a new key // If one of them is not an object or if we have a map and a array, don't override, create a new key
if (!obj1[k] || typeof(obj1[k]) !== "object" || typeof(obj2[k]) !== "object" || if (!obj1[k] || typeof(obj1[k]) !== "object" || typeof(obj2[k]) !== "object" ||
(getType(obj1[k]) !== getType(obj2[k]))) { (getType(obj1[k]) !== getType(obj2[k]))) {
@ -80,7 +80,7 @@ define([
path.pop(); path.pop();
} }
var p, next, nextRoot; var next, nextRoot;
path.forEach(function (p, i) { path.forEach(function (p, i) {
if (!root) { return; } if (!root) { return; }
if (typeof(p) === "string") { if (typeof(p) === "string") {
@ -128,7 +128,7 @@ define([
}); });
}; };
var mergeAnonDrive = exp.anonDriveIntoUser = function (proxy, cb) { exp.anonDriveIntoUser = function (proxy, cb) {
// Make sure we have an FS_hash and we don't use it, otherwise just stop the migration and cb // Make sure we have an FS_hash and we don't use it, otherwise just stop the migration and cb
if (!localStorage.FS_hash || !Cryptpad.isLoggedIn()) { if (!localStorage.FS_hash || !Cryptpad.isLoggedIn()) {
if (typeof(cb) === "function") { cb(); } if (typeof(cb) === "function") { cb(); }

@ -132,7 +132,7 @@ define(function () {
}; };
}); });
var extensionOf = Modes.extensionOf = function (mode) { Modes.extensionOf = function (mode) {
var ext = ''; var ext = '';
list.some(function (o) { list.some(function (o) {
if (o.mode !== mode) { return; } if (o.mode !== mode) { return; }

@ -16,14 +16,14 @@
}); });
}; };
var create = Module.create = function (msg, title, icon) { var create = Module.create = function (msg, title) {
return new Notification(title,{ return new Notification(title,{
// icon: icon, // icon: icon,
body: msg, body: msg,
}); });
}; };
var system = Module.system = function (msg, title, icon) { Module.system = function (msg, title, icon) {
// Let's check if the browser supports notifications // Let's check if the browser supports notifications
if (!isSupported()) { console.log("Notifications are not supported"); } if (!isSupported()) { console.log("Notifications are not supported"); }
@ -41,7 +41,7 @@
} }
}; };
var tab = Module.tab = function (frequency, count) { Module.tab = function (frequency, count) {
var key = '_pendingTabNotification'; var key = '_pendingTabNotification';
var favicon = document.getElementById('favicon'); var favicon = document.getElementById('favicon');

@ -1,7 +1,6 @@
define([ define([
'/bower_components/tweetnacl/nacl-fast.min.js', '/bower_components/tweetnacl/nacl-fast.min.js',
], function () { ], function () {
var MAX_LAG_BEFORE_TIMEOUT = 30000;
var Nacl = window.nacl; var Nacl = window.nacl;
var uid = function () { var uid = function () {
@ -130,22 +129,22 @@ types of messages:
return sendMsg(ctx, data, cb); return sendMsg(ctx, data, cb);
}; };
network.on('message', function (msg, sender) { network.on('message', function (msg) {
onMsg(ctx, msg); onMsg(ctx, msg);
}); });
network.on('disconnect', function (reason) { network.on('disconnect', function () {
ctx.connected = false; ctx.connected = false;
}); });
network.on('reconnect', function (uid) { network.on('reconnect', function () {
send('COOKIE', "", function (e, msg) { send('COOKIE', "", function (e) {
if (e) { return void cb(e); } if (e) { return void cb(e); }
ctx.connected = true; ctx.connected = true;
}); });
}); });
send('COOKIE', "", function (e, msg) { send('COOKIE', "", function (e) {
if (e) { return void cb(e); } if (e) { return void cb(e); }
// callback to provide 'send' method to whatever needs it // callback to provide 'send' method to whatever needs it
cb(void 0, { send: send, }); cb(void 0, { send: send, });

@ -71,7 +71,7 @@ define([], function () {
} }
}; };
var orderOfNodes = tree.orderOfNodes = function (a, b, root) { tree.orderOfNodes = function (a, b, root) {
// b might not be supplied // b might not be supplied
if (!b) { return; } if (!b) { return; }
// a and b might be the same element // a and b might be the same element

@ -9,7 +9,7 @@ define([
var TRASH = module.TRASH = "trash"; var TRASH = module.TRASH = "trash";
var TEMPLATE = module.TEMPLATE = "template"; var TEMPLATE = module.TEMPLATE = "template";
var init = module.init = function (files, config) { module.init = function (files, config) {
var exp = {}; var exp = {};
var Cryptpad = config.Cryptpad; var Cryptpad = config.Cryptpad;
var Messages = Cryptpad.Messages; var Messages = Cryptpad.Messages;
@ -19,7 +19,6 @@ define([
var NEW_FILE_NAME = Messages.fm_newFile; var NEW_FILE_NAME = Messages.fm_newFile;
// Logging // Logging
var DEBUG = config.DEBUG || false;
var logging = function () { var logging = function () {
console.log.apply(console, arguments); console.log.apply(console, arguments);
}; };
@ -39,7 +38,7 @@ define([
* UTILS * UTILS
*/ */
var getStructure = exp.getStructure = function () { exp.getStructure = function () {
var a = {}; var a = {};
a[ROOT] = {}; a[ROOT] = {};
a[TRASH] = {}; a[TRASH] = {};
@ -58,7 +57,7 @@ define([
return typeof(element) === "string"; return typeof(element) === "string";
}; };
var isReadOnlyFile = exp.isReadOnlyFile = function (element) { exp.isReadOnlyFile = function (element) {
if (!isFile(element)) { return false; } if (!isFile(element)) { return false; }
var parsed = Cryptpad.parsePadUrl(element); var parsed = Cryptpad.parsePadUrl(element);
if (!parsed) { return false; } if (!parsed) { return false; }
@ -71,15 +70,15 @@ define([
var isFolder = exp.isFolder = function (element) { var isFolder = exp.isFolder = function (element) {
return typeof(element) === "object"; return typeof(element) === "object";
}; };
var isFolderEmpty = exp.isFolderEmpty = function (element) { exp.isFolderEmpty = function (element) {
if (typeof(element) !== "object") { return false; } if (typeof(element) !== "object") { return false; }
return Object.keys(element).length === 0; return Object.keys(element).length === 0;
}; };
var hasSubfolder = exp.hasSubfolder = function (element, trashRoot) { exp.hasSubfolder = function (element, trashRoot) {
if (typeof(element) !== "object") { return false; } if (typeof(element) !== "object") { return false; }
var subfolder = 0; var subfolder = 0;
var addSubfolder = function (el, idx) { var addSubfolder = function (el) {
subfolder += isFolder(el.element) ? 1 : 0; subfolder += isFolder(el.element) ? 1 : 0;
}; };
for (var f in element) { for (var f in element) {
@ -94,10 +93,10 @@ define([
return subfolder; return subfolder;
}; };
var hasFile = exp.hasFile = function (element, trashRoot) { exp.hasFile = function (element, trashRoot) {
if (typeof(element) !== "object") { return false; } if (typeof(element) !== "object") { return false; }
var file = 0; var file = 0;
var addFile = function (el, idx) { var addFile = function (el) {
file += isFile(el.element) ? 1 : 0; file += isFile(el.element) ? 1 : 0;
}; };
for (var f in element) { for (var f in element) {
@ -232,7 +231,7 @@ define([
_getFiles[TRASH] = function () { _getFiles[TRASH] = function () {
var root = files[TRASH]; var root = files[TRASH];
var ret = []; var ret = [];
var addFiles = function (el, idx) { var addFiles = function (el) {
if (isFile(el.element)) { if (isFile(el.element)) {
if(ret.indexOf(el.element) === -1) { ret.push(el.element); } if(ret.indexOf(el.element) === -1) { ret.push(el.element); }
} else { } else {
@ -297,7 +296,7 @@ define([
return paths; return paths;
}; };
var findFileInRoot = exp.findFileInRoot = function (href) { exp.findFileInRoot = function (href) {
return _findFileInRoot([ROOT], href); return _findFileInRoot([ROOT], href);
}; };
var _findFileInHrefArray = function (rootName, href) { var _findFileInHrefArray = function (rootName, href) {
@ -352,7 +351,7 @@ define([
var trashpaths = _findFileInTrash([TRASH], href); var trashpaths = _findFileInTrash([TRASH], href);
return rootpaths.concat(templatepaths, trashpaths); return rootpaths.concat(templatepaths, trashpaths);
}; };
var search = exp.search = function (value) { exp.search = function (value) {
if (typeof(value) !== "string") { return []; } if (typeof(value) !== "string") { return []; }
var res = []; var res = [];
// Search in ROOT // Search in ROOT
@ -403,7 +402,7 @@ define([
var ret = []; var ret = [];
res.forEach(function (l) { res.forEach(function (l) {
var paths = findFile(l); //var paths = findFile(l);
ret.push({ ret.push({
paths: findFile(l), paths: findFile(l),
data: exp.getFileData(l) data: exp.getFileData(l)
@ -435,7 +434,7 @@ define([
cb(); cb();
}; };
if (!Cryptpad.isLoggedIn() || !AppConfig.enablePinning) { return void todo(); } if (!Cryptpad.isLoggedIn() || !AppConfig.enablePinning) { return void todo(); }
Cryptpad.pinPads([Cryptpad.hrefToHexChannelId(data.href)], function (e, hash) { Cryptpad.pinPads([Cryptpad.hrefToHexChannelId(data.href)], function (e) {
if (e) { return void cb(e); } if (e) { return void cb(e); }
todo(); todo();
}); });
@ -531,7 +530,7 @@ define([
}); });
exp.delete(toRemove, cb); exp.delete(toRemove, cb);
}; };
var restore = exp.restore = function (path, cb) { exp.restore = function (path, cb) {
if (!isInTrashRoot(path)) { return; } if (!isInTrashRoot(path)) { return; }
var parentPath = path.slice(); var parentPath = path.slice();
parentPath.pop(); parentPath.pop();
@ -566,7 +565,7 @@ define([
} }
} }
}; };
var addFile = exp.addFile = function (filePath, name, type, cb) { exp.addFile = function (filePath, name, type, cb) {
var parentEl = findElement(files, filePath); var parentEl = findElement(files, filePath);
var fileName = getAvailableName(parentEl, name || NEW_FILE_NAME); var fileName = getAvailableName(parentEl, name || NEW_FILE_NAME);
var href = '/' + type + '/#' + Cryptpad.createRandomHash(); var href = '/' + type + '/#' + Cryptpad.createRandomHash();
@ -586,7 +585,7 @@ define([
}); });
}); });
}; };
var addFolder = exp.addFolder = function (folderPath, name, cb) { exp.addFolder = function (folderPath, name, cb) {
var parentEl = find(folderPath); var parentEl = find(folderPath);
var folderName = getAvailableName(parentEl, name || NEW_FOLDER_NAME); var folderName = getAvailableName(parentEl, name || NEW_FOLDER_NAME);
parentEl[folderName] = {}; parentEl[folderName] = {};
@ -598,7 +597,7 @@ define([
}; };
// FORGET (move with href not path) // FORGET (move with href not path)
var forget = exp.forget = function (href) { exp.forget = function (href) {
var paths = findFile(href); var paths = findFile(href);
move(paths, [TRASH]); move(paths, [TRASH]);
}; };
@ -700,18 +699,18 @@ define([
// FILES_DATA (replaceHref) // FILES_DATA (replaceHref)
if (!nocheck) { checkDeletedFiles(); } if (!nocheck) { checkDeletedFiles(); }
}; };
var deletePath = exp.delete = function (paths, cb, nocheck) { exp.delete = function (paths, cb, nocheck) {
deleteMultiplePermanently(paths, nocheck); deleteMultiplePermanently(paths, nocheck);
if (typeof cb === "function") { cb(); } if (typeof cb === "function") { cb(); }
}; };
var emptyTrash = exp.emptyTrash = function (cb) { exp.emptyTrash = function (cb) {
files[TRASH] = {}; files[TRASH] = {};
checkDeletedFiles(); checkDeletedFiles();
if(cb) { cb(); } if(cb) { cb(); }
}; };
// RENAME // RENAME
var rename = exp.rename = function (path, newName, cb) { exp.rename = function (path, newName, cb) {
if (path.length <= 1) { if (path.length <= 1) {
logError('Renaming `root` is forbidden'); logError('Renaming `root` is forbidden');
return; return;
@ -753,7 +752,7 @@ define([
} }
}; };
// Replace a href by a stronger one everywhere in the drive (except FILES_DATA) // Replace a href by a stronger one everywhere in the drive (except FILES_DATA)
var replaceHref = exp.replace = function (o, n) { exp.replace = function (o, n) {
if (!isFile(o) || !isFile(n)) { return; } if (!isFile(o) || !isFile(n)) { return; }
var paths = findFile(o); var paths = findFile(o);
@ -782,7 +781,7 @@ define([
* INTEGRITY CHECK * INTEGRITY CHECK
*/ */
var fixFiles = exp.fixFiles = function () { exp.fixFiles = function () {
// Explore the tree and check that everything is correct: // Explore the tree and check that everything is correct:
// * 'root', 'trash', 'unsorted' and 'filesData' exist and are objects // * 'root', 'trash', 'unsorted' and 'filesData' exist and are objects
// * ROOT: Folders are objects, files are href // * ROOT: Folders are objects, files are href
@ -841,9 +840,9 @@ define([
return; return;
} }
var rootFiles = getFiles([ROOT, TEMPLATE]).slice(); var rootFiles = getFiles([ROOT, TEMPLATE]).slice();
var toClean = []; //var toClean = [];
var root = find([ROOT]); var root = find([ROOT]);
us.forEach(function (el, idx) { us.forEach(function (el) {
if (!isFile(el) || rootFiles.indexOf(el) !== -1) { if (!isFile(el) || rootFiles.indexOf(el) !== -1) {
return; return;
//toClean.push(idx); //toClean.push(idx);
@ -878,7 +877,7 @@ define([
var rootFiles = getFiles([ROOT, TRASH, 'hrefArray']); var rootFiles = getFiles([ROOT, TRASH, 'hrefArray']);
var root = find([ROOT]); var root = find([ROOT]);
var toClean = []; var toClean = [];
fd.forEach(function (el, idx) { fd.forEach(function (el) {
if (!el || typeof(el) !== "object") { if (!el || typeof(el) !== "object") {
debug("An element in filesData was not an object.", el); debug("An element in filesData was not an object.", el);
toClean.push(el); toClean.push(el);

@ -20,18 +20,18 @@
visibilityChange: visibilityChange, visibilityChange: visibilityChange,
}; };
var isSupported = Visible.isSupported = function () { Visible.isSupported = function () {
return !(typeof(document.addEventListener) === "undefined" || return !(typeof(document.addEventListener) === "undefined" ||
typeof document[hidden] === "undefined"); typeof document[hidden] === "undefined");
}; };
var onChange = Visible.onChange = function (f) { Visible.onChange = function (f) {
document.addEventListener(visibilityChange, function (ev) { document.addEventListener(visibilityChange, function (ev) {
f(!document[hidden], ev); f(!document[hidden], ev);
}, false); }, false);
}; };
var currently = Visible.currently = function () { Visible.currently = function () {
return !document[hidden]; return !document[hidden];
}; };

@ -14,7 +14,7 @@ define([
var module = window.MODULE = {}; var module = window.MODULE = {};
var Messages = Cryptpad.Messages; var Messages = Cryptpad.Messages;
var saveAs = window.saveAs; //var saveAs = window.saveAs;
// Use `$(function () {});` to make sure the html is loaded before doing anything else // Use `$(function () {});` to make sure the html is loaded before doing anything else
$(function () { $(function () {
@ -22,7 +22,7 @@ define([
var ifrw = $('#pad-iframe')[0].contentWindow; var ifrw = $('#pad-iframe')[0].contentWindow;
Cryptpad.addLoadingScreen(); Cryptpad.addLoadingScreen();
var onConnectError = function (info) { var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError); Cryptpad.errorLoadingScreen(Messages.websocketError);
}; };
@ -134,10 +134,9 @@ define([
return localStorage.searchCursor || 0; return localStorage.searchCursor || 0;
}; };
/* var now = function () {
var now = function () {
return new Date().getTime(); return new Date().getTime();
}; }; */
var setEditable = function (state) { var setEditable = function (state) {
APP.editable = state; APP.editable = state;
@ -162,12 +161,12 @@ define([
var $slideIcon = $('<span>', {"class": "fa fa-file-powerpoint-o file icon"}); var $slideIcon = $('<span>', {"class": "fa fa-file-powerpoint-o file icon"});
var $pollIcon = $('<span>', {"class": "fa fa-calendar file icon"}); var $pollIcon = $('<span>', {"class": "fa fa-calendar file icon"});
var $whiteboardIcon = $('<span>', {"class": "fa fa-paint-brush"}); var $whiteboardIcon = $('<span>', {"class": "fa fa-paint-brush"});
var $upIcon = $('<span>', {"class": "fa fa-arrow-circle-up"}); //var $upIcon = $('<span>', {"class": "fa fa-arrow-circle-up"});
var $unsortedIcon = $('<span>', {"class": "fa fa-files-o"}); var $unsortedIcon = $('<span>', {"class": "fa fa-files-o"});
var $templateIcon = $('<span>', {"class": "fa fa-cubes"}); var $templateIcon = $('<span>', {"class": "fa fa-cubes"});
var $trashIcon = $('<span>', {"class": "fa fa-trash"}); var $trashIcon = $('<span>', {"class": "fa fa-trash"});
var $trashEmptyIcon = $('<span>', {"class": "fa fa-trash-o"}); var $trashEmptyIcon = $('<span>', {"class": "fa fa-trash-o"});
var $collapseIcon = $('<span>', {"class": "fa fa-minus-square-o expcol"}); //var $collapseIcon = $('<span>', {"class": "fa fa-minus-square-o expcol"});
var $expandIcon = $('<span>', {"class": "fa fa-plus-square-o expcol"}); var $expandIcon = $('<span>', {"class": "fa fa-plus-square-o expcol"});
var $listIcon = $('<span>', {"class": "fa fa-list"}); var $listIcon = $('<span>', {"class": "fa fa-list"});
var $gridIcon = $('<span>', {"class": "fa fa-th"}); var $gridIcon = $('<span>', {"class": "fa fa-th"});
@ -228,8 +227,6 @@ define([
if (AppConfig.enableTemplates) { displayedCategories.push(TEMPLATE); } if (AppConfig.enableTemplates) { displayedCategories.push(TEMPLATE); }
if (isWorkgroup()) { displayedCategories = [ROOT, TRASH, SEARCH]; } if (isWorkgroup()) { displayedCategories = [ROOT, TRASH, SEARCH]; }
var selectedElement;
if (!APP.readOnly) { if (!APP.readOnly) {
setEditable(true); setEditable(true);
} }
@ -557,7 +554,7 @@ define([
var hide = []; var hide = [];
var hasFolder = false; var hasFolder = false;
paths.forEach(function (p, i) { paths.forEach(function (p) {
var path = p.path; var path = p.path;
var $element = p.element; var $element = p.element;
if (path.length === 1) { if (path.length === 1) {
@ -675,7 +672,7 @@ define([
var paths = getSelectedPaths($element); var paths = getSelectedPaths($element);
var $menu = $element.data('context'); var $menu = $element.data('context');
if (!$menu) { return; } if (!$menu) { return; }
var actions = []; //var actions = [];
var $actions = $menu.find('a'); var $actions = $menu.find('a');
var toHide = filterContextMenu($menu, paths); var toHide = filterContextMenu($menu, paths);
$actions = $actions.filter(function (i, el) { $actions = $actions.filter(function (i, el) {
@ -1173,6 +1170,7 @@ define([
}; };
// Display the full path in the title when displaying a directory from the trash // Display the full path in the title when displaying a directory from the trash
/*
var getTrashTitle = function (path) { var getTrashTitle = function (path) {
if (!path[0] || path[0] !== TRASH) { return; } if (!path[0] || path[0] !== TRASH) { return; }
var title = TRASH_NAME; var title = TRASH_NAME;
@ -1187,7 +1185,7 @@ define([
} }
} }
return title; return title;
}; }; */
var getPrettyName = function (name) { var getPrettyName = function (name) {
var pName; var pName;
@ -1218,7 +1216,7 @@ define([
if (idx < path.length - 1) { if (idx < path.length - 1) {
if (!noStyle) { if (!noStyle) {
$span.addClass('clickable'); $span.addClass('clickable');
$span.click(function (e) { $span.click(function () {
var sliceEnd = idx + 1; var sliceEnd = idx + 1;
if (isTrash && idx === 1) { sliceEnd = 4; } // Make sure we don't show the index or 'element' and 'path' if (isTrash && idx === 1) { sliceEnd = 4; } // Make sure we don't show the index or 'element' and 'path'
module.displayDirectory(path.slice(0, sliceEnd)); module.displayDirectory(path.slice(0, sliceEnd));
@ -1359,13 +1357,13 @@ define([
$block.find('a.newFolder').click(function () { $block.find('a.newFolder').click(function () {
filesOp.addFolder(currentPath, null, onCreated); filesOp.addFolder(currentPath, null, onCreated);
}); });
$block.find('a.newdoc').click(function (e) { $block.find('a.newdoc').click(function () {
var type = $(this).attr('data-type') || 'pad'; var type = $(this).attr('data-type') || 'pad';
var name = Cryptpad.getDefaultName({type: type}); var name = Cryptpad.getDefaultName({type: type});
filesOp.addFile(currentPath, name, type, onCreated); filesOp.addFile(currentPath, name, type, onCreated);
}); });
} else { } else {
$block.find('a.newdoc').click(function (e) { $block.find('a.newdoc').click(function () {
var type = $(this).attr('data-type') || 'pad'; var type = $(this).attr('data-type') || 'pad';
sessionStorage[Cryptpad.newPadPathKey] = filesOp.isPathIn(currentPath, [TRASH]) ? '' : currentPath; sessionStorage[Cryptpad.newPadPathKey] = filesOp.isPathIn(currentPath, [TRASH]) ? '' : currentPath;
window.open('/' + type + '/'); window.open('/' + type + '/');
@ -1390,7 +1388,7 @@ define([
return Cryptpad.getLSAttribute(SORT_FOLDER_DESC) === "true"; return Cryptpad.getLSAttribute(SORT_FOLDER_DESC) === "true";
}; };
var onSortByClick = function (e) { var onSortByClick = function () {
var $span = $(this); var $span = $(this);
var value; var value;
if ($span.hasClass('foldername')) { if ($span.hasClass('foldername')) {
@ -1530,7 +1528,7 @@ define([
return keys; return keys;
}; };
var sortTrashElements = function (folder, oldkeys, prop, asc) { var sortTrashElements = function (folder, oldkeys, prop, asc) {
var root = files[TRASH]; //var root = files[TRASH];
var test = folder ? filesOp.isFolder : filesOp.isFile; var test = folder ? filesOp.isFolder : filesOp.isFile;
var keys = oldkeys.filter(function (e) { var keys = oldkeys.filter(function (e) {
return test(e.element); return test(e.element);
@ -1569,14 +1567,14 @@ define([
}; };
// Drive content toolbar // Drive content toolbar
var createToolbar = function (path) { var createToolbar = function () {
var $toolbar = $driveToolbar; var $toolbar = $driveToolbar;
$toolbar.html(''); $toolbar.html('');
var $leftside = $('<div>', {'class': 'leftside'}).appendTo($toolbar); var $leftside = $('<div>', {'class': 'leftside'}).appendTo($toolbar);
if (!APP.mobile()) { if (!APP.mobile()) {
$leftside.width($tree.width()); $leftside.width($tree.width());
} }
var $rightside = $('<div>', {'class': 'rightside'}).appendTo($toolbar); $('<div>', {'class': 'rightside'}).appendTo($toolbar);
return $toolbar; return $toolbar;
}; };
@ -1702,7 +1700,7 @@ define([
var parsed = Cryptpad.parsePadUrl(href); var parsed = Cryptpad.parsePadUrl(href);
var $table = $('<table>'); var $table = $('<table>');
var $icon = $('<td>', {'rowspan': '3', 'class': 'icon'}).append(getFileIcon(href)); var $icon = $('<td>', {'rowspan': '3', 'class': 'icon'}).append(getFileIcon(href));
var $title = $('<td>', {'class': 'col1 title'}).text(r.data.title).click(function (e) { var $title = $('<td>', {'class': 'col1 title'}).text(r.data.title).click(function () {
openFile(r.data.href); openFile(r.data.href);
}); });
var $typeName = $('<td>', {'class': 'label2'}).text(Messages.fm_type); var $typeName = $('<td>', {'class': 'label2'}).text(Messages.fm_type);
@ -1726,9 +1724,11 @@ define([
}); });
} }
var $openDir = $('<td>', {'class': 'openDir'}).append($a); var $openDir = $('<td>', {'class': 'openDir'}).append($a);
var $row1 = $('<tr>').append($icon).append($title).append($typeName).append($type).appendTo($table);
var $row2 = $('<tr>').append($path).append($atimeName).append($atime).appendTo($table); // rows 1-3
var $row3 = $('<tr>').append($openDir).append($ctimeName).append($ctime).appendTo($table); $('<tr>').append($icon).append($title).append($typeName).append($type).appendTo($table);
$('<tr>').append($path).append($atimeName).append($atime).appendTo($table);
$('<tr>').append($openDir).append($ctimeName).append($ctime).appendTo($table);
$('<li>', {'class':'searchResult'}).append($table).appendTo($list); $('<li>', {'class':'searchResult'}).append($table).appendTo($list);
}); });
}); });
@ -1793,11 +1793,11 @@ define([
if (mode) { if (mode) {
$dirContent.addClass(getViewModeClass()); $dirContent.addClass(getViewModeClass());
} }
var $modeButton = createViewModeButton().appendTo($toolbar.find('.rightside')); createViewModeButton().appendTo($toolbar.find('.rightside'));
} }
var $list = $('<ul>').appendTo($dirContent); var $list = $('<ul>').appendTo($dirContent);
var $title = createTitle(path).appendTo($toolbar.find('.rightside')); createTitle(path).appendTo($toolbar.find('.rightside'));
updatePathSize(); updatePathSize();
if (APP.mobile()) { if (APP.mobile()) {
@ -1883,7 +1883,7 @@ define([
appStatus.ready(true); appStatus.ready(true);
}; };
var refreshFilesData = function () { /* var refreshFilesData = function () {
$content.find('.element-row').each(function (i, e) { $content.find('.element-row').each(function (i, e) {
var $el = $(e); var $el = $(e);
if ($el.data('path')) { if ($el.data('path')) {
@ -1898,7 +1898,8 @@ define([
$el.find('.ctime').attr('title', getDate(data.ctime)).text(getDate(data.ctime)); $el.find('.ctime').attr('title', getDate(data.ctime)).text(getDate(data.ctime));
} }
}); });
}; }; */
var createTreeElement = function (name, $icon, path, draggable, droppable, collapsable, active) { var createTreeElement = function (name, $icon, path, draggable, droppable, collapsable, active) {
var $name = $('<span>', { 'class': 'folder-element element' }).text(name); var $name = $('<span>', { 'class': 'folder-element element' }).text(name);
@ -1961,7 +1962,7 @@ define([
var $rootElement = createTreeElement(ROOT_NAME, $rootIcon.clone(), [ROOT], false, true, false, isRootOpened); var $rootElement = createTreeElement(ROOT_NAME, $rootIcon.clone(), [ROOT], false, true, false, isRootOpened);
$rootElement.addClass('root'); $rootElement.addClass('root');
$rootElement.find('>.element-row').contextmenu(openDirectoryContextMenu); $rootElement.find('>.element-row').contextmenu(openDirectoryContextMenu);
var $root = $('<ul>').append($rootElement).appendTo($container); $('<ul>').append($rootElement).appendTo($container);
$container = $rootElement; $container = $rootElement;
} else if (filesOp.isFolderEmpty(root)) { return; } } else if (filesOp.isFolderEmpty(root)) { return; }
@ -2048,7 +2049,7 @@ define([
$container.append($div); $container.append($div);
}; };
var resetTree = module.resetTree = function () { module.resetTree = function () {
$tree.html(''); $tree.html('');
if (displayedCategories.indexOf(SEARCH) !== -1) { createSearch($tree); } if (displayedCategories.indexOf(SEARCH) !== -1) { createSearch($tree); }
if (displayedCategories.indexOf(ROOT) !== -1) { createTree($tree, [ROOT]); } if (displayedCategories.indexOf(ROOT) !== -1) { createTree($tree, [ROOT]); }
@ -2057,7 +2058,7 @@ define([
if (displayedCategories.indexOf(TRASH) !== -1) { createTrash($tree, [TRASH]); } if (displayedCategories.indexOf(TRASH) !== -1) { createTrash($tree, [TRASH]); }
}; };
var hideMenu = module.hideMenu = function () { module.hideMenu = function () {
$contextMenu.hide(); $contextMenu.hide();
$trashTreeContextMenu.hide(); $trashTreeContextMenu.hide();
$trashContextMenu.hide(); $trashContextMenu.hide();
@ -2361,7 +2362,7 @@ define([
removeInput(); removeInput();
module.hideMenu(e); module.hideMenu(e);
}); });
$appContainer.on('mouseup drop', function (e) { $appContainer.on('mouseup drop', function () {
$iframe.find('.droppable').removeClass('droppable'); $iframe.find('.droppable').removeClass('droppable');
}); });
$appContainer.on('keydown', function (e) { $appContainer.on('keydown', function (e) {
@ -2407,7 +2408,7 @@ define([
onRefresh.to = window.setTimeout(refresh, 500); onRefresh.to = window.setTimeout(refresh, 500);
} }
}; };
proxy.on('change', [], function (o, n, p) { proxy.on('change', [], function () {
if (history.isHistoryMode) { return; } if (history.isHistoryMode) { return; }
var path = arguments[2]; var path = arguments[2];
if (path[0] !== 'drive') { return false; } if (path[0] !== 'drive') { return false; }
@ -2422,7 +2423,7 @@ define([
} }
module.resetTree(); module.resetTree();
return false; return false;
}).on('remove', [], function (o, p) { }).on('remove', [], function () {
if (history.isHistoryMode) { return; } if (history.isHistoryMode) { return; }
var path = arguments[1]; var path = arguments[1];
if (path[0] !== 'drive') { return false; } if (path[0] !== 'drive') { return false; }
@ -2437,7 +2438,7 @@ define([
return false; return false;
}); });
$iframe.find('#tree').mousedown(function (e) { $iframe.find('#tree').mousedown(function () {
if (APP.mobile()) { return; } if (APP.mobile()) { return; }
if (APP.resizeTree) { return; } if (APP.resizeTree) { return; }
APP.resizeTree = window.setInterval(function () { APP.resizeTree = window.setInterval(function () {
@ -2445,7 +2446,7 @@ define([
updatePathSize(); updatePathSize();
}, 100); }, 100);
}); });
$appContainer.mouseup(function (e) { $appContainer.mouseup(function () {
window.clearInterval(APP.resizeTree); window.clearInterval(APP.resizeTree);
APP.resizeTree = undefined; APP.resizeTree = undefined;
}); });
@ -2506,7 +2507,7 @@ define([
myUserNameTemp = myUserNameTemp.substr(0, 32); myUserNameTemp = myUserNameTemp.substr(0, 32);
} }
var myUserName = myUserNameTemp; var myUserName = myUserNameTemp;
Cryptpad.setAttribute('username', myUserName, function (err, data) { Cryptpad.setAttribute('username', myUserName, function (err) {
if (err) { if (err) {
logError("Couldn't set username", err); logError("Couldn't set username", err);
return; return;
@ -2587,7 +2588,7 @@ define([
common: Cryptpad, common: Cryptpad,
hideShare: true hideShare: true
}; };
var toolbar = APP.toolbar = info.realtime.toolbar = Toolbar.create(APP.$bar, info.myID, info.realtime, info.getLag, userList, config); APP.toolbar = info.realtime.toolbar = Toolbar.create(APP.$bar, info.myID, info.realtime, info.getLag, userList, config);
var $bar = APP.$bar; var $bar = APP.$bar;
var $rightside = $bar.find('.' + Toolbar.constants.rightside); var $rightside = $bar.find('.' + Toolbar.constants.rightside);
@ -2621,10 +2622,10 @@ define([
var $usage = $('<span>', {'class': 'usage'}).css('width', width+'px'); var $usage = $('<span>', {'class': 'usage'}).css('width', width+'px');
if (quota >= 0.8) { if (quota >= 0.8) {
var $upgrade = $('<button>', { $('<button>', {
'class': 'upgrade buttonSuccess', 'class': 'upgrade buttonSuccess',
title: Messages.upgradeTitle title: Messages.upgradeTitle
}).text(Messages.upgrade).click(function (e) { }).text(Messages.upgrade).click(function () {
// TODO // TODO
}).appendTo($leftside); }).appendTo($leftside);
} }
@ -2659,7 +2660,7 @@ define([
// Close button clicked // Close button clicked
setHistory(false, true); setHistory(false, true);
}; };
histConfig.onRevert = function (val) { histConfig.onRevert = function () {
// Revert button clicked // Revert button clicked
setHistory(false, false); setHistory(false, false);
proxy.drive = history.currentObj.drive; proxy.drive = history.currentObj.drive;
@ -2701,7 +2702,7 @@ define([
Cryptpad.removeLoadingScreen(); Cryptpad.removeLoadingScreen();
}); });
}; };
var onDisconnect = function (info) { var onDisconnect = function () {
setEditable(false); setEditable(false);
if (APP.refresh) { APP.refresh(); } if (APP.refresh) { APP.refresh(); }
APP.toolbar.failed(); APP.toolbar.failed();

@ -169,6 +169,7 @@ define([
var $input = Input({ var $input = Input({
placeholder: 'card description', placeholder: 'card description',
id: id,
}) })
.addClass('card-title'); .addClass('card-title');
@ -206,7 +207,7 @@ define([
/* /*
*/ */
Card.move = function (uid, A, B) { Card.move = function (/*uid, A, B*/) {
}; };
@ -228,11 +229,10 @@ define([
} }
var card = proxy.cards[cid]; var card = proxy.cards[cid];
card = card; // TODO actually draw
}; };
var Draw = Board.Draw = function ($lists) { Board.Draw = function ($lists) {
proxy.listOrder.forEach(function (luid) { proxy.listOrder.forEach(function (luid) {
List.draw($lists, luid); List.draw($lists, luid);
}); });

@ -7,12 +7,12 @@ define([
'/bower_components/chainpad-listmap/chainpad-listmap.js', '/bower_components/chainpad-listmap/chainpad-listmap.js',
'/bower_components/chainpad-crypto/crypto.js', '/bower_components/chainpad-crypto/crypto.js',
'/common/cryptpad-common.js', '/common/cryptpad-common.js',
'/common/visible.js', //'/common/visible.js',
'/common/notify.js', //'/common/notify.js',
'/bower_components/file-saver/FileSaver.min.js' '/bower_components/file-saver/FileSaver.min.js'
], function ($, Config, Messages, Board, TextPatcher, Listmap, Crypto, Cryptpad, Visible, Notify) { ], function ($, Config, Messages, Board, TextPatcher, Listmap, Crypto, Cryptpad /*, Visible, Notify*/) {
var saveAs = window.saveAs; // var saveAs = window.saveAs;
Cryptpad.styleAlerts(); Cryptpad.styleAlerts();
console.log("Initializing your realtime session..."); console.log("Initializing your realtime session...");
@ -23,28 +23,28 @@ define([
Board: Board, Board: Board,
}; };
/*
var unnotify = function () { var unnotify = function () {
if (!(module.tabNotification && if (!(module.tabNotification &&
typeof(module.tabNotification.cancel) === 'function')) { return; } typeof(module.tabNotification.cancel) === 'function')) { return; }
module.tabNotification.cancel(); module.tabNotification.cancel();
}; };
var notify = function () { var notify = function () {
if (!(Visible.isSupported() && !Visible.currently())) { return; } if (!(Visible.isSupported() && !Visible.currently())) { return; }
unnotify(); unnotify();
module.tabNotification = Notify.tab(1000, 10); module.tabNotification = Notify.tab(1000, 10);
}; };
*/
var setEditable = function (bool) { var setEditable = function (bool) {
bool = bool;
}; };
setEditable(false); setEditable(false);
var $lists = $('#lists'); var $lists = $('#lists');
var $addList = $('#create-list').click(function () { $('#create-list').click(function () {
Board.List.draw($lists); Board.List.draw($lists);
}); });
@ -52,7 +52,7 @@ define([
Cryptpad.log("You are the first user to visit this board"); Cryptpad.log("You are the first user to visit this board");
}; };
var whenReady = function (opt) { var whenReady = function () {
var rt = module.rt; var rt = module.rt;
var proxy = rt.proxy; var proxy = rt.proxy;
@ -63,7 +63,6 @@ define([
Board.Draw($lists); Board.Draw($lists);
if (first) { firstUser(); } if (first) { firstUser(); }
}; };
var config = { var config = {
@ -78,10 +77,10 @@ define([
var proxy = rt.proxy; var proxy = rt.proxy;
proxy proxy
.on('create', function (info) { .on('create', function (info) {
var realtime = module.realtime = info.realtime; module.realtime = info.realtime;
window.location.hash = info.channel + secret.key; window.location.hash = info.channel + secret.key;
}) })
.on('ready', function (info) { .on('ready', function () {
Cryptpad.log("Ready!"); Cryptpad.log("Ready!");
whenReady({ whenReady({

@ -128,7 +128,7 @@ define([
setEditable(false); setEditable(false);
var onInit = config.onInit = function (info) { config.onInit = function (info) {
var realtime = module.realtime = info.realtime; var realtime = module.realtime = info.realtime;
window.location.hash = info.channel + secret.key; window.location.hash = info.channel + secret.key;
@ -140,7 +140,7 @@ define([
}; };
var readValues = function () { var readValues = function () {
UI.each(function (ui, i, list) { UI.each(function (ui) {
Map[ui.id] = ui.value(); Map[ui.id] = ui.value();
}); });
}; };
@ -165,7 +165,7 @@ define([
if (UI.ids.indexOf(key) === -1) { Map[key] = parsed[key]; } if (UI.ids.indexOf(key) === -1) { Map[key] = parsed[key]; }
}); });
UI.each(function (ui, i, list) { UI.each(function (ui) {
var newval = parsed[ui.id]; var newval = parsed[ui.id];
var oldval = ui.value(); var oldval = ui.value();
@ -178,9 +178,7 @@ define([
if (ui.preserveCursor) { if (ui.preserveCursor) {
op = TextPatcher.diff(oldval, newval); op = TextPatcher.diff(oldval, newval);
selects = ['selectionStart', 'selectionEnd'].map(function (attr) { selects = ['selectionStart', 'selectionEnd'].map(function (attr) {
var before = element[attr]; return TextPatcher.transformCursor(element[attr], op);
var after = TextPatcher.transformCursor(element[attr], op);
return after;
}); });
} }
@ -195,13 +193,13 @@ define([
}); });
}; };
var onRemote = config.onRemote = function (info) { config.onRemote = function () {
if (initializing) { return; } if (initializing) { return; }
/* integrate remote changes */ /* integrate remote changes */
updateValues(); updateValues();
}; };
var onReady = config.onReady = function (info) { config.onReady = function () {
updateValues(); updateValues();
console.log("READY"); console.log("READY");
@ -209,13 +207,13 @@ define([
initializing = false; initializing = false;
}; };
var onAbort = config.onAbort = function (info) { config.onAbort = function () {
window.alert("Network Connection Lost"); window.alert("Network Connection Lost");
}; };
var rt = Realtime.start(config); Realtime.start(config);
UI.each(function (ui, i, list) { UI.each(function (ui) {
var type = ui.type; var type = ui.type;
var events = eventsByType[type]; var events = eventsByType[type];
ui.$.on(events, onLocal); ui.$.on(events, onLocal);

@ -1,7 +1,7 @@
define([], function () { define([], function () {
var ula = {}; var ula = {};
var uid = ula.uid = (function () { ula.uid = (function () {
var i = 0; var i = 0;
var prefix = 'rt_'; var prefix = 'rt_';
return function () { return prefix + i++; }; return function () { return prefix + i++; };

@ -1,77 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<script data-bootload="main.js" data-main="/common/boot.js" src="/bower_components/requirejs/require.js"></script>
<style>
html, body{
padding: 0px;
margin: 0px;
overflow: hidden;
box-sizing: border-box;
}
textarea{
position: absolute;
top: 5vh;
left: 0px;
border: 0px;
padding-top: 15px;
width: 100%;
height: 95vh;
max-width: 100%;
max-height: 100vh;
font-size: 30px;
background-color: #073642;
color: #839496;
overflow-x: hidden;
/* disallow textarea resizes */
resize: none;
}
textarea[disabled] {
background-color: #275662;
color: #637476;
}
#panel {
position: fixed;
top: 0px;
right: 0px;
width: 100%;
height: 5vh;
z-index: 95;
background-color: #777;
/* min-height: 75px; */
}
#run {
display: block;
float: right;
height: 100%;
width: 10vw;
z-index: 100;
line-height: 5vw;
font-size: 1.5em;
background-color: #222;
color: #CCC;
text-align: center;
border-radius: 5%;
border: 0px;
}
</style>
</head>
<body>
<textarea></textarea>
<div id="panel">
<!-- TODO update this element when new users join -->
<span id="users"></span>
<!-- what else should go in the panel? -->
<a href="#" id="run">RUN</a>
</div>
</body>
</html>

@ -1,161 +0,0 @@
define([
'jquery',
'/api/config',
'/bower_components/chainpad-netflux/chainpad-netflux.js',
'/bower_components/chainpad-crypto/crypto.js',
'/bower_components/textpatcher/TextPatcher.amd.js',
'/common/cryptpad-common.js'
], function ($, Config, Realtime, Crypto, TextPatcher, Cryptpad) {
var secret = Cryptpad.getSecrets();
var $textarea = $('textarea'),
$run = $('#run');
var module = {};
var config = {
initialState: '',
websocketURL: Config.websocketURL,
channel: secret.channel,
crypto: Crypto.createEncryptor(secret.key),
};
var initializing = true;
var setEditable = function (bool) { $textarea.attr('disabled', !bool); };
var canonicalize = function (text) { return text.replace(/\r\n/g, '\n'); };
setEditable(false);
var onInit = config.onInit = function (info) {
window.location.hash = info.channel + secret.key;
$(window).on('hashchange', function() { window.location.reload(); });
};
var onRemote = config.onRemote = function (info) {
if (initializing) { return; }
var userDoc = info.realtime.getUserDoc();
var current = canonicalize($textarea.val());
var op = TextPatcher.diff(current, userDoc);
var elem = $textarea[0];
var selects = ['selectionStart', 'selectionEnd'].map(function (attr) {
return TextPatcher.transformCursor(elem[attr], op);
});
$textarea.val(userDoc);
elem.selectionStart = selects[0];
elem.selectionEnd = selects[1];
// TODO do something on external messages
// http://webdesign.tutsplus.com/tutorials/how-to-display-update-notifications-in-the-browser-tab--cms-23458
};
var onReady = config.onReady = function (info) {
module.patchText = TextPatcher.create({
realtime: info.realtime
// logging: true
});
initializing = false;
setEditable(true);
$textarea.val(info.realtime.getUserDoc());
};
var onAbort = config.onAbort = function (info) {
setEditable(false);
window.alert("Server Connection Lost");
};
var onLocal = config.onLocal = function () {
if (initializing) { return; }
module.patchText(canonicalize($textarea.val()));
};
var rt = window.rt = Realtime.start(config);
var splice = function (str, index, chars) {
var count = chars.length;
return str.slice(0, index) + chars + str.slice((index -1) + count);
};
var setSelectionRange = function (input, start, end) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(start, end);
} else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
};
var setCursor = function (el, pos) {
setSelectionRange(el, pos, pos);
};
var state = {};
// TODO
$textarea.on('keydown', function (e) {
// track when control keys are pushed down
//switch (e.key) { }
});
// TODO
$textarea.on('keyup', function (e) {
// track when control keys are released
});
//$textarea.on('change', onLocal);
$textarea.on('keypress', function (e) {
onLocal();
switch (e.key) {
case 'Tab':
// insert a tab wherever the cursor is...
var start = $textarea.prop('selectionStart');
var end = $textarea.prop('selectionEnd');
if (typeof start !== 'undefined') {
if (start === end) {
$textarea.val(function (i, val) {
return splice(val, start, "\t");
});
setCursor($textarea[0], start +1);
} else {
// indentation?? this ought to be fun.
}
}
// simulate a keypress so the event goes through..
// prevent default behaviour for tab
e.preventDefault();
onLocal();
break;
default:
break;
}
});
['cut', 'paste', 'change', 'keyup', 'keydown', 'select', 'textInput']
.forEach(function (evt) {
$textarea.on(evt, onLocal);
});
$run.click(function (e) {
e.preventDefault();
var content = $textarea.val();
try {
eval(content); // jshint ignore:line
} catch (err) {
// FIXME don't use alert, make an errorbox
window.alert(err.message);
console.error(err);
}
});
});

@ -26,15 +26,13 @@ define([
}); });
}; };
var initializing = true;
setEditable(false); setEditable(false);
var rt = module.rt = RtListMap.create(config); var rt = module.rt = RtListMap.create(config);
rt.proxy.on('create', function (info) { rt.proxy.on('create', function (info) {
console.log("initializing..."); console.log("initializing...");
window.location.hash = info.channel + secret.key; window.location.hash = info.channel + secret.key;
}).on('ready', function (info) { }).on('ready', function () {
console.log("...your realtime object is ready"); console.log("...your realtime object is ready");
rt.proxy rt.proxy
@ -42,7 +40,7 @@ define([
.on('change', [], function (o, n, p) { .on('change', [], function (o, n, p) {
console.log("root change event firing for path [%s]: %s => %s", p.join(','), o, n); console.log("root change event firing for path [%s]: %s => %s", p.join(','), o, n);
}) })
.on('remove', [], function (o, p, root) { .on('remove', [], function (o, p) {
console.log("Removal of value [%s] at path [%s]", o, p.join(',')); console.log("Removal of value [%s] at path [%s]", o, p.join(','));
}) })
.on('change', ['a', 'b', 'c'], function (o, n, p) { .on('change', ['a', 'b', 'c'], function (o, n, p) {
@ -51,7 +49,7 @@ define([
return false; return false;
}) })
// on(event, cb) // on(event, cb)
.on('disconnect', function (info) { .on('disconnect', function () {
setEditable(false); setEditable(false);
window.alert("Network connection lost"); window.alert("Network connection lost");
}); });
@ -65,6 +63,7 @@ define([
console.log("evaluating `%s`", value); console.log("evaluating `%s`", value);
var x = rt.proxy; var x = rt.proxy;
x = x; // LOL jshint says this is unused otherwise <3
console.log('> ', eval(value)); // jshint ignore:line console.log('> ', eval(value)); // jshint ignore:line
console.log(); console.log();

@ -3,7 +3,7 @@ define([
'/common/cryptpad-common.js', '/common/cryptpad-common.js',
'/common/pinpad.js' '/common/pinpad.js'
], function ($, Cryptpad, Pinpad) { ], function ($, Cryptpad, Pinpad) {
var APP = window.APP = { window.APP = {
Cryptpad: Cryptpad, Cryptpad: Cryptpad,
}; };
@ -37,7 +37,7 @@ define([
}; };
$(function () { $(function () {
Cryptpad.ready(function (err, env) { Cryptpad.ready(function () {
var network = Cryptpad.getNetwork(); var network = Cryptpad.getNetwork();
var proxy = Cryptpad.getStore().getProxy().proxy; var proxy = Cryptpad.getStore().getProxy().proxy;

@ -2,9 +2,7 @@ define([
'jquery', 'jquery',
'/common/cryptget.js' '/common/cryptget.js'
], function ($, Crypt) { ], function ($, Crypt) {
var $target = $('#target'); var $target = $('#target');
var $dest = $('#dest');
var useDoc = function (err, doc) { var useDoc = function (err, doc) {
if (err) { return console.error(err); } if (err) { return console.error(err); }

@ -55,7 +55,7 @@ define([
var initializing = true; var initializing = true;
var onInit = config.onInit = function (info) { config.onInit = function (info) {
window.location.hash = info.channel + secret.key; window.location.hash = info.channel + secret.key;
module.realtime = info.realtime; module.realtime = info.realtime;
}; };
@ -73,7 +73,7 @@ define([
}; };
// when your editor is ready // when your editor is ready
var onReady = config.onReady = function (info) { config.onReady = function () {
console.log("Realtime is ready!"); console.log("Realtime is ready!");
var userDoc = module.realtime.getUserDoc(); var userDoc = module.realtime.getUserDoc();
lazyDraw(getContent(userDoc)); lazyDraw(getContent(userDoc));
@ -81,13 +81,13 @@ define([
}; };
// when remote editors do things... // when remote editors do things...
var onRemote = config.onRemote = function () { config.onRemote = function () {
if (initializing) { return; } if (initializing) { return; }
var userDoc = module.realtime.getUserDoc(); var userDoc = module.realtime.getUserDoc();
lazyDraw(getContent(userDoc)); lazyDraw(getContent(userDoc));
}; };
var onLocal = config.onLocal = function () { config.onLocal = function () {
// we're not really expecting any local events for this editor... // we're not really expecting any local events for this editor...
/* but we might add a second pane in the future so that you don't need /* but we might add a second pane in the future so that you don't need
a second window to edit your markdown */ a second window to edit your markdown */
@ -96,9 +96,9 @@ define([
lazyDraw(userDoc); lazyDraw(userDoc);
}; };
var onAbort = config.onAbort = function () { config.onAbort = function () {
window.alert("Network Connection Lost"); window.alert("Network Connection Lost");
}; };
var rts = Realtime.start(config); Realtime.start(config);
}); });

@ -20,8 +20,6 @@ define([
crypto: Crypto.createEncryptor(secret.key), crypto: Crypto.createEncryptor(secret.key),
}; };
var userName = module.userName = config.userName = Crypto.rand64(8);
var lazyDraw = (function () { var lazyDraw = (function () {
var to, var to,
delay = 500; delay = 500;
@ -37,7 +35,7 @@ define([
var initializing = true; var initializing = true;
var onInit = config.onInit = function (info) { config.onInit = function (info) {
window.location.hash = info.channel + secret.key; window.location.hash = info.channel + secret.key;
var realtime = module.realtime = info.realtime; var realtime = module.realtime = info.realtime;
module.patchText = TextPatcher.create({ module.patchText = TextPatcher.create({
@ -50,28 +48,28 @@ define([
}); });
}; };
var onReady = config.onReady = function (info) { config.onReady = function () {
var userDoc = module.realtime.getUserDoc(); var userDoc = module.realtime.getUserDoc();
draw(userDoc); draw(userDoc);
console.log("Ready"); console.log("Ready");
initializing = false; initializing = false;
}; };
var onRemote = config.onRemote = function () { config.onRemote = function () {
draw(module.realtime.getUserDoc()); draw(module.realtime.getUserDoc());
}; };
var onAbort = config.onAbort = function (info) { config.onAbort = function () {
// notify the user of the abort // notify the user of the abort
window.alert("Network Connection Lost"); window.alert("Network Connection Lost");
}; };
var onLocal = config.onLocal = function () { config.onLocal = function () {
// nope // nope
}; };
$edit.attr('href', '/examples/text/'+ window.location.hash); $edit.attr('href', '/examples/text/'+ window.location.hash);
var rt = Realtime.start(config); Realtime.start(config);
}); });

@ -13,8 +13,6 @@ define([
TextPatcher: TextPatcher TextPatcher: TextPatcher
}; };
var userName = module.userName = Crypto.rand64(8);
var initializing = true; var initializing = true;
var $textarea = $('textarea'); var $textarea = $('textarea');
@ -30,14 +28,14 @@ define([
setEditable(false); setEditable(false);
var onInit = config.onInit = function (info) { config.onInit = function (info) {
window.location.hash = info.channel + secret.key; window.location.hash = info.channel + secret.key;
$(window).on('hashchange', function() { $(window).on('hashchange', function() {
window.location.reload(); window.location.reload();
}); });
}; };
var onRemote = config.onRemote = function (info) { config.onRemote = function () {
if (initializing) { return; } if (initializing) { return; }
var userDoc = module.realtime.getUserDoc(); var userDoc = module.realtime.getUserDoc();
var content = canonicalize($textarea.val()); var content = canonicalize($textarea.val());
@ -59,7 +57,7 @@ define([
module.patchText(canonicalize($textarea.val())); module.patchText(canonicalize($textarea.val()));
}; };
var onReady = config.onReady = function (info) { config.onReady = function (info) {
var realtime = module.realtime = info.realtime; var realtime = module.realtime = info.realtime;
module.patchText = TextPatcher.create({ module.patchText = TextPatcher.create({
realtime: realtime realtime: realtime
@ -71,12 +69,12 @@ define([
initializing = false; initializing = false;
}; };
var onAbort = config.onAbort = function (info) { config.onAbort = function () {
setEditable(false); setEditable(false);
window.alert("Server Connection Lost"); window.alert("Server Connection Lost");
}; };
var onConnectionChange = config.onConnectionChange = function (info) { config.onConnectionChange = function (info) {
if (info.state) { if (info.state) {
initializing = true; initializing = true;
} else { } else {
@ -85,7 +83,7 @@ define([
} }
}; };
var rt = Realtime.start(config); Realtime.start(config);
['cut', 'paste', 'change', 'keyup', 'keydown', 'select', 'textInput'] ['cut', 'paste', 'change', 'keyup', 'keydown', 'select', 'textInput']
.forEach(function (evt) { .forEach(function (evt) {

@ -27,7 +27,7 @@ define([
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.open("GET", src, true); xhr.open("GET", src, true);
xhr.responseType = "arraybuffer"; xhr.responseType = "arraybuffer";
xhr.onload = function (e) { xhr.onload = function () {
return void cb(void 0, new Uint8Array(xhr.response)); return void cb(void 0, new Uint8Array(xhr.response));
}; };
xhr.send(null); xhr.send(null);
@ -57,19 +57,19 @@ define([
var again = function (state, box) { var again = function (state, box) {
switch (state) { switch (state) {
case 0: case 0:
sendChunk(box, function (e, msg) { sendChunk(box, function (e) {
if (e) { return console.error(e); } if (e) { return console.error(e); }
next(again); next(again);
}); });
break; break;
case 1: case 1:
sendChunk(box, function (e, msg) { sendChunk(box, function (e) {
if (e) { return console.error(e); } if (e) { return console.error(e); }
next(again); next(again);
}); });
break; break;
case 2: case 2:
sendChunk(box, function (e, msg) { sendChunk(box, function (e) {
if (e) { return console.error(e); } if (e) { return console.error(e); }
Cryptpad.rpc.send('UPLOAD_COMPLETE', '', function (e, res) { Cryptpad.rpc.send('UPLOAD_COMPLETE', '', function (e, res) {
if (e) { return void console.error(e); } if (e) { return void console.error(e); }
@ -171,7 +171,6 @@ define([
document.title = title; document.title = title;
}; };
var blob;
var exportFile = function () { var exportFile = function () {
var suggestion = document.title; var suggestion = document.title;
Cryptpad.prompt(Messages.exportPrompt, Cryptpad.prompt(Messages.exportPrompt,
@ -239,10 +238,10 @@ define([
display: 'block', display: 'block',
}); });
var $file = $form.find("#file").on('change', function (e) { $form.find("#file").on('change', function (e) {
var file = e.target.files[0]; var file = e.target.files[0];
var reader = new FileReader(); var reader = new FileReader();
reader.onloadend = function (e) { reader.onloadend = function () {
upload(this.result, { upload(this.result, {
name: file.name, name: file.name,
type: file.type, type: file.type,
@ -255,7 +254,7 @@ define([
Cryptpad.removeLoadingScreen(); Cryptpad.removeLoadingScreen();
}; };
Cryptpad.ready(function (err, anv) { Cryptpad.ready(function () {
andThen(); andThen();
Cryptpad.reportAppUsage(); Cryptpad.reportAppUsage();
}); });

@ -3,11 +3,6 @@ define([
'/common/cryptpad-common.js', '/common/cryptpad-common.js',
'/common/login.js' '/common/login.js'
], function ($, Cryptpad, Login) { ], function ($, Cryptpad, Login) {
var APP = window.APP = {
Cryptpad: Cryptpad,
};
$(function () { $(function () {
var $main = $('#mainBlock'); var $main = $('#mainBlock');
var Messages = Cryptpad.Messages; var Messages = Cryptpad.Messages;
@ -61,7 +56,7 @@ define([
$('button.login').click(); $('button.login').click();
}); });
$('button.login').click(function (e) { $('button.login').click(function () {
Cryptpad.addLoadingScreen(Messages.login_hashing); Cryptpad.addLoadingScreen(Messages.login_hashing);
// We need a setTimeout(cb, 0) otherwise the loading screen is only displayed after hashing the password // We need a setTimeout(cb, 0) otherwise the loading screen is only displayed after hashing the password
window.setTimeout(function () { window.setTimeout(function () {

@ -4,13 +4,13 @@ define([
'/bower_components/chainpad-netflux/chainpad-netflux.js', '/bower_components/chainpad-netflux/chainpad-netflux.js',
'/common/toolbar.js', '/common/toolbar.js',
'/common/cryptpad-common.js', '/common/cryptpad-common.js',
'/common/visible.js', //'/common/visible.js',
'/common/notify.js', //'/common/notify.js',
'/bower_components/tweetnacl/nacl-fast.min.js', '/bower_components/tweetnacl/nacl-fast.min.js',
'/bower_components/file-saver/FileSaver.min.js', '/bower_components/file-saver/FileSaver.min.js',
], function ($, Crypto, realtimeInput, Toolbar, Cryptpad, Visible, Notify) { ], function ($, Crypto, realtimeInput, Toolbar, Cryptpad /*, Visible, Notify*/) {
var Messages = Cryptpad.Messages; //var Messages = Cryptpad.Messages;
var saveAs = window.saveAs; //var saveAs = window.saveAs;
//window.Nacl = window.nacl; //window.Nacl = window.nacl;
$(function () { $(function () {
@ -84,17 +84,17 @@ define([
} }
}; };
Toolbar.create($bar, null, null, null, null, configTb); Toolbar.create($bar, null, null, null, null, configTb);
var $rightside = $bar.find('.' + Toolbar.constants.rightside); //var $rightside = $bar.find('.' + Toolbar.constants.rightside);
updateTitle(Cryptpad.initialName || getTitle() || defaultName); updateTitle(Cryptpad.initialName || getTitle() || defaultName);
var mt = MediaTag($mt[0]); MediaTag($mt[0]);
Cryptpad.removeLoadingScreen(); Cryptpad.removeLoadingScreen();
}); });
}; };
Cryptpad.ready(function (err, anv) { Cryptpad.ready(function () {
andThen(); andThen();
Cryptpad.reportAppUsage(); Cryptpad.reportAppUsage();
}); });

@ -42,7 +42,7 @@ define(function () {
}); });
} }
if (editor.contextMenu) { if (editor.contextMenu) {
editor.contextMenu.addListener(function(startElement, selection, path) { editor.contextMenu.addListener(function(startElement) {
if (startElement) { if (startElement) {
var anchor = getActiveLink(editor); var anchor = getActiveLink(editor);
if (anchor && anchor.getAttribute('href')) { if (anchor && anchor.getAttribute('href')) {

@ -87,7 +87,7 @@ define([
return hj; return hj;
}; };
var onConnectError = function (info) { var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError); Cryptpad.errorLoadingScreen(Messages.websocketError);
}; };
@ -103,7 +103,7 @@ define([
}); });
editor.on('instanceReady', Links.addSupportForOpeningLinksInNewTab(Ckeditor)); editor.on('instanceReady', Links.addSupportForOpeningLinksInNewTab(Ckeditor));
editor.on('instanceReady', function (Ckeditor) { editor.on('instanceReady', function () {
var $bar = $('#pad-iframe')[0].contentWindow.$('#cke_1_toolbox'); var $bar = $('#pad-iframe')[0].contentWindow.$('#cke_1_toolbox');
var parsedHash = Cryptpad.parsePadUrl(window.location.href); var parsedHash = Cryptpad.parsePadUrl(window.location.href);
var defaultName = Cryptpad.getDefaultName(parsedHash); var defaultName = Cryptpad.getDefaultName(parsedHash);
@ -167,7 +167,7 @@ define([
if (['addAttribute', 'modifyAttribute'].indexOf(info.diff.action) !== -1) { if (['addAttribute', 'modifyAttribute'].indexOf(info.diff.action) !== -1) {
if (info.diff.name === 'href') { if (info.diff.name === 'href') {
// console.log(info.diff); // console.log(info.diff);
var href = info.diff.newValue; //var href = info.diff.newValue;
// TODO normalize HTML entities // TODO normalize HTML entities
if (/javascript *: */.test(info.diff.newValue)) { if (/javascript *: */.test(info.diff.newValue)) {
@ -314,7 +314,7 @@ define([
uid: Cryptpad.getUid(), uid: Cryptpad.getUid(),
}; };
addToUserData(myData); addToUserData(myData);
Cryptpad.setAttribute('username', newName, function (err, data) { Cryptpad.setAttribute('username', newName, function (err) {
if (err) { if (err) {
console.error("Couldn't set username"); console.error("Couldn't set username");
return; return;
@ -323,11 +323,6 @@ define([
}); });
}; };
var isDefaultTitle = function () {
var parsed = Cryptpad.parsePadUrl(window.location.href);
return Cryptpad.isDefaultName(parsed, document.title);
};
var getHeadingText = function () { var getHeadingText = function () {
var text; var text;
if (['h1', 'h2', 'h3'].some(function (t) { if (['h1', 'h2', 'h3'].some(function (t) {
@ -483,7 +478,7 @@ define([
} }
}; };
var onRemote = realtimeOptions.onRemote = function () { realtimeOptions.onRemote = function () {
if (initializing) { return; } if (initializing) { return; }
if (isHistoryMode) { return; } if (isHistoryMode) { return; }
@ -544,7 +539,7 @@ define([
} }
}; };
var getHTML = function (Dom) { var getHTML = function () {
return ('<!DOCTYPE html>\n' + '<html>\n' + inner.innerHTML); return ('<!DOCTYPE html>\n' + '<html>\n' + inner.innerHTML);
}; };
@ -562,7 +557,7 @@ define([
saveAs(blob, filename); saveAs(blob, filename);
}); });
}; };
var importFile = function (content, file) { var importFile = function (content) {
var shjson = stringify(Hyperjson.fromDOM(domFromHTML(content).body)); var shjson = stringify(Hyperjson.fromDOM(domFromHTML(content).body));
applyHjson(shjson); applyHjson(shjson);
realtimeOptions.onLocal(); realtimeOptions.onLocal();
@ -574,7 +569,7 @@ define([
editor.fire('change'); editor.fire('change');
}; };
var onInit = realtimeOptions.onInit = function (info) { realtimeOptions.onInit = function (info) {
userList = info.userList; userList = info.userList;
var configTb = { var configTb = {
@ -596,11 +591,10 @@ define([
toolbar = info.realtime.toolbar = Toolbar.create($bar, info.myID, info.realtime, info.getLag, userList, configTb); toolbar = info.realtime.toolbar = Toolbar.create($bar, info.myID, info.realtime, info.getLag, userList, configTb);
var $rightside = $bar.find('.' + Toolbar.constants.rightside); var $rightside = $bar.find('.' + Toolbar.constants.rightside);
var $userBlock = $bar.find('.' + Toolbar.constants.username); $bar.find('.' + Toolbar.constants.username);
var $usernameButton = module.$userNameButton = $($bar.find('.' + Toolbar.constants.changeUsername)); module.$userNameButton = $($bar.find('.' + Toolbar.constants.changeUsername));
var editHash; var editHash;
var viewHash = Cryptpad.getViewHashFromKeys(info.channel, secret.keys);
if (!readOnly) { if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys); editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
@ -680,7 +674,7 @@ define([
} }
/* add a forget button */ /* add a forget button */
var forgetCb = function (err, title) { var forgetCb = function (err) {
if (err) { return; } if (err) { return; }
setEditable(false); setEditable(false);
}; };
@ -694,7 +688,7 @@ define([
}; };
// this should only ever get called once, when the chain syncs // this should only ever get called once, when the chain syncs
var onReady = realtimeOptions.onReady = function (info) { realtimeOptions.onReady = function (info) {
if (!module.isMaximized) { if (!module.isMaximized) {
editor.execCommand('maximize'); editor.execCommand('maximize');
module.isMaximized = true; module.isMaximized = true;
@ -780,7 +774,7 @@ define([
}); });
}; };
var onAbort = realtimeOptions.onAbort = function (info) { realtimeOptions.onAbort = function () {
console.log("Aborting the session!"); console.log("Aborting the session!");
// stop the user from continuing to edit // stop the user from continuing to edit
setEditable(false); setEditable(false);
@ -788,7 +782,7 @@ define([
Cryptpad.alert(Messages.common_connectionLost, undefined, true); Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}; };
var onConnectionChange = realtimeOptions.onConnectionChange = function (info) { realtimeOptions.onConnectionChange = function (info) {
setEditable(info.state); setEditable(info.state);
toolbar.failed(); toolbar.failed();
if (info.state) { if (info.state) {
@ -800,7 +794,7 @@ define([
} }
}; };
var onError = realtimeOptions.onError = onConnectError; realtimeOptions.onError = onConnectError;
var onLocal = realtimeOptions.onLocal = function () { var onLocal = realtimeOptions.onLocal = function () {
if (initializing) { return; } if (initializing) { return; }
@ -816,7 +810,7 @@ define([
} }
}; };
var rti = module.realtimeInput = realtimeInput.start(realtimeOptions); module.realtimeInput = realtimeInput.start(realtimeOptions);
Cryptpad.onLogout(function () { setEditable(false); }); Cryptpad.onLogout(function () { setEditable(false); });
@ -834,7 +828,7 @@ define([
// export the typing tests to the window. // export the typing tests to the window.
// call like `test = easyTest()` // call like `test = easyTest()`
// terminate the test like `test.cancel()` // terminate the test like `test.cancel()`
var easyTest = window.easyTest = function () { window.easyTest = function () {
cursor.update(); cursor.update();
var start = cursor.Range.start; var start = cursor.Range.start;
var test = TypingTest.testInput(inner, start.el, start.offset, onLocal); var test = TypingTest.testInput(inner, start.el, start.offset, onLocal);
@ -846,7 +840,7 @@ define([
var interval = 100; var interval = 100;
var second = function (Ckeditor) { var second = function (Ckeditor) {
Cryptpad.ready(function (err, env) { Cryptpad.ready(function () {
andThen(Ckeditor); andThen(Ckeditor);
Cryptpad.reportAppUsage(); Cryptpad.reportAppUsage();
}); });

@ -37,7 +37,7 @@ define([
var error = console.error; var error = console.error;
Cryptpad.addLoadingScreen(); Cryptpad.addLoadingScreen();
var onConnectError = function (info) { var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError); Cryptpad.errorLoadingScreen(Messages.websocketError);
}; };
@ -97,15 +97,6 @@ define([
return newObj; return newObj;
}; };
var setColumnDisabled = function (id, state) {
if (!state) {
$('input[data-rt-id^="' + id + '"]').removeAttr('disabled');
return;
}
$('input[data-rt-id^="' + id + '"]').attr('disabled', 'disabled');
};
var styleUncommittedColumn = function () { var styleUncommittedColumn = function () {
var id = APP.userid; var id = APP.userid;
@ -286,7 +277,7 @@ define([
}; };
/* Called whenever an event is fired on an input element */ /* Called whenever an event is fired on an input element */
var handleInput = function (input, isKeyup) { var handleInput = function (input) {
var type = input.type.toLowerCase(); var type = input.type.toLowerCase();
var id = getRealtimeId(input); var id = getRealtimeId(input);
@ -485,7 +476,7 @@ define([
uid: Cryptpad.getUid(), uid: Cryptpad.getUid(),
}; };
addToUserData(myData); addToUserData(myData);
Cryptpad.setAttribute('username', newName, function (err, data) { Cryptpad.setAttribute('username', newName, function (err) {
if (err) { if (err) {
console.error("Couldn't set username"); console.error("Couldn't set username");
return; return;
@ -558,7 +549,7 @@ define([
var colsOrder = sortColumns(displayedObj.table.colsOrder, userid); var colsOrder = sortColumns(displayedObj.table.colsOrder, userid);
var $table = APP.$table = $(Render.asHTML(displayedObj, null, colsOrder, readOnly)); var $table = APP.$table = $(Render.asHTML(displayedObj, null, colsOrder, readOnly));
var $createRow = APP.$createRow = $('#create-option').click(function () { APP.$createRow = $('#create-option').click(function () {
//console.error("BUTTON CLICKED! LOL"); //console.error("BUTTON CLICKED! LOL");
Render.createRow(proxy, function (empty, id) { Render.createRow(proxy, function (empty, id) {
change(null, null, null, null, function() { change(null, null, null, null, function() {
@ -567,7 +558,7 @@ define([
}); });
}); });
var $createCol = APP.$createCol = $('#create-user').click(function () { APP.$createCol = $('#create-user').click(function () {
Render.createColumn(proxy, function (empty, id) { Render.createColumn(proxy, function (empty, id) {
change(null, null, null, null, function() { change(null, null, null, null, function() {
$('.edit[data-rt-id="' + id + '"]').click(); $('.edit[data-rt-id="' + id + '"]').click();
@ -576,7 +567,7 @@ define([
}); });
// Commit button // Commit button
var $commit = APP.$commit = $('#commit').click(function () { APP.$commit = $('#commit').click(function () {
var uncommittedCopy = JSON.parse(JSON.stringify(APP.uncommitted)); var uncommittedCopy = JSON.parse(JSON.stringify(APP.uncommitted));
APP.uncommitted = {}; APP.uncommitted = {};
prepareProxy(APP.uncommitted, copyObject(Render.Example)); prepareProxy(APP.uncommitted, copyObject(Render.Example));
@ -586,13 +577,13 @@ define([
}); });
// #publish button is removed in readonly // #publish button is removed in readonly
var $publish = APP.$publish = $('#publish') APP.$publish = $('#publish')
.click(function () { .click(function () {
publish(true); publish(true);
}); });
// #publish button is removed in readonly // #publish button is removed in readonly
var $admin = APP.$admin = $('#admin') APP.$admin = $('#admin')
.click(function () { .click(function () {
publish(false); publish(false);
}); });
@ -644,9 +635,7 @@ define([
var el = $description[0]; var el = $description[0];
var selects = ['selectionStart', 'selectionEnd'].map(function (attr) { var selects = ['selectionStart', 'selectionEnd'].map(function (attr) {
var before = el[attr]; return TextPatcher.transformCursor(el[attr], op);
var after = TextPatcher.transformCursor(el[attr], op);
return after;
}); });
$description.val(n); $description.val(n);
if (op) { if (op) {
@ -700,7 +689,7 @@ define([
}); });
}; };
var disconnect = function (info) { var disconnect = function () {
//setEditable(false); // TODO //setEditable(false); // TODO
APP.realtime.toolbar.failed(); APP.realtime.toolbar.failed();
Cryptpad.alert(Messages.common_connectionLost, undefined, true); Cryptpad.alert(Messages.common_connectionLost, undefined, true);
@ -713,11 +702,9 @@ define([
}; };
var create = function (info) { var create = function (info) {
var myID = APP.myID = info.myID; APP.myID = info.myID;
var editHash; var editHash;
var viewHash = Cryptpad.getViewHashFromKeys(info.channel, secret.keys);
if (!readOnly) { if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys); editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
} }
@ -748,17 +735,17 @@ define([
ifrw: window, ifrw: window,
common: Cryptpad, common: Cryptpad,
}; };
var toolbar = info.realtime.toolbar = Toolbar.create(APP.$bar, info.myID, info.realtime, info.getLag, userList, config); info.realtime.toolbar = Toolbar.create(APP.$bar, info.myID, info.realtime, info.getLag, userList, config);
var $bar = APP.$bar; var $bar = APP.$bar;
var $rightside = $bar.find('.' + Toolbar.constants.rightside); var $rightside = $bar.find('.' + Toolbar.constants.rightside);
var $userBlock = $bar.find('.' + Toolbar.constants.username); $bar.find('.' + Toolbar.constants.username);
var $editShare = $bar.find('.' + Toolbar.constants.editShare); $bar.find('.' + Toolbar.constants.editShare);
var $viewShare = $bar.find('.' + Toolbar.constants.viewShare); $bar.find('.' + Toolbar.constants.viewShare);
var $usernameButton = APP.$userNameButton = $($bar.find('.' + Toolbar.constants.changeUsername)); APP.$userNameButton = $($bar.find('.' + Toolbar.constants.changeUsername));
/* add a forget button */ /* add a forget button */
var forgetCb = function (err, title) { var forgetCb = function (err) {
if (err) { return; } if (err) { return; }
disconnect(); disconnect();
}; };
@ -814,6 +801,7 @@ define([
if (!userid) { userid = Render.coluid(); } if (!userid) { userid = Render.coluid(); }
APP.userid = userid; APP.userid = userid;
Cryptpad.setPadAttribute('userid', userid, function (e) { Cryptpad.setPadAttribute('userid', userid, function (e) {
if (e) { console.error(e); }
ready(info, userid, readOnly); ready(info, userid, readOnly);
}); });
}); });

@ -57,7 +57,7 @@ var Renderer = function (Cryptpad) {
return null; return null;
}; };
var getCoordinates = Render.getCoordinates = function (id) { Render.getCoordinates = function (id) {
return id.split('_'); return id.split('_');
}; };
@ -91,7 +91,7 @@ var Renderer = function (Cryptpad) {
return null; return null;
}; };
var createColumn = Render.createColumn = function (obj, cb, id, value) { Render.createColumn = function (obj, cb, id, value) {
var order = Cryptpad.find(obj, ['table', 'colsOrder']); var order = Cryptpad.find(obj, ['table', 'colsOrder']);
if (!order) { throw new Error("Uninitialized realtime object!"); } if (!order) { throw new Error("Uninitialized realtime object!"); }
id = id || coluid(); id = id || coluid();
@ -101,7 +101,7 @@ var Renderer = function (Cryptpad) {
if (typeof(cb) === 'function') { cb(void 0, id); } if (typeof(cb) === 'function') { cb(void 0, id); }
}; };
var removeColumn = Render.removeColumn = function (obj, id, cb) { Render.removeColumn = function (obj, id, cb) {
var order = Cryptpad.find(obj, ['table', 'colsOrder']); var order = Cryptpad.find(obj, ['table', 'colsOrder']);
var parent = Cryptpad.find(obj, ['table', 'cols']); var parent = Cryptpad.find(obj, ['table', 'cols']);
@ -126,7 +126,7 @@ var Renderer = function (Cryptpad) {
} }
}; };
var createRow = Render.createRow = function (obj, cb, id, value) { Render.createRow = function (obj, cb, id, value) {
var order = Cryptpad.find(obj, ['table', 'rowsOrder']); var order = Cryptpad.find(obj, ['table', 'rowsOrder']);
if (!order) { throw new Error("Uninitialized realtime object!"); } if (!order) { throw new Error("Uninitialized realtime object!"); }
id = id || rowuid(); id = id || rowuid();
@ -136,7 +136,7 @@ var Renderer = function (Cryptpad) {
if (typeof(cb) === 'function') { cb(void 0, id); } if (typeof(cb) === 'function') { cb(void 0, id); }
}; };
var removeRow = Render.removeRow = function (obj, id, cb) { Render.removeRow = function (obj, id, cb) {
var order = Cryptpad.find(obj, ['table', 'rowsOrder']); var order = Cryptpad.find(obj, ['table', 'rowsOrder']);
var parent = Cryptpad.find(obj, ['table', 'rows']); var parent = Cryptpad.find(obj, ['table', 'rows']);
@ -153,7 +153,7 @@ var Renderer = function (Cryptpad) {
if (typeof(cb) === 'function') { cb(); } if (typeof(cb) === 'function') { cb(); }
}; };
var setValue = Render.setValue = function (obj, id, value) { Render.setValue = function (obj, id, value) {
var type = typeofId(id); var type = typeofId(id);
switch (type) { switch (type) {
@ -167,7 +167,7 @@ var Renderer = function (Cryptpad) {
} }
}; };
var getValue = Render.getValue = function (obj, id) { Render.getValue = function (obj, id) {
switch (typeofId(id)) { switch (typeofId(id)) {
case 'row': return getRowValue(obj, id); case 'row': return getRowValue(obj, id);
case 'col': return getColumnValue(obj, id); case 'col': return getColumnValue(obj, id);
@ -219,7 +219,7 @@ var Renderer = function (Cryptpad) {
})); }));
} }
if (i === rows.length) { if (i === rows.length) {
return [null].concat(cols.map(function (col) { return [null].concat(cols.map(function () {
return { return {
'class': 'lastRow', 'class': 'lastRow',
}; };
@ -359,7 +359,7 @@ var Renderer = function (Cryptpad) {
return ['TABLE', {id:'table'}, [head, foot, body]]; return ['TABLE', {id:'table'}, [head, foot, body]];
}; };
var asHTML = Render.asHTML = function (obj, rows, cols, readOnly) { Render.asHTML = function (obj, rows, cols, readOnly) {
return Hyperjson.toDOM(toHyperjson(cellMatrix(obj, rows, cols, readOnly), readOnly)); return Hyperjson.toDOM(toHyperjson(cellMatrix(obj, rows, cols, readOnly), readOnly));
}; };
@ -384,9 +384,7 @@ var Renderer = function (Cryptpad) {
var op = TextPatcher.diff(o, n); var op = TextPatcher.diff(o, n);
info.selection = ['selectionStart', 'selectionEnd'].map(function (attr) { info.selection = ['selectionStart', 'selectionEnd'].map(function (attr) {
var before = element[attr]; return TextPatcher.transformCursor(element[attr], op);
var after = TextPatcher.transformCursor(element[attr], op);
return after;
}); });
} }
}; };
@ -432,7 +430,7 @@ var Renderer = function (Cryptpad) {
} }
}; };
var updateTable = Render.updateTable = function (table, obj, conf) { Render.updateTable = function (table, obj, conf) {
var DD = new DiffDOM(diffOptions); var DD = new DiffDOM(diffOptions);
var rows = conf ? conf.rows : null; var rows = conf ? conf.rows : null;

@ -2,14 +2,8 @@ define([
'jquery', 'jquery',
'/common/login.js', '/common/login.js',
'/common/cryptpad-common.js', '/common/cryptpad-common.js',
'/common/cryptget.js', '/common/credential.js' // preloaded for login.js
'/common/credential.js' ], function ($, Login, Cryptpad) {
], function ($, Login, Cryptpad, Crypt) {
var APP = window.APP = {
Login: Login,
};
var Messages = Cryptpad.Messages; var Messages = Cryptpad.Messages;
$(function () { $(function () {

@ -16,10 +16,6 @@ define([
var Messages = Cryptpad.Messages; var Messages = Cryptpad.Messages;
var redirectToMain = function () {
window.location.href = '/';
};
// Manage changes in the realtime object made from another page // Manage changes in the realtime object made from another page
var onRefresh = function (h) { var onRefresh = function (h) {
if (typeof(h) !== "function") { return; } if (typeof(h) !== "function") { return; }
@ -71,7 +67,7 @@ define([
var createDisplayNameInput = function (store) { var createDisplayNameInput = function (store) {
var obj = store.proxy; var obj = store.proxy;
var $div = $('<div>', {'class': 'displayName'}); var $div = $('<div>', {'class': 'displayName'});
var $label = $('<label>', {'for' : 'displayName'}).text(Messages.user_displayName).appendTo($div); $('<label>', {'for' : 'displayName'}).text(Messages.user_displayName).appendTo($div);
$('<br>').appendTo($div); $('<br>').appendTo($div);
var $input = $('<input>', { var $input = $('<input>', {
'type': 'text', 'type': 'text',
@ -114,7 +110,7 @@ define([
}; };
var createResetTips = function () { var createResetTips = function () {
var $div = $('<div>', {'class': 'resetTips'}); var $div = $('<div>', {'class': 'resetTips'});
var $label = $('<label>', {'for' : 'resetTips'}).text(Messages.settings_resetTips).appendTo($div); $('<label>', {'for' : 'resetTips'}).text(Messages.settings_resetTips).appendTo($div);
$('<br>').appendTo($div); $('<br>').appendTo($div);
var $button = $('<button>', {'id': 'resetTips', 'class': 'btn btn-primary'}) var $button = $('<button>', {'id': 'resetTips', 'class': 'btn btn-primary'})
.text(Messages.settings_resetTipsButton).appendTo($div); .text(Messages.settings_resetTipsButton).appendTo($div);
@ -145,7 +141,7 @@ define([
saveAs(blob, filename); saveAs(blob, filename);
}); });
}; };
var importFile = function (content, file) { var importFile = function (content) {
var $spinner = $('<span>', {'class': 'fa fa-spinner fa-pulse'}).appendTo($div); var $spinner = $('<span>', {'class': 'fa fa-spinner fa-pulse'}).appendTo($div);
Crypt.put(Cryptpad.getUserHash() || localStorage[Cryptpad.fileHashKey], content, function (e) { Crypt.put(Cryptpad.getUserHash() || localStorage[Cryptpad.fileHashKey], content, function (e) {
if (e) { console.error(e); } if (e) { console.error(e); }
@ -153,7 +149,7 @@ define([
}); });
}; };
var $label = $('<label>', {'for' : 'exportDrive'}).text(Messages.settings_backupTitle).appendTo($div); $('<label>', {'for' : 'exportDrive'}).text(Messages.settings_backupTitle).appendTo($div);
$('<br>').appendTo($div); $('<br>').appendTo($div);
/* add an export button */ /* add an export button */
var $export = Cryptpad.createButton('export', true, {}, exportFile); var $export = Cryptpad.createButton('export', true, {}, exportFile);
@ -170,7 +166,7 @@ define([
var createResetDrive = function (obj) { var createResetDrive = function (obj) {
var $div = $('<div>', {'class': 'resetDrive'}); var $div = $('<div>', {'class': 'resetDrive'});
var $label = $('<label>', {'for' : 'resetDrive'}).text(Messages.settings_resetTitle).appendTo($div); $('<label>', {'for' : 'resetDrive'}).text(Messages.settings_resetTitle).appendTo($div);
$('<br>').appendTo($div); $('<br>').appendTo($div);
var $button = $('<button>', {'id': 'resetDrive', 'class': 'btn btn-danger'}) var $button = $('<button>', {'id': 'resetDrive', 'class': 'btn btn-danger'})
.text(Messages.settings_reset).appendTo($div); .text(Messages.settings_reset).appendTo($div);
@ -259,7 +255,7 @@ define([
var createImportLocalPads = function (obj) { var createImportLocalPads = function (obj) {
if (!Cryptpad.isLoggedIn()) { return; } if (!Cryptpad.isLoggedIn()) { return; }
var $div = $('<div>', {'class': 'importLocalPads'}); var $div = $('<div>', {'class': 'importLocalPads'});
var $label = $('<label>', {'for' : 'importLocalPads'}).text(Messages.settings_importTitle).appendTo($div); $('<label>', {'for' : 'importLocalPads'}).text(Messages.settings_importTitle).appendTo($div);
$('<br>').appendTo($div); $('<br>').appendTo($div);
var $button = $('<button>', {'id': 'importLocalPads', 'class': 'btn btn-primary'}) var $button = $('<button>', {'id': 'importLocalPads', 'class': 'btn btn-primary'})
.text(Messages.settings_import).appendTo($div); .text(Messages.settings_import).appendTo($div);
@ -284,7 +280,7 @@ define([
var createLanguageSelector = function () { var createLanguageSelector = function () {
var $div = $('<div>', {'class': 'importLocalPads'}); var $div = $('<div>', {'class': 'importLocalPads'});
var $label = $('<label>').text(Messages.language).appendTo($div); $('<label>').text(Messages.language).appendTo($div);
$('<br>').appendTo($div); $('<br>').appendTo($div);
var $b = Cryptpad.createLanguageSelector().appendTo($div); var $b = Cryptpad.createLanguageSelector().appendTo($div);
$b.find('button').addClass('btn btn-secondary'); $b.find('button').addClass('btn btn-secondary');
@ -343,7 +339,6 @@ define([
}); });
window.addEventListener('storage', function (e) { window.addEventListener('storage', function (e) {
var key = e.key;
if (e.key !== Cryptpad.userHashKey) { return; } if (e.key !== Cryptpad.userHashKey) { return; }
var o = e.oldValue; var o = e.oldValue;
var n = e.newValue; var n = e.newValue;

@ -57,7 +57,7 @@ define([
var presentMode = Slide.isPresentURL(); var presentMode = Slide.isPresentURL();
var onConnectError = function (info) { var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError); Cryptpad.errorLoadingScreen(Messages.websocketError);
}; };
@ -222,11 +222,6 @@ define([
} }
}; };
var isDefaultTitle = function () {
var parsed = Cryptpad.parsePadUrl(window.location.href);
return Cryptpad.isDefaultName(parsed, APP.title);
};
var initializing = true; var initializing = true;
var stringifyInner = function (textValue) { var stringifyInner = function (textValue) {
@ -281,7 +276,7 @@ define([
uid: Cryptpad.getUid(), uid: Cryptpad.getUid(),
}; };
addToUserData(myData); addToUserData(myData);
Cryptpad.setAttribute('username', myUserName, function (err, data) { Cryptpad.setAttribute('username', myUserName, function (err) {
if (err) { if (err) {
console.log("Couldn't set username"); console.log("Couldn't set username");
console.error(err); console.error(err);
@ -506,13 +501,13 @@ define([
h = Cryptpad.listenForKeys(todo, todoCancel); h = Cryptpad.listenForKeys(todo, todoCancel);
var $nav = $('<nav>').appendTo($div); var $nav = $('<nav>').appendTo($div);
var $cancel = $('<button>', {'class': 'cancel'}).text(Messages.cancelButton).appendTo($nav).click(todoCancel); $('<button>', {'class': 'cancel'}).text(Messages.cancelButton).appendTo($nav).click(todoCancel);
var $ok = $('<button>', {'class': 'ok'}).text(Messages.settings_save).appendTo($nav).click(todo); $('<button>', {'class': 'ok'}).text(Messages.settings_save).appendTo($nav).click(todo);
return $container; return $container;
}; };
var onInit = config.onInit = function (info) { config.onInit = function (info) {
userList = info.userList; userList = info.userList;
var configTb = { var configTb = {
@ -534,11 +529,10 @@ define([
toolbar = module.toolbar = Toolbar.create($bar, info.myID, info.realtime, info.getLag, info.userList, configTb); toolbar = module.toolbar = Toolbar.create($bar, info.myID, info.realtime, info.getLag, info.userList, configTb);
var $rightside = $bar.find('.' + Toolbar.constants.rightside); var $rightside = $bar.find('.' + Toolbar.constants.rightside);
var $userBlock = $bar.find('.' + Toolbar.constants.username); $bar.find('.' + Toolbar.constants.username);
var $usernameButton = module.$userNameButton = $($bar.find('.' + Toolbar.constants.changeUsername)); module.$userNameButton = $($bar.find('.' + Toolbar.constants.changeUsername));
var editHash; var editHash;
var viewHash = Cryptpad.getViewHashFromKeys(info.channel, secret.keys);
if (!readOnly) { if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys); editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
@ -595,14 +589,10 @@ define([
/* add an import button */ /* add an import button */
var $import = Cryptpad.createButton('import', true, {}, importText); var $import = Cryptpad.createButton('import', true, {}, importText);
$rightside.append($import); $rightside.append($import);
/* add a rename button */
//var $setTitle = Cryptpad.createButton('rename', true, {suggestName: suggestName}, renameCb);
//$rightside.append($setTitle);
} }
/* add a forget button */ /* add a forget button */
var forgetCb = function (err, title) { var forgetCb = function (err) {
if (err) { return; } if (err) { return; }
setEditable(false); setEditable(false);
}; };
@ -675,11 +665,10 @@ define([
initialValue: lastTheme initialValue: lastTheme
}; };
var $block = module.$theme = Cryptpad.createDropdown(dropdownConfig); var $block = module.$theme = Cryptpad.createDropdown(dropdownConfig);
var $button = $block.find('.buttonTitle');
setTheme(lastTheme, $block); setTheme(lastTheme, $block);
$block.find('a').click(function (e) { $block.find('a').click(function () {
var theme = $(this).attr('data-value'); var theme = $(this).attr('data-value');
setTheme(theme, $block); setTheme(theme, $block);
localStorage.setItem(themeKey, theme); localStorage.setItem(themeKey, theme);
@ -762,7 +751,7 @@ define([
} }
}; };
var onReady = config.onReady = function (info) { config.onReady = function (info) {
module.users = info.userList.users; module.users = info.userList.users;
if (module.realtime !== info.realtime) { if (module.realtime !== info.realtime) {
@ -883,7 +872,7 @@ define([
return cursor; return cursor;
}; };
var onRemote = config.onRemote = function () { config.onRemote = function () {
if (initializing) { return; } if (initializing) { return; }
if (isHistoryMode) { return; } if (isHistoryMode) { return; }
var scroll = editor.getScrollInfo(); var scroll = editor.getScrollInfo();
@ -940,14 +929,14 @@ define([
} }
}; };
var onAbort = config.onAbort = function (info) { config.onAbort = function () {
// inform of network disconnect // inform of network disconnect
setEditable(false); setEditable(false);
toolbar.failed(); toolbar.failed();
Cryptpad.alert(Messages.common_connectionLost, undefined, true); Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}; };
var onConnectionChange = config.onConnectionChange = function (info) { config.onConnectionChange = function (info) {
setEditable(info.state); setEditable(info.state);
toolbar.failed(); toolbar.failed();
if (info.state) { if (info.state) {
@ -959,9 +948,9 @@ define([
} }
}; };
var onError = config.onError = onConnectError; config.onError = onConnectError;
var realtime = module.realtime = Realtime.start(config); module.realtime = Realtime.start(config);
editor.on('change', onLocal); editor.on('change', onLocal);
@ -971,7 +960,7 @@ define([
var interval = 100; var interval = 100;
var second = function (CM) { var second = function (CM) {
Cryptpad.ready(function (err, env) { Cryptpad.ready(function () {
andThen(CM); andThen(CM);
Cryptpad.reportAppUsage(); Cryptpad.reportAppUsage();
}); });

@ -9,7 +9,7 @@ define([
var checkedTaskItemPtn = /^\s*\[x\]\s*/; var checkedTaskItemPtn = /^\s*\[x\]\s*/;
var uncheckedTaskItemPtn = /^\s*\[ \]\s*/; var uncheckedTaskItemPtn = /^\s*\[ \]\s*/;
renderer.listitem = function (text, level) { renderer.listitem = function (text) {
var isCheckedTaskItem = checkedTaskItemPtn.test(text); var isCheckedTaskItem = checkedTaskItemPtn.test(text);
var isUncheckedTaskItem = uncheckedTaskItemPtn.test(text); var isUncheckedTaskItem = uncheckedTaskItemPtn.test(text);
if (isCheckedTaskItem) { if (isCheckedTaskItem) {
@ -28,8 +28,6 @@ define([
renderer: renderer renderer: renderer
}); });
var truthy = function (x) { return x; };
var Slide = { var Slide = {
index: 0, index: 0,
lastIndex: 0, lastIndex: 0,
@ -59,8 +57,7 @@ define([
var change = function (oldIndex, newIndex) { var change = function (oldIndex, newIndex) {
if (Slide.changeHandlers.length) { if (Slide.changeHandlers.length) {
Slide.changeHandlers.some(function (f, i) { Slide.changeHandlers.some(function (f) {
// HERE
f(oldIndex, newIndex, getNumberOfSlides()); f(oldIndex, newIndex, getNumberOfSlides());
}); });
} }
@ -194,7 +191,7 @@ define([
change(Slide.lastIndex, Slide.index); change(Slide.lastIndex, Slide.index);
}; };
var updateOptions = Slide.updateOptions = function () { Slide.updateOptions = function () {
draw(Slide.index); draw(Slide.index);
}; };
@ -233,7 +230,7 @@ define([
$modal.removeClass('shown'); $modal.removeClass('shown');
}; };
var update = Slide.update = function (content, init) { Slide.update = function (content, init) {
if (!Slide.shown && !init) { return; } if (!Slide.shown && !init) { return; }
if (!content) { content = ''; } if (!content) { content = ''; }
var old = Slide.content; var old = Slide.content;
@ -245,7 +242,7 @@ define([
change(Slide.lastIndex, Slide.index); change(Slide.lastIndex, Slide.index);
}; };
var left = Slide.left = function () { Slide.left = function () {
console.log('left'); console.log('left');
Slide.lastIndex = Slide.index; Slide.lastIndex = Slide.index;
@ -253,7 +250,7 @@ define([
Slide.draw(i); Slide.draw(i);
}; };
var right = Slide.right = function () { Slide.right = function () {
console.log('right'); console.log('right');
Slide.lastIndex = Slide.index; Slide.lastIndex = Slide.index;
@ -261,7 +258,7 @@ define([
Slide.draw(i); Slide.draw(i);
}; };
var first = Slide.first = function () { Slide.first = function () {
console.log('first'); console.log('first');
Slide.lastIndex = Slide.index; Slide.lastIndex = Slide.index;
@ -269,7 +266,7 @@ define([
Slide.draw(i); Slide.draw(i);
}; };
var last = Slide.last = function () { Slide.last = function () {
console.log('end'); console.log('end');
Slide.lastIndex = Slide.index; Slide.lastIndex = Slide.index;
@ -279,7 +276,7 @@ define([
var addEvent = function () { var addEvent = function () {
var icon_to; var icon_to;
$modal.mousemove(function (e) { $modal.mousemove(function () {
var $buttons = $modal.find('.button'); var $buttons = $modal.find('.button');
$buttons.show(); $buttons.show();
if (icon_to) { window.clearTimeout(icon_to); } if (icon_to) { window.clearTimeout(icon_to); }
@ -287,17 +284,17 @@ define([
$buttons.fadeOut(); $buttons.fadeOut();
}, 1000); }, 1000);
}); });
$modal.find('#button_exit').click(function (e) { $modal.find('#button_exit').click(function () {
var ev = $.Event("keyup"); var ev = $.Event("keyup");
ev.which = 27; ev.which = 27;
$modal.trigger(ev); $modal.trigger(ev);
}); });
$modal.find('#button_left').click(function (e) { $modal.find('#button_left').click(function () {
var ev = $.Event("keyup"); var ev = $.Event("keyup");
ev.which = 37; ev.which = 37;
$modal.trigger(ev); $modal.trigger(ev);
}); });
$modal.find('#button_right').click(function (e) { $modal.find('#button_right').click(function () {
var ev = $.Event("keyup"); var ev = $.Event("keyup");
ev.which = 39; ev.which = 39;
$modal.trigger(ev); $modal.trigger(ev);

@ -24,7 +24,7 @@ define([
$(function () { $(function () {
Cryptpad.addLoadingScreen(); Cryptpad.addLoadingScreen();
var onConnectError = function (info) { var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError); Cryptpad.errorLoadingScreen(Messages.websocketError);
}; };
var toolbar; var toolbar;
@ -330,8 +330,7 @@ window.canvas = canvas;
return $color; return $color;
}; };
var editHash; config.onInit = function (info) {
var onInit = config.onInit = function (info) {
userList = info.userList; userList = info.userList;
var config = { var config = {
displayed: ['useradmin', 'spinner', 'lag', 'state', 'share', 'userlist', 'newpad', 'limit'], displayed: ['useradmin', 'spinner', 'lag', 'state', 'share', 'userlist', 'newpad', 'limit'],
@ -370,7 +369,7 @@ window.canvas = canvas;
var $export = Cryptpad.createButton('export', true, {}, saveImage); var $export = Cryptpad.createButton('export', true, {}, saveImage);
$rightside.append($export); $rightside.append($export);
var $forget = Cryptpad.createButton('forget', true, {}, function (err, title) { var $forget = Cryptpad.createButton('forget', true, {}, function (err) {
if (err) { return; } if (err) { return; }
setEditable(false); setEditable(false);
toolbar.failed(); toolbar.failed();
@ -380,7 +379,6 @@ window.canvas = canvas;
makeColorButton($rightside); makeColorButton($rightside);
var editHash; var editHash;
var viewHash = Cryptpad.getViewHashFromKeys(info.channel, secret.keys);
if (!readOnly) { if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys); editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
@ -522,7 +520,7 @@ window.canvas = canvas;
uid: Cryptpad.getUid(), uid: Cryptpad.getUid(),
}; };
addToUserData(myData); addToUserData(myData);
Cryptpad.setAttribute('username', myUserName, function (err, data) { Cryptpad.setAttribute('username', myUserName, function (err) {
if (err) { if (err) {
console.log("Couldn't set username"); console.log("Couldn't set username");
console.error(err); console.error(err);
@ -532,7 +530,7 @@ window.canvas = canvas;
}); });
}; };
var onReady = config.onReady = function (info) { config.onReady = function (info) {
var realtime = module.realtime = info.realtime; var realtime = module.realtime = info.realtime;
module.patchText = TextPatcher.create({ module.patchText = TextPatcher.create({
realtime: realtime realtime: realtime
@ -578,14 +576,14 @@ window.canvas = canvas;
}); });
}; };
var onAbort = config.onAbort = function (info) { config.onAbort = function () {
setEditable(false); setEditable(false);
toolbar.failed(); toolbar.failed();
Cryptpad.alert(Messages.common_connectionLost, undefined, true); Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}; };
// TODO onConnectionStateChange // TODO onConnectionStateChange
var onConnectionChange = config.onConnectionChange = function (info) { config.onConnectionChange = function (info) {
setEditable(info.state); setEditable(info.state);
toolbar.failed(); toolbar.failed();
if (info.state) { if (info.state) {
@ -597,7 +595,7 @@ window.canvas = canvas;
} }
}; };
var rt = Realtime.start(config); module.rt = Realtime.start(config);
canvas.on('mouse:up', onLocal); canvas.on('mouse:up', onLocal);
@ -611,7 +609,7 @@ window.canvas = canvas;
}); });
}; };
Cryptpad.ready(function (err, env) { Cryptpad.ready(function () {
andThen(); andThen();
Cryptpad.reportAppUsage(); Cryptpad.reportAppUsage();
}); });

Loading…
Cancel
Save