replace old poll app with new

pull/1/head
ansuz 8 years ago
parent 387f4ebf5d
commit aae443c8e9

@ -0,0 +1,114 @@
<!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"/>
<title data-localization="poll_title">Zero Knowledge Date Picker</title>
<link rel="icon" type="image/png"
href="/customize/main-favicon.png"
data-main-favicon="/customize/main-favicon.png"
data-alt-favicon="/customize/alt-favicon.png"
id="favicon" />
<link rel="stylesheet" href="/customize/main.css" />
<script data-main="main" src="/bower_components/requirejs/require.js"></script>
<script>
require.config({
waitSeconds: 60,
});
</script>
<style>
html, body {
width: 100;
margin-top: 1.25em;
height: auto;
}
#main {
margin: auto;
}
.clickable {
cursor: pointer;
}
#adduser, #addoption {
font-weight: bold;
}
</style>
</head>
<body>
<div id="main">
<div id="toolbar" class="buttons">
</div>
<h1 id="mainTitle">CryptPoll</h1>
<h2 data-localization="poll_subtitle"></h2>
<p data-localization="poll_p_save"></p>
<p data-localization="poll_p_encryption"></p>
<hr>
<br>
<form class="realtime">
<input type="text" id="title" placeholder="title"><br />
<textarea id="description" placeholder="description"></textarea>
<p id="howToUse" data-localization="poll_p_howtouse"></p>
<!-- Table markup-->
<table id="table">
<!-- Table header -->
<thead>
<tr>
<td>
<div id="adduser" class="clickable" data-localization="poll_addUserButton" data-localization-title="poll_addUserButtonTitle"></div>
</td>
</tr>
</thead>
<!-- Table footer -->
<tfoot>
<tr>
<td>
<div id="addoption" class="clickable" data-localization="poll_addOptionButton" data-localization-title="poll_addOptionButtonTitle"></div>
</td>
</tr>
</tfoot>
<!-- Table body -->
<tbody>
</tbody>
</table>
</form>
<div class="modal" id="wizard-modal">
<button id="close-wizard" class="button action" data-localization="poll_closeWizardButton" data-localization-title="poll_closeWizardButtonTitle"></button>
<div class="center">
<div id="modal-toolbar">
<button id="get-options" class="action button" data-localization="poll_wizardComputeButton"></button>
<button id="clear-table" class="action button" data-localization="poll_wizardClearButton"></button>
</div>
<h2 data-localization="poll_wizardDescription"></h2>
<table id="wizard-table">
<thead>
<tr>
<td>
<div id="adddate" class="clickable" data-localization="poll_wizardAddDateButton"></div>
</td>
</tr>
</thead>
<tfoot>
<tr>
<td>
<div id="addtime" class="clickable" data-localization="poll_wizardAddTimeButton"></div>
</td>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</div>
</div>

@ -0,0 +1,943 @@
define([
'/api/config?cb=' + Math.random().toString(16).substring(2),
'/customize/messages.js?app=poll',
'/poll/table.js',
'/poll/wizard.js',
'/bower_components/textpatcher/TextPatcher.js',
'/bower_components/chainpad-listmap/chainpad-listmap.js',
'/bower_components/chainpad-crypto/crypto.js',
'/common/cryptpad-common.js',
'/common/visible.js',
'/common/notify.js',
'/bower_components/file-saver/FileSaver.min.js',
'/bower_components/jquery/dist/jquery.min.js',
'/customize/pad.js'
], function (Config, Messages, Table, Wizard, TextPatcher, Listmap, Crypto, Cryptpad, Visible, Notify) {
var $ = window.jQuery;
var saveAs = window.saveAs;
Cryptpad.styleAlerts();
console.log("Initializing your realtime session...");
/* TODO
* set range of dates/times
* (pair of date pickers)
* hide options within that range
* show hidden options
* add notes to a particular time slot
* check or uncheck options for a particular user
* mark preference level? (+1, 0, -1)
* delete/hide columns/rows
// let users choose what they want the default input to be...
* date
- http://foxrunsoftware.github.io/DatePicker/ ?
* ???
*/
var secret = Cryptpad.getSecrets();
var readOnly = secret.keys && !secret.keys.editKeyStr;
if (!secret.keys) {
secret.keys = secret.key;
}
if (readOnly) {
$('#mainTitle').html($('#mainTitle').html() + ' - ' + Messages.readonly);
$('#adduser, #addoption, #howToUse').remove();
}
var module = window.APP = {
Cryptpad: Cryptpad,
};
module.getResults = function () {
if (!module.ready) { return []; }
var table = module.rt.proxy.table;
var cells = table.cells;
var rows = table.rows;
return Object.keys(rows).map(function (id) {
var text = rows[id];
var count = Object.keys(cells).filter(function (c) {
return c.indexOf(id) !== -1 && cells[c];
}).length;
return {
text: text,
count: count,
};
}).sort(function (a,b) {
return b.count - a.count;
});
};
var getLastName = module.getLastName = function (cb) {
Cryptpad.getAttribute('username', function (err, userName) {
cb(err, userName || '');
});
};
var setName = module.setName = function (uname, cb) {
if (typeof(uname) !== 'string') {
return void cb(new Error('expected string'));
}
uname = Cryptpad.fixHTML(uname.trim()).slice(0, 32);
Cryptpad.setAttribute('username', uname, function (err, data) {
if (err) { return void cb(err); }
cb(void 0, uname);
});
};
module.Wizard = Wizard;
// special UI elements
var $title = $('#title').attr('placeholder', Messages.poll_titleHint || 'title');
var $description = $('#description').attr('placeholder', Messages.poll_descriptionHint || 'description');
var items = [$title, $description];
var Uid = function (prefix, f) {
f = f || function () {
return Number(Math.random() * Number.MAX_SAFE_INTEGER)
.toString(32).replace(/\./g, '');
};
return function () { return prefix + '-' + f(); };
};
var xy = function (x, y) { return x + '_' + y; };
var parseXY = function (id) {
var p = id.split('_');
return {
x: p[0],
y: p[1],
};
};
var Input = function (opt) { return $('<input>', opt); };
var Checkbox = function (id) {
var p = parseXY(id);
var proxy = module.rt.proxy;
var $div = $('<div>', {
'class': 'checkbox-contain',
});
var $cover = $('<span>', {
'class': 'cover'
});
var $label = $('<label>', {
'for': id,
}); //.text("WAT");
var $check = Input({
id: id,
name: id,
type:'checkbox',
}).on('change', function () {
//console.log("(%s, %s) => %s", p.x, p.y, $check[0].checked);
var checked = proxy.table.cells[id] = $check[0].checked? 1: 0;
if (checked) {
$cover.addClass('yes');
}
else {
$cover.removeClass('yes');
}
});
if (p.x === module.activeColumn) {
$check.addClass('editable');
}
$div
//.append($label)
.append($check)
.append($label);
$check.after($cover);
return $div; //$check;
};
var Text = function () { return Input({type:'text'}); };
var table = module.table = Table($('#table'), xy);
var setEditable = function (bool) {
if (readOnly && bool) { return; }
module.isEditable = bool;
items.forEach(function ($item) {
$item.attr('disabled', !bool);
});
if (!bool) {
$('input[id^="y"]').each(function (i, e) {
var $option = $(this);
$option.attr('disabled', true);
console.log($option.val());
});
}
};
var coluid = Uid('x');
var rowuid = Uid('y');
var addIfAbsent = function (A, e) {
if (A.indexOf(e) !== -1) { return; }
A.push(e);
};
var removeRow = function (proxy, uid) {
if (readOnly) { return; }
// remove proxy.table.rows[uid]
proxy.table.rows[uid] = undefined;
delete proxy.table.rows[uid];
// remove proxy.table.rowsOrder
var order = proxy.table.rowsOrder;
order.splice(order.indexOf(uid), 1);
// remove all cells including uid
// proxy.table.cells
Object.keys(proxy.table.cells).forEach(function (cellUid) {
if (cellUid.indexOf(uid) === -1) { return; }
proxy.table.cells[cellUid] = undefined;
delete proxy.table.cells[cellUid];
});
// remove elements from DOM
table.removeRow(uid);
};
var removeColumn = function (proxy, uid) {
if (readOnly) { return; }
// remove proxy.table.cols[uid]
proxy.table.cols[uid] = undefined;
delete proxy.table.rows[uid];
// remove proxy.table.colsOrder
var order = proxy.table.colsOrder;
order.splice(order.indexOf(uid), 1);
// remove all cells including uid
Object.keys(proxy.table.cells).forEach(function (cellUid) {
if (cellUid.indexOf(uid) === -1) { return; }
proxy.table.cells[cellUid] = undefined;
delete proxy.table.cells[cellUid];
});
// remove elements from DOM
table.removeColumn(uid);
};
var removeFromArray = function (A, e) {
var i = A.indexOf(e);
if (i === -1) { return; }
A.splice(i, 1);
};
var makeUserEditable = module.makeUserEditable = function (id, bool) {
if (readOnly) { return; }
var $name = $('input[type="text"][id="' + id + '"]').attr('disabled', !bool);
var $edit = $name.parent().find('.edit');
$edit[bool?'addClass':'removeClass']('editable');
var $sel = $('input[id^="' + id + '"]')
[bool?'addClass':'removeClass']('editable')
.attr('disabled', !bool);
if (bool) {
var $target = $('tfoot td')
.eq(module.rt.proxy.table.colsOrder.indexOf(id) + 1);
if ($target.length) {
var $save = $('<span>', {
'class': 'save action',
'for': id,
})
.text(Messages.commitButton)
.click(function () {
module.activeColumn = '';
makeUserEditable(id, false);
});
$target.append($save);
}
module.activeColumn = id;
module.rt.proxy.table.colsOrder.forEach(function (coluid) {
if (coluid !== id) { makeUserEditable(coluid, false); }
});
} else {
$('.save[for="' + id + '"]').remove();
}
return $sel;
};
var makeUser = function (proxy, id, value) {
var $user = Input({
id: id,
type: 'text',
placeholder: Messages.poll_userPlaceholder,
disabled: true,
}).on('keyup change', function () {
proxy.table.cols[id] = $user.val() || "";
});
var $edit = $('<span>', {
'class': 'edit',
title: Messages.poll_editUserTitle,
}).click(function () {
if ($edit.hasClass('editable')) { return; }
Cryptpad.confirm(Messages.poll_editUser,
function (yes) {
if (!yes) { return; }
makeUserEditable(id, true);
$edit.addClass('editable');
$edit.text("");
module.activeColumn = id;
});
});
var $remove = $('<span>', {
'class': 'remove',
'title': Messages.poll_removeUserTitle,
}).text('✖').click(function () {
Cryptpad.confirm(Messages.poll_removeUser,
function (yes) {
if (!yes) { return; }
// remove commit button, and anything else...
makeUserEditable(id, false);
removeColumn(proxy, id);
table.removeColumn(id);
});
});
if (readOnly) {
$edit = '';
$remove = '';
}
var $wrapper = $('<div>', {
'class': 'text-cell',
})
.append($edit)
.append($user)
.append($remove);
proxy.table.cols[id] = value || "";
addIfAbsent(proxy.table.colsOrder, id);
table.addColumn($wrapper, Checkbox, id);
return $user;
};
var scrollDown = module.scrollDown = function (px) {
if (module.scrolling) { return; }
module.scrolling = true;
var top = $(window).scrollTop() + px + 'px';
$('html, body').animate({
scrollTop: top,
}, {
duration: 200,
easing: 'swing',
complete: function () {
module.scrolling = false;
}
});
};
var makeOptionEditable = function (id, bool) {
if (readOnly) { return; }
if (bool) {
module.rt.proxy.table.rowsOrder.forEach(function (rowuid) {
$('#' + rowuid)
.attr('disabled', rowuid !== id)
.closest('td')
.find('.edit')
.removeClass('editable');
});
return;
}
$('input[id^="y"]').attr('disabled', true);
};
var makeOption = function (proxy, id, value) {
var $option = Input({
type: 'text',
placeholder: Messages.optionPlaceholder,
id: id,
}).on('keyup change', function () {
proxy.table.rows[id] = $option.val();
}).attr('disabled', true);
var $edit = $('<span>', {
'class': 'edit',
title: Messages.poll_editOptionTitle,
})
.click(function () {
if ($edit.hasClass('editable')) { return; }
Cryptpad.confirm(Messages.poll_editOption,
function (yes) {
if (!yes) { return; }
makeOptionEditable(id, true);
$edit.addClass('editable');
$edit.text("");
module.activeOption = id;
});
});
var $remove = $('<span>', {
'class': 'remove',
'title': Messages.poll_removeOptionTitle,
}).text('✖').click(function () {
var msg = Messages.poll_removeOption;
Cryptpad.confirm(msg, function (yes) {
if (!yes) { return; }
removeRow(proxy, id);
table.removeRow(id);
});
});
if (readOnly) {
$edit = '';
$remove = '';
}
var $wrapper = $('<div>', {
'class': 'text-cell',
})
.append($edit)
.append($option)
.append($remove);
proxy.table.rows[id] = value || "";
addIfAbsent(proxy.table.rowsOrder, id);
var $row = table.addRow($wrapper, Checkbox, id);
if (module.ready) {
scrollDown($row.height());
}
return $option;
};
$('#adduser').click(function () {
if (!module.isEditable) { return; }
var id = coluid();
var msg = Messages.poll_addUser;
Cryptpad.prompt(msg, "", function (name) {
if (!(name && name.trim())) { return; }
makeUser(module.rt.proxy, id, name).val(name);
makeUserEditable(id, true).focus();
});
});
$('#addoption').click(function () {
if (!module.isEditable) { return; }
var id = rowuid();
var msg = Messages.poll_addOption;
Cryptpad.prompt(msg, "", function (option) {
if (option === null || !option) { return; }
makeOption(module.rt.proxy, id, option).val(option).focus();
});
//makeOption(module.rt.proxy, id).focus();
});
Wizard.$getOptions.click(function () {
Cryptpad.confirm(Messages.wizardConfirm, function (yes) {
if (!yes) { return; }
var options = Wizard.computeSlots(function (a, b) {
return a + ' ('+ b + ')';
});
var proxy = module.rt.proxy;
options.forEach(function (text) {
var id = rowuid();
makeOption(proxy, id, text).val(text);
});
Wizard.hide();
});
});
// notifications
var unnotify = function () {
if (!(module.tabNotification &&
typeof(module.tabNotification.cancel) === 'function')) { return; }
module.tabNotification.cancel();
};
var notify = function () {
if (!(Visible.isSupported() && !Visible.currently())) { return; }
unnotify();
module.tabNotification = Notify.tab(1000, 10);
};
var updateTitle = function (newTitle) {
if (newTitle === document.title) { return; }
// Change the title now, and set it back to the old value if there is an error
var oldTitle = document.title;
document.title = newTitle;
Cryptpad.setPadTitle(newTitle, function (err, data) {
if (err) {
console.log("Couldn't set pad title");
console.error(err);
document.title = oldTitle;
return;
}
});
};
// don't make changes until the interface is ready
setEditable(false);
var ready = function (info) {
module.users = info.userList.users;
console.log("Your realtime object is ready");
module.ready = true;
var proxy = module.rt.proxy;
var First = false;
if (proxy.metadata && proxy.metadata.title) {
updateTitle(proxy.metadata.title);
}
// ensure that proxy.info and proxy.table exist
['info', 'table'].forEach(function (k) {
if (typeof(proxy[k]) === 'undefined') {
// you seem to be the first person to have visited this pad...
First = true;
proxy[k] = {};
}
});
// table{cols,rows,cells}
['cols', 'rows', 'cells'].forEach(function (k) {
if (typeof(proxy.table[k]) === 'undefined') { proxy.table[k] = {}; }
});
// table{rowsOrder,colsOrder}
['rows', 'cols'].forEach(function (k) {
var K = k + 'Order';
if (typeof(proxy.table[K]) === 'undefined') {
//console.log("Creating %s", K);
proxy.table[K] = [];
Object.keys(proxy.table[k]).forEach(function (uid) {
addIfAbsent(proxy.table[K], uid);
});
}
});
// HERE TODO make this idempotent so you can call it again
// cols
proxy.table.colsOrder.forEach(function (uid) {
var val = proxy.table.cols[uid];
makeUser(proxy, uid, val).val(val);
});
// rows
proxy.table.rowsOrder.forEach(function (uid) {
var val = proxy.table.rows[uid];
makeOption(proxy, uid, val).val(val);
});
// cells
Object.keys(proxy.table.cells).forEach(function (uid) {
//var p = parseXY(uid);
var box = document.getElementById(uid);
if (!box) {
console.log("Couldn't find an element with uid [%s]", uid);
return;
}
var checked = box.checked = proxy.table.cells[uid] ? true : false;
if (checked) {
$(box).closest('.checkbox-contain').find('.cover').addClass('yes');
}
});
items.forEach(function ($item) {
var id = $item.attr('id');
$item.on('change keyup', function () {
var val = $item.val();
proxy.info[id] = val;
});
if (typeof(proxy.info[id]) !== 'undefined') {
$item.val(proxy.info[id]);
}
});
// listen for visibility changes
if (Visible.isSupported()) {
Visible.onChange(function (yes) {
if (yes) { unnotify(); }
});
}
proxy
.on('change', [], function () {
notify();
})
.on('change', ['info'], function (o, n, p) {
var $target = $('#' + p[1]);
var el = $target[0];
var selects;
var op;
if (el && ['textarea', 'text'].indexOf(el.type) !== -1) {
op = TextPatcher.diff(o, n);
selects = ['selectionStart', 'selectionEnd'].map(function (attr) {
var before = el[attr];
var after = TextPatcher.transformCursor(el[attr], op);
return after;
});
$target.val(n);
if (op) {
el.selectionStart = selects[0];
el.selectionEnd = selects[1];
}
}
console.log("change: (%s, %s, [%s])", o, n, p.join(', '));
})
.on('change', ['table'], function (o, n, p) {
var id = p[p.length -1];
var type = p[1];
if (typeof(o) === 'undefined' &&
['cols', 'rows', 'cells'].indexOf(type) !== -1) {
switch (type) {
case 'cols':
makeUser(proxy, id, n);
break;
case 'rows':
makeOption(proxy, id, n);
break;
case 'cells':
//
break;
default:
console.log("Unhandled table element creation");
break;
}
}
var el = document.getElementById(id);
if (!el) {
console.log("Couldn't find the element you wanted!");
return;
}
switch (p[1]) {
case 'cols':
console.log("[Table.cols change] %s (%s => %s)@[%s]", id, o, n, p.slice(0, -1).join(', '));
el.value = n;
break;
case 'rows':
console.log("[Table.rows change] %s (%s => %s)@[%s]", id, o, n, p.slice(0, -1).join(', '));
el.value = n;
break;
case 'cells':
console.log("[Table.cell change] %s (%s => %s)@[%s]", id, o, n, p.slice(0, -1).join(', '));
var checked = el.checked = proxy.table.cells[id] ? true: false;
var $parent = $(el).closest('.checkbox-contain');
if (!$parent.length) { console.log("couldn't find parent element of checkbox"); return; }
if (checked) {
$parent.find('.cover').addClass('yes');
} else {
$parent.find('.cover').removeClass('yes');
}
break;
default:
console.log("[Table change] (%s => %s)@[%s]", o, n, p.join(', '));
break;
}
})
.on('change', ['metadata'], function (o, n, p) {
var newTitle = proxy.metadata.title;
updateTitle(newTitle);
})
.on('remove', [], function (o, p, root) {
//console.log("remove: (%s, [%s])", o, p.join(', '));
//console.log(p, o, p.length);
switch (p[1]) {
case 'cols':
console.log("[Table.cols removal] [%s]", p[2]);
table.removeColumn(p[2]);
return false;
case 'rows':
console.log("[Table.rows removal] [%s]", p[2]);
table.removeRow(p[2]);
return false;
case 'rowsOrder':
Object.keys(proxy.table.rows)
.forEach(function (rowId) {
if (proxy.table.rowsOrder.indexOf(rowId) === -1) {
proxy.table.rows[rowId] = undefined;
delete proxy.table.rows[rowId];
}
});
break;
case 'colsOrder':
Object.keys(proxy.table.cols)
.forEach(function (colId) {
if (proxy.table.colsOrder.indexOf(colId) === -1) {
proxy.table.cols[colId] = undefined;
delete proxy.table.cols[colId];
}
});
break;
case 'cells':
// cool story bro
break;
default:
console.log("[Table removal] [%s]", p.join(', '));
break;
}
})
.on('disconnect', function (info) {
setEditable(false);
});
var $toolbar = $('#toolbar');
var Button = function (opt) {
return $('<button>', opt);
};
var suggestName = module.suggestName = function () {
var parsed = Cryptpad.parsePadUrl(window.location.href);
var name = Cryptpad.getDefaultName(parsed, []);
if (document.title.slice(0, name.length) === name) {
return $title.val() || document.title;
} else {
return document.title || $title.val() || name;
}
};
/* add a forget button */
var forgetCb = function (err, title) {
if (err) { return; }
document.title = title;
};
var $forgetPad = Cryptpad.createButton('forget', false, {}, forgetCb)
.text(Messages.forgetButton)
.removeAttr('style')
.attr('class', 'action button forget');
$toolbar.append($forgetPad);
/* add a rename button */
var renameCb = function (err, title) {
if (err) { return; }
document.title = title;
var proxy = module.rt.proxy;
if (proxy.metadata) {
proxy.metadata.title = title;
}
else {
proxy.metadata = {title: title};
}
};
var $setTitle = Cryptpad.createButton('rename', true, {suggestName: suggestName}, renameCb)
.text(Messages.renameButton)
.removeAttr('style')
.attr('class', 'action button rename');
$toolbar.append($setTitle);
if (!readOnly) {
$toolbar.append(Button({
id: 'wizard',
'class': 'wizard button action',
title: Messages.wizardTitle,
}).text(Messages.wizardButton).click(function () {
Wizard.show();
if (Wizard.hasBeenDisplayed) { return; }
Cryptpad.log(Messages.wizardLog);
Wizard.hasBeenDisplayed = true;
}));
}
/*
if (!readOnly && module.viewHash) {
/* add a 'links' button
var $links = Cryptpad.createButton('readonly', true, {viewHash: module.viewHash})
.text(Messages.getViewButton)
.removeAttr('style')
.attr('class', 'action button readonly');
$toolbar.append($links);
}
*/
/* Import/Export buttons */
/*
$toolbar.append(Button({
id: 'import',
'class': 'import button action',
title: 'IMPORT', // TODO translate
}).text('IMPORT') // TODO translate
.click(function () {
var proxy = module.rt.proxy;
console.log("pew pew");
if (!module.ready) { return; }
console.log("bang bang");
Cryptpad.importContent('text/plain', function (content, file) {
var parsed;
try {
parsed = JSON.parse(content);
} catch (err) {
Cryptpad.alert("Could not parse imported content");
return;
}
console.log(content);
//module.rt.update(parsed);
})();
}));
$toolbar.append(Button({
id: 'export',
'class': 'export button action',
title: 'EXPORT', // TODO translate
}).text("EXPORT") // TODO translate
.click(function () {
if (!module.ready) { return; }
var proxy = module.rt.proxy;
var title = suggestName();
var text = JSON.stringify(proxy, null, 2);
Cryptpad.prompt(Messages.exportPrompt, title + '.json', function (filename) {
if (filename === null) { return; }
var blob = new Blob([text], {
type: 'application/json',
});
saveAs(blob, filename);
});
}));*/
setEditable(true);
return;
// shortcircuiting before all of this code since it's not quite the
// behaviour we want, and it's a bit of work to make it Do The Right Thing
/*
if (First) {
// assume the first user to the poll wants to be the administrator...
// TODO prompt them with questions to set up their poll...
}
Cryptpad.getPadAttribute('column', function (err, column) {
if (readOnly) { return; }
if (err) {
console.log("unable to retrieve column");
return;
}
module.activeColumn = '';
var promptForName = function () {
var followUp = function (name) {
if (!name) { return; }
var id = module.activeColumn = coluid();
Cryptpad.setPadAttribute('column', id, function (err) {
if (err) { return void console.error("Couldn't remember your column id"); }
makeUser(module.rt.proxy, id, name).focus().val(name);
makeUserEditable(id, true);
});
};
getLastName(function (err, uname) {
if (!uname) {
return void Cryptpad.prompt(Messages.promptName, "", function (name, ev) {
if (!(name || module.isEditable)) { return; }
followUp(name);
});
}
followUp(uname);
});
};
if (column === null) { return void promptForName(); }
// column might be defined, but that column might have been deleted...
if (proxy.table.colsOrder.indexOf(column) === -1) { return void promptForName(); }
});*/
};
var config = {
websocketURL: Cryptpad.getWebsocketURL(),
channel: secret.channel,
data: {},
// our public key
validateKey: secret.keys.validateKey || undefined,
readOnly: readOnly,
crypto: Crypto.createEncryptor(secret.keys),
};
// don't initialize until the store is ready.
Cryptpad.ready(function () {
var rt = window.rt = module.rt = Listmap.create(config);
rt.proxy.on('create', function (info) {
var realtime = module.realtime = info.realtime;
var editHash;
var viewHash = module.viewHash = Cryptpad.getViewHashFromKeys(info.channel, secret.keys);
if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
}
// set the hash
if (!readOnly) { Cryptpad.replaceHash(editHash); }
module.patchText = TextPatcher.create({
realtime: realtime,
logging: true,
});
Cryptpad.getPadTitle(function (err, title) {
title = document.title = title || info.channel.slice(0, 8);
Cryptpad.setPadTitle(title, function (err, data) {
if (err) {
console.log("unable to remember pad");
console.log(err);
return;
}
});
});
}).on('ready', ready)
.on('disconnect', function () {
setEditable(false);
Cryptpad.alert(Messages.common_connectionLost);
});
});
});

@ -1,114 +1,117 @@
<!DOCTYPE html>
<html>
<html class="cp poll">
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title data-localization="poll_title">Zero Knowledge Date Picker</title>
<link rel="icon" type="image/png"
href="/customize/main-favicon.png"
data-main-favicon="/customize/main-favicon.png"
data-alt-favicon="/customize/alt-favicon.png"
id="favicon" />
<link rel="stylesheet" href="/bower_components/components-font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="/customize/main.css" />
<script data-main="main" src="/bower_components/requirejs/require.js"></script>
<script>
require.config({
waitSeconds: 60,
});
</script>
<script> require.config({ waitSeconds: 60, }); </script>
<style>
html, body {
width: 100;
margin-top: 1.25em;
height: auto;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
border: 0px;
}
#main {
margin: auto;
.cryptpad-toolbar h2 {
font: normal normal normal 12px Arial, Helvetica, Tahoma, Verdana, Sans-Serif;
color: #000;
line-height: auto;
}
.clickable {
cursor: pointer;
.realtime {
display: block;
overflow: auto;
max-height: 100%;
max-width: 100%;
}
.realtime input[type="text"] {
height: 1em;
margin: 0px;
}
.text-cell input[type="text"] {
width: 400px;
}
/*input#title, textarea { wiidth: 50px; }*/
input[type="text"][disabled], textarea[disabled] {
background-color: transparent;
font: white;
border: 0px;
}
#adduser, #addoption {
font-weight: bold;
td label {
border: .5px solid black;
}
table#table {
margin: 0px;
}
#tableContainer {
position: relative;
padding: 29px;
padding-right: 79px;
}
#tableContainer button {
height: 2rem;
display: none;
}
#publish {
display: none;
}
#create-user {
position: absolute;
display: inline-block;
/*left: 0px;*/
top: 55px;
width: 50px;
overflow: hidden;
}
#create-option {
width: 50px;
}
#tableScroll {
overflow-x: auto; margin-left: calc(30% - 50px + 29px); max-width: 70%; width: auto; display: inline-block;
}
#description[disabled] {
resize: none;
}
#description {
padding: 5px;
}
#commit {
width: 100%;
}
</style>
</head>
<body>
<div id="main">
<div id="toolbar" class="toolbar-container"></div>
<div id="toolbar" class="buttons">
</div>
<div id="howItWorks">
<h1 id="mainTitle">CryptPoll</h1>
<h2 data-localization="poll_subtitle"></h2>
<p data-localization="poll_p_save"></p>
<p data-localization="poll_p_encryption"></p>
<hr>
<br>
<form class="realtime">
<input type="text" id="title" placeholder="title"><br />
<textarea id="description" placeholder="description"></textarea>
<p id="howToUse" data-localization="poll_p_howtouse"></p>
<!-- Table markup-->
<table id="table">
<!-- Table header -->
<thead>
<tr>
<td>
<div id="adduser" class="clickable" data-localization="poll_addUserButton" data-localization-title="poll_addUserButtonTitle"></div>
</td>
</tr>
</thead>
<!-- Table footer -->
<tfoot>
<tr>
<td>
<div id="addoption" class="clickable" data-localization="poll_addOptionButton" data-localization-title="poll_addOptionButtonTitle"></div>
</td>
</tr>
</tfoot>
<!-- Table body -->
<tbody>
</tbody>
</table>
</form>
<div class="modal" id="wizard-modal">
<button id="close-wizard" class="button action" data-localization="poll_closeWizardButton" data-localization-title="poll_closeWizardButtonTitle"></button>
<div class="center">
<div id="modal-toolbar">
<button id="get-options" class="action button" data-localization="poll_wizardComputeButton"></button>
<button id="clear-table" class="action button" data-localization="poll_wizardClearButton"></button>
</div>
<h2 data-localization="poll_wizardDescription"></h2>
<button id="publish" data-localization-title="poll_publish_button" data-localization="poll_publish_button" style="display: none;">publish poll</button>
<button id="admin" data-localization-title="poll_admin_button" data-localization="poll_admin_button" style="display: none;">admin</button>
<table id="wizard-table">
<thead>
<tr>
<td>
<div id="adddate" class="clickable" data-localization="poll_wizardAddDateButton"></div>
</td>
</tr>
</thead>
<tfoot>
<tr>
<td>
<div id="addtime" class="clickable" data-localization="poll_wizardAddTimeButton"></div>
</td>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
<div class="realtime">
<br />
<textarea rows=5 cols=50 disabled="disabled" id="description"></textarea><br />
<div id="tableContainer">
<div id="tableScroll"></div>
<button data-localization-title="poll_create_user" id="create-user"><span class="fa fa-plus"></span></button>
<button data-localization-title="poll_create_option" id="create-option"><span class="fa fa-plus"></span></button>
<button data-localization-title="poll_commit" id="commit"><span class="fa fa-check"></span></button>
</div>
</div>

File diff suppressed because it is too large Load Diff

@ -1,117 +0,0 @@
<!DOCTYPE html>
<html class="cp poll">
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title data-localization="poll_title">Zero Knowledge Date Picker</title>
<link rel="stylesheet" href="/bower_components/components-font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="/customize/main.css" />
<script data-main="main" src="/bower_components/requirejs/require.js"></script>
<script> require.config({ waitSeconds: 60, }); </script>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
border: 0px;
}
.cryptpad-toolbar h2 {
font: normal normal normal 12px Arial, Helvetica, Tahoma, Verdana, Sans-Serif;
color: #000;
line-height: auto;
}
.realtime {
display: block;
overflow: auto;
max-height: 100%;
max-width: 100%;
}
.realtime input[type="text"] {
height: 1em;
margin: 0px;
}
.text-cell input[type="text"] {
width: 400px;
}
/*input#title, textarea { wiidth: 50px; }*/
input[type="text"][disabled], textarea[disabled] {
background-color: transparent;
font: white;
border: 0px;
}
td label {
border: .5px solid black;
}
table#table {
margin: 0px;
}
#tableContainer {
position: relative;
padding: 29px;
padding-right: 79px;
}
#tableContainer button {
height: 2rem;
display: none;
}
#publish {
display: none;
}
#create-user {
position: absolute;
display: inline-block;
/*left: 0px;*/
top: 55px;
width: 50px;
overflow: hidden;
}
#create-option {
width: 50px;
}
#tableScroll {
overflow-x: auto; margin-left: calc(30% - 50px + 29px); max-width: 70%; width: auto; display: inline-block;
}
#description[disabled] {
resize: none;
}
#description {
padding: 5px;
}
#commit {
width: 100%;
}
</style>
</head>
<body>
<div id="toolbar" class="toolbar-container"></div>
<div id="howItWorks">
<h1 id="mainTitle">CryptPoll</h1>
<h2 data-localization="poll_subtitle"></h2>
<p data-localization="poll_p_save"></p>
<p data-localization="poll_p_encryption"></p>
</div>
<button id="publish" data-localization-title="poll_publish_button" data-localization="poll_publish_button" style="display: none;">publish poll</button>
<button id="admin" data-localization-title="poll_admin_button" data-localization="poll_admin_button" style="display: none;">admin</button>
<div class="realtime">
<br />
<textarea rows=5 cols=50 disabled="disabled" id="description"></textarea><br />
<div id="tableContainer">
<div id="tableScroll"></div>
<button data-localization-title="poll_create_user" id="create-user"><span class="fa fa-plus"></span></button>
<button data-localization-title="poll_create_option" id="create-option"><span class="fa fa-plus"></span></button>
<button data-localization-title="poll_commit" id="commit"><span class="fa fa-check"></span></button>
</div>
</div>

@ -1,726 +0,0 @@
define([
'/api/config?cb=' + Math.random().toString(16).substring(2),
'/customize/messages.js?app=poll',
'/bower_components/textpatcher/TextPatcher.js',
'/bower_components/chainpad-listmap/chainpad-listmap.js',
'/bower_components/chainpad-crypto/crypto.js',
'/common/cryptpad-common.js',
'/bower_components/hyperjson/hyperjson.js',
'/poll/test/render.js',
'/common/toolbar.js',
'/common/visible.js',
'/common/notify.js',
'/bower_components/file-saver/FileSaver.min.js',
'/bower_components/jquery/dist/jquery.min.js',
'/customize/pad.js'
], function (Config, Messages, TextPatcher, Listmap, Crypto, Cryptpad, Hyperjson, Render, Toolbar) {
var $ = window.jQuery;
var HIDE_INTRODUCTION_TEXT = "hide_poll_text";
var defaultName;
var secret = Cryptpad.getSecrets();
var readOnly = secret.keys && !secret.keys.editKeyStr;
Cryptpad.addLoadingScreen();
var onConnectError = function (info) {
Cryptpad.errorLoadingScreen(Messages.websocketError);
};
var APP = window.APP = {
Toolbar: Toolbar,
Hyperjson: Hyperjson,
Render: Render,
$bar: $('#toolbar'),
editable: {
row: [],
col: []
}
};
var sortColumns = function (order, firstcol) {
var colsOrder = order.slice();
colsOrder.sort(function (a, b) {
return (a === firstcol) ? -1 :
((b === firstcol) ? 1 : 0);
});
return colsOrder;
};
var isOwnColumnCommitted = function () {
return APP.proxy && APP.proxy.table.colsOrder.indexOf(APP.userid) !== -1;
};
var mergeUncommitted = function (proxy, uncommitted, commit) {
var newObj;
if (commit) {
newObj = proxy;
} else {
newObj = $.extend(true, {}, proxy);
}
// We have uncommitted data only if the user's column is not in the proxy
// If it is already is the proxy, nothing to merge
if (isOwnColumnCommitted()) {
return newObj;
}
// Merge uncommitted into the proxy
uncommitted.table.colsOrder.forEach(function (x) {
if (newObj.table.colsOrder.indexOf(x) !== -1) { return; }
newObj.table.colsOrder.push(x);
});
for (var k in uncommitted.table.cols) {
if (!newObj.table.cols[k]) {
newObj.table.cols[k] = uncommitted.table.cols[k];
}
}
for (var l in uncommitted.table.cells) {
if (!newObj.table.cells[l]) {
newObj.table.cells[l] = uncommitted.table.cells[l];
}
}
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 id = APP.userid;
// Enable the checkboxes for the user's column (committed or not)
$('input[disabled="disabled"][data-rt-id^="' + id + '"]').removeAttr('disabled');
$('input[type="checkbox"][data-rt-id^="' + id + '"]').addClass('enabled');
$('[data-rt-id="' + id + '"] ~ .edit').css('visibility', 'hidden');
$('.lock[data-rt-id="' + id + '"]').html('🔓');
if (isOwnColumnCommitted()) { return; }
$('[data-rt-id^="' + id + '"]').closest('td').addClass("uncommitted");
$('td.uncommitted .remove, td.uncommitted .edit').css('visibility', 'hidden');
$('td.uncommitted .cover').addClass("uncommitted");
$('.uncommitted input[type="text"]').attr("placeholder", Messages.poll_userPlaceholder);
};
var unlockElements = function () {
APP.editable.row.forEach(function (id) {
$('input[type="text"][disabled="disabled"][data-rt-id="' + id + '"]').removeAttr('disabled');
$('span.edit[data-rt-id="' + id + '"]').css('visibility', 'hidden');
});
APP.editable.col.forEach(function (id) {
$('input[disabled="disabled"][data-rt-id^="' + id + '"]').removeAttr('disabled');
$('input[type="checkbox"][data-rt-id^="' + id + '"]').addClass('enabled');
$('span.edit[data-rt-id="' + id + '"]').css('visibility', 'hidden');
$('.lock[data-rt-id="' + id + '"]').html('🔓');
});
};
var updateTableButtons = function () {
if (!isOwnColumnCommitted()) {
$('#commit').show();
}
var $createOption = APP.$table.find('tfoot tr td:first-child');
var $commitCell = APP.$table.find('tfoot tr td:nth-child(2)');
$createOption.append(APP.$createRow);
$commitCell.append(APP.$commit);
$('#create-user, #create-option').css('display', 'inline-block');
if (!APP.proxy || !APP.proxy.table.rowsOrder || APP.proxy.table.rowsOrder.length === 0) { $('#create-user').hide(); }
var width = $('#table').outerWidth();
if (width) {
//$('#create-user').css('left', width + 30 + 'px');
}
};
var setTablePublished = function (bool) {
if (bool) {
if (APP.$publish) { APP.$publish.hide(); }
if (APP.$admin) { APP.$admin.show(); }
$('#create-option').hide();
$('.remove[data-rt-id^="y"], .edit[data-rt-id^="y"]').hide();
} else {
if (APP.$publish) { APP.$publish.show(); }
if (APP.$admin) { APP.$admin.hide(); }
$('#create-option').show();
$('.remove[data-rt-id^="y"], .edit[data-rt-id^="y"]').show();
}
};
var updateDisplayedTable = function () {
styleUncommittedColumn();
unlockElements();
updateTableButtons();
setTablePublished(APP.proxy.published);
};
var unlockColumn = function (id, cb) {
if (APP.editable.col.indexOf(id) === -1) {
APP.editable.col.push(id);
}
if (typeof(cb) === "function") {
cb();
}
};
var unlockRow = function (id, cb) {
if (APP.editable.row.indexOf(id) === -1) {
APP.editable.row.push(id);
}
if (typeof(cb) === "function") {
cb();
}
};
/* Any time the realtime object changes, call this function */
var change = function (o, n, path) {
if (path && path.join) {
console.log("Change from [%s] to [%s] at [%s]",
o, n, path.join(', '));
}
var table = APP.$table[0];
var displayedObj = mergeUncommitted(APP.proxy, APP.uncommitted);
var colsOrder = sortColumns(displayedObj.table.colsOrder, APP.userid);
var conf = {
cols: colsOrder,
readOnly: readOnly
};
//Render.updateTable(table, displayedObj, conf);
/* FIXME browser autocomplete fills in new fields sometimes
calling updateTable twice removes the autofilled in values
setting autocomplete="off" is not reliable
https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion
*/
window.setTimeout(function () {
var displayedObj2 = mergeUncommitted(APP.proxy, APP.uncommitted);
Render.updateTable(table, displayedObj2, conf);
updateDisplayedTable();
});
};
var getRealtimeId = function (input) {
return input.getAttribute && input.getAttribute('data-rt-id');
};
/* Called whenever an event is fired on an input element */
var handleInput = function (input) {
var type = input.type.toLowerCase();
var id = getRealtimeId(input);
console.log(input);
var object = APP.proxy;
var x = Render.getCoordinates(id)[0];
if (type !== "row" && x === APP.userid && APP.proxy.table.colsOrder.indexOf(x) === -1) {
object = APP.uncommitted;
}
switch (type) {
case 'text':
console.log("text[rt-id='%s'] [%s]", id, input.value);
if (!input.value) { return void console.log("Hit enter?"); }
Render.setValue(object, id, input.value);
change();
break;
case 'checkbox':
console.log("checkbox[tr-id='%s'] %s", id, input.checked);
if (APP.editable.col.indexOf(x) >= 0 || x === APP.userid) {
Render.setValue(object, id, input.checked);
change();
} else {
console.log('checkbox locked');
}
break;
default:
console.log("Input[type='%s']", type);
break;
}
};
/* Called whenever an event is fired on a span */
var handleSpan = function (span) {
var id = span.getAttribute('data-rt-id');
var type = Render.typeofId(id);
var isRemove = span.className && span.className.split(' ').indexOf('remove') !== -1;
var isEdit = span.className && span.className.split(' ').indexOf('edit') !== -1;
if (type === 'row') {
if (isRemove) {
Cryptpad.confirm(Messages.poll_removeOption, function (res) {
if (!res) { return; }
Render.removeRow(APP.proxy, id, function () {
change();
});
});
} else if (isEdit) {
unlockRow(id, function () {
change();
});
}
} else if (type === 'col') {
if (isRemove) {
Cryptpad.confirm(Messages.poll_removeUser, function (res) {
if (!res) { return; }
Render.removeColumn(APP.proxy, id, function () {
change();
});
});
} else if (isEdit) {
unlockColumn(id, function () {
change();
});
}
} else if (type === 'cell') {
change();
} else {
console.log("UNHANDLED");
}
};
var hideInputs = function (e) {
if ($(e.target).is('[type="text"]')) {
return;
}
$('.lock[data-rt-id!="' + APP.userid + '"]').html('🔒 ');
var $cells = APP.$table.find('thead td:not(.uncommitted), tbody td');
$cells.find('[type="text"][data-rt-id!="' + APP.userid + '"]').attr('disabled', true);
$('.edit[data-rt-id!="' + APP.userid + '"]').css('visibility', 'visible');
APP.editable.col = [APP.userid];
APP.editable.row = [];
};
$(window).click(hideInputs);
var handleClick = function (e, isKeyup) {
e.stopPropagation();
if (!APP.ready) { return; }
var target = e && e.target;
if (isKeyup) {
console.log("Keyup!");
}
if (!target) { return void console.log("NO TARGET"); }
var nodeName = target && target.nodeName;
if (!$(target).parents('#table tbody').length || $(target).hasClass('edit')) {
hideInputs(e);
}
switch (nodeName) {
case 'INPUT':
handleInput(target);
break;
case 'SPAN':
//case 'LABEL':
handleSpan(target);
break;
case undefined:
//console.error(new Error("C'est pas possible!"));
break;
default:
console.log(target, nodeName);
break;
}
};
/*
Make sure that the realtime data structure has all the required fields
*/
var prepareProxy = function (proxy, schema) {
if (proxy && proxy.version === 1) { return; }
console.log("Configuring proxy schema...");
proxy.info = schema.info;
proxy.table = schema.table;
proxy.version = 1;
};
/*
*/
var publish = APP.publish = function (bool) {
if (!APP.ready) { return; }
if (APP.proxy.published !== bool) {
APP.proxy.published = bool;
}
setTablePublished(bool);
['textarea'].forEach(function (sel) {
$(sel).attr('disabled', bool);
});
};
var userData = APP.userData = {}; // List of pretty names for all users (mapped with their ID)
var userList; // List of users still connected to the channel (server IDs)
var addToUserData = function(data) {
var users = userList ? userList.users : undefined;
//var userData = APP.proxy.info.userData;
for (var attrname in data) { userData[attrname] = data[attrname]; }
if (users && users.length) {
for (var userKey in userData) {
if (users.indexOf(userKey) === -1) { delete userData[userKey]; }
}
}
if(userList && typeof userList.onChange === "function") {
userList.onChange(userData);
}
APP.proxy.info.userData = userData;
};
//var myData = {};
var getLastName = function (cb) {
Cryptpad.getAttribute('username', function (err, userName) {
cb(err, userName || '');
});
};
var setName = APP.setName = function (newName) {
if (typeof(newName) !== 'string') { return; }
var myUserNameTemp = Cryptpad.fixHTML(newName.trim());
if(myUserNameTemp.length > 32) {
myUserNameTemp = myUserNameTemp.substr(0, 32);
}
var myUserName = myUserNameTemp;
var myID = APP.myID;
var myData = {};
myData[myID] = {
name: myUserName
};
addToUserData(myData);
Cryptpad.setAttribute('username', newName, function (err, data) {
if (err) {
console.error("Couldn't set username");
return;
}
APP.userName.lastName = myUserName;
//change();
});
};
var updateTitle = function (newTitle) {
if (newTitle === document.title) { return; }
// Change the title now, and set it back to the old value if there is an error
var oldTitle = document.title;
document.title = newTitle;
Cryptpad.renamePad(newTitle, function (err, data) {
if (err) {
console.log("Couldn't set pad title");
console.error(err);
document.title = oldTitle;
return;
}
document.title = data;
APP.$bar.find('.' + Toolbar.constants.title).find('span.title').text(data);
APP.$bar.find('.' + Toolbar.constants.title).find('input').val(data);
});
};
var updateDefaultTitle = function (defaultTitle) {
defaultName = defaultTitle;
APP.$bar.find('.' + Toolbar.constants.title).find('input').attr("placeholder", defaultName);
};
var renameCb = function (err, title) {
if (err) { return; }
document.title = title;
APP.proxy.info.title = title;
};
var suggestName = function (fallback) {
return document.title || defaultName || "";
};
var copyObject = function (obj) {
return JSON.parse(JSON.stringify(obj));
};
// special UI elements
//var $title = $('#title').attr('placeholder', Messages.poll_titleHint || 'title'); TODO
var $description = $('#description').attr('placeholder', Messages.poll_descriptionHint || 'description');
var ready = function (info, userid, readOnly) {
console.log("READY");
console.log('userid: %s', userid);
var proxy = APP.proxy;
var uncommitted = APP.uncommitted = {};
prepareProxy(proxy, copyObject(Render.Example));
prepareProxy(uncommitted, copyObject(Render.Example));
if (!readOnly && proxy.table.colsOrder.indexOf(userid) === -1 &&
uncommitted.table.colsOrder.indexOf(userid) === -1) {
uncommitted.table.colsOrder.unshift(userid);
}
var displayedObj = mergeUncommitted(proxy, uncommitted, false);
var colsOrder = sortColumns(displayedObj.table.colsOrder, userid);
var $table = APP.$table = $(Render.asHTML(displayedObj, null, colsOrder, readOnly));
var $createRow = APP.$createRow = $('#create-option').click(function () {
console.error("BUTTON CLICKED! LOL");
Render.createRow(proxy, function () {
change();
});
});
var $createCol = APP.$createCol = $('#create-user').click(function () {
Render.createColumn(proxy, function () {
change();
});
});
// Commit button
var $commit = APP.$commit = $('#commit').click(function () {
var uncommittedCopy = JSON.parse(JSON.stringify(APP.uncommitted));
APP.uncommitted = {};
prepareProxy(APP.uncommitted, copyObject(Render.Example));
mergeUncommitted(proxy, uncommittedCopy, true);
APP.$commit.hide();
change();
});
// #publish button is removed in readonly
var $publish = APP.$publish = $('#publish')
.click(function () {
publish(true);
});
// #publish button is removed in readonly
var $admin = APP.$admin = $('#admin')
.click(function () {
publish(false);
});
// Title
if (APP.proxy.info.defaultTitle) {
updateDefaultTitle(APP.proxy.info.defaultTitle);
} else {
APP.proxy.info.defaultTitle = defaultName;
}
updateTitle(APP.proxy.info.title || defaultName);
// Description
var resize = function () {
var lineCount = $description.val().split('\n').length;
$description.css('height', lineCount + 'rem');
};
$description.on('change keyup', function () {
var val = $description.val();
proxy.info.description = val;
resize();
});
resize();
if (typeof(proxy.info.description) !== 'undefined') {
$description.val(proxy.info.description);
}
$('#tableScroll').prepend($table);
updateDisplayedTable();
$table
.click(handleClick)
.on('keyup', function (e) { handleClick(e, true); });
proxy
.on('change', ['info'], function (o, n, p) {
if (p[1] === 'title') {
updateTitle(n);
} else if (p[1] === "userData") {
addToUserData(APP.proxy.info.userData);
} else if (p[1] === 'description') {
var op = TextPatcher.diff(o, n);
var el = $description[0];
var selects = ['selectionStart', 'selectionEnd'].map(function (attr) {
var before = el[attr];
var after = TextPatcher.transformCursor(el[attr], op);
return after;
});
$description.val(n);
if (op) {
el.selectionStart = selects[0];
el.selectionEnd = selects[1];
}
}
console.log("change: (%s, %s, [%s])", o, n, p.join(', '));
})
.on('change', ['table'], change)
.on('remove', [], change);
addToUserData(APP.proxy.info.userData);
getLastName(function (err, lastName) {
APP.ready = true;
if (!proxy.published) {
publish(false);
} else {
publish(true);
}
Cryptpad.removeLoadingScreen();
// Update the toolbar list:
// Add the current user in the metadata if he has edit rights
if (readOnly) { return; }
if (typeof(lastName) === 'string' && lastName.length) {
setName(lastName);
} else {
var myData = {};
myData[info.myId] = {
name: ""
};
addToUserData(myData);
APP.$userNameButton.click();
}
});
};
var create = function (info) {
var realtime = APP.realtime = info.realtime;
var myID = APP.myID = info.myID;
var editHash;
var viewHash = Cryptpad.getViewHashFromKeys(info.channel, secret.keys);
if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
}
APP.patchText = TextPatcher.create({
realtime: realtime,
logging: true,
});
userList = APP.userList = info.userList;
var config = {
userData: userData,
readOnly: readOnly,
title: {
onRename: renameCb,
defaultName: defaultName,
suggestName: suggestName
},
ifrw: window,
common: Cryptpad
};
var toolbar = info.realtime.toolbar = Toolbar.create(APP.$bar, info.myID, info.realtime, info.getLag, userList, config);
var $bar = APP.$bar;
var $rightside = $bar.find('.' + Toolbar.constants.rightside);
var $userBlock = $bar.find('.' + Toolbar.constants.username);
var $editShare = $bar.find('.' + Toolbar.constants.editShare);
var $viewShare = $bar.find('.' + Toolbar.constants.viewShare);
// Store the object sent for the "change username" button so that we can update the field value correctly
var userNameButtonObject = APP.userName = {};
/* add a "change username" button */
getLastName(function (err, lastName) {
userNameButtonObject.lastName = lastName;
var $username = APP.$userNameButton = Cryptpad.createButton('username', false, userNameButtonObject, setName).hide();
$userBlock.append($username);
});
/* add a forget button */
var forgetCb = function (err, title) {
if (err) { return; }
document.title = title;
};
var $forgetPad = Cryptpad.createButton('forget', true, {}, forgetCb);
$rightside.append($forgetPad);
if (!readOnly) {
$editShare.append(Cryptpad.createButton('editshare', false, {editHash: editHash}));
}
if (viewHash) {
/* add a 'links' button */
$viewShare.append(Cryptpad.createButton('viewshare', false, {viewHash: viewHash}));
if (!readOnly) {
$viewShare.append(Cryptpad.createButton('viewopen', false, {viewHash: viewHash}));
}
}
// set the hash
if (!readOnly) { Cryptpad.replaceHash(editHash); }
Cryptpad.getPadTitle(function (err, title) {
if (err) {
console.error(err);
console.log("Couldn't get pad title");
return;
}
updateTitle(title || defaultName);
});
};
var disconnect = function (info) {
//setEditable(false); // TODO
Cryptpad.alert(Messages.common_connectionLost);
};
var config = {
websocketURL: Cryptpad.getWebsocketURL(),
channel: secret.channel,
readOnly: readOnly,
data: {},
// our public key
validateKey: secret.keys.validateKey || undefined,
//readOnly: readOnly,
crypto: Crypto.createEncryptor(secret.keys),
};
// don't initialize until the store is ready.
Cryptpad.ready(function () {
if (readOnly) {
$('#commit, #create-user, #create-option, #publish, #admin').remove();
}
var parsedHash = Cryptpad.parsePadUrl(window.location.href);
defaultName = Cryptpad.getDefaultName(parsedHash);
var rt = window.rt = APP.rt = Listmap.create(config);
APP.proxy = rt.proxy;
rt.proxy
.on('create', create)
.on('ready', function (info) {
Cryptpad.getPadAttribute('userid', function (e, userid) {
if (e) { console.error(e); }
if (!userid) { userid = Render.coluid(); }
APP.userid = userid;
Cryptpad.setPadAttribute('userid', userid, function (e) {
ready(info, userid, readOnly);
});
});
})
.on('disconnect', disconnect);
Cryptpad.getAttribute(HIDE_INTRODUCTION_TEXT, function (e, value) {
if (e) { console.error(e); }
if (value === null) {
Cryptpad.setAttribute(HIDE_INTRODUCTION_TEXT, "1", function (e) {
if (e) { console.error(e); }
});
} else if (value === "1") {
$('#howItWorks').hide();
}
});
});
Cryptpad.onError(function (info) {
if (info) {
onConnectError();
}
});
});
Loading…
Cancel
Save