Sandboxed iframe for the whiteboard app

pull/1/head
yflory 7 years ago
parent a78b597ebb
commit 732585ea7b

@ -575,64 +575,63 @@ define([
Pages['/whiteboard/'] = Pages['/whiteboard/index.html'] = function () { Pages['/whiteboard/'] = Pages['/whiteboard/index.html'] = function () {
return [ return [
appToolbar(), h('div#cp-toolbar.cp-toolbar-container'),
h('div#canvas-area', h('canvas#canvas', { h('div#cp-app-whiteboard-canvas-area', h('canvas#cp-app-whiteboard-canvas', {
width: 600, width: 600,
height: 600 height: 600
})), })),
h('div#controls', { h('div#cp-app-whiteboard-controls', {
style: { style: {
display: 'block', display: 'block',
} }
}, [ }, [
h('button#clear.btn.btn-danger', Msg.canvas_clear), ' ', h('button#cp-app-whiteboard-clear.btn.btn-danger', Msg.canvas_clear), ' ',
h('button#toggleDraw.btn.btn-secondary', Msg.canvas_disable), h('button#cp-app-whiteboard-toggledraw.btn.btn-secondary', Msg.canvas_disable),
h('button#delete.btn.btn-secondary', { h('button#cp-app-whiteboard-delete.btn.btn-secondary', {
style: { style: {
display: 'none', display: 'none',
} }
}, Msg.canvas_delete), }, Msg.canvas_delete),
h('div.range-group', [ h('div.cp-app-whiteboard-range-group', [
h('label', { h('label', {
'for': 'width' 'for': 'cp-app-whiteboard-width'
}, Msg.canvas_width), }, Msg.canvas_width),
h('input#width', { h('input#cp-app-whiteboard-width', {
type: 'range', type: 'range',
value: "5", value: "5",
min: "1", min: "1",
max: "100" max: "100"
}), }),
h('span#width-val', '5px') h('span#cp-app-whiteboard-width-val', '5px')
]), ]),
h('div.range-group', [ h('div.cp-app-whiteboard-range-group', [
h('label', { h('label', {
'for': 'opacity', 'for': 'cp-app-whiteboard-opacity',
}, Msg.canvas_opacity), }, Msg.canvas_opacity),
h('input#opacity', { h('input#cp-app-whiteboard-opacity', {
type: 'range', type: 'range',
value: "1", value: "1",
min: "0.1", min: "0.1",
max: "1", max: "1",
step: "0.1" step: "0.1"
}), }),
h('span#opacity-val', '100%') h('span#cp-app-whiteboard-opacity-val', '100%')
]), ]),
h('span.selected', [ h('span.cp-app-whiteboard-selected', [
h('img', { h('img', {
title: Msg.canvas_currentBrush title: Msg.canvas_currentBrush
}) })
]) ])
]), ]),
setHTML(h('div#colors'), ' '), setHTML(h('div#cp-app-whiteboard-colors'), ' '),
loadingScreen(), h('div#cp-app-whiteboard-cursors', {
h('div#cursors', {
style: { style: {
display: 'none', display: 'none',
background: 'white', background: 'white',
'text-align': 'center', 'text-align': 'center',
} }
}), }),
h('div#pickers'), h('div#cp-app-whiteboard-pickers'),
]; ];
}; };

@ -27,4 +27,5 @@ body.cp-app-code { @import "../../../code/app-code.less"; }
body.cp-app-slide { @import "../../../slide/app-slide.less"; } body.cp-app-slide { @import "../../../slide/app-slide.less"; }
body.cp-app-file { @import "../../../file/app-file.less"; } body.cp-app-file { @import "../../../file/app-file.less"; }
body.cp-app-filepicker { @import "../../../filepicker/app-filepicker.less"; } body.cp-app-filepicker { @import "../../../filepicker/app-filepicker.less"; }
body.cp-app-whiteboard { @import "../../../whiteboard/app-whiteboard.less"; }

@ -118,6 +118,7 @@ define([
} }
console.log('CACHE MISS ' + url); console.log('CACHE MISS ' + url);
((/\.less([\?\#].*)?$/.test(url)) ? loadLess : loadCSS)(url, function (err, css) { ((/\.less([\?\#].*)?$/.test(url)) ? loadLess : loadCSS)(url, function (err, css) {
if (err) { console.error(err); }
var output = fixAllURLs(css, url); var output = fixAllURLs(css, url);
cachePut(url, output); cachePut(url, output);
inject(output, url); inject(output, url);

@ -182,11 +182,18 @@ define([
break; break;
case 'more': case 'more':
button = $('<button>', { button = $('<button>', {
title: Messages.moreActions || 'TODO', title: Messages.moreActions,
'class': "cp-toolbar-drawer-button fa fa-ellipsis-h", 'class': "cp-toolbar-drawer-button fa fa-ellipsis-h",
style: 'font:'+size+' FontAwesome' style: 'font:'+size+' FontAwesome'
}); });
break; break;
case 'savetodrive':
button = $('<button>', {
'class': 'fa fa-cloud-upload',
title: Messages.canvas_saveToDrive,
})
.click(common.prepareFeedback(type));
break;
default: default:
button = $('<button>', { button = $('<button>', {
'class': "fa fa-question", 'class': "fa fa-question",

@ -0,0 +1,52 @@
define(function () {
var padZero = function (str, len) {
len = len || 2;
var zeros = new Array(len).join('0');
return (zeros + str).slice(-len);
};
var invertColor = function (hex) {
if (hex.indexOf('#') === 0) {
hex = hex.slice(1);
}
// convert 3-digit hex to 6-digits.
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
if (hex.length !== 6) {
console.error(hex);
throw new Error('Invalid HEX color.');
}
// invert color components
var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16),
g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16),
b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16);
// pad each with zeros and return
return '#' + padZero(r) + padZero(g) + padZero(b);
};
var rgb2hex = function (rgb) {
if (rgb.indexOf('#') === 0) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
var hex = function (x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
};
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
};
var hex2rgba = function (hex, opacity) {
if (hex.indexOf('#') === 0) {
hex = hex.slice(1);
}
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
if (!opacity) { opacity = 1; }
var r = parseInt(hex.slice(0,2), 16);
var g = parseInt(hex.slice(2,4), 16);
var b = parseInt(hex.slice(4,6), 16);
return 'rgba('+r+', '+g+', '+b+', '+opacity+')';
};
return {
invert: invertColor,
rgb2hex: rgb2hex,
hex2rgba: hex2rgba
};
});

@ -0,0 +1,9 @@
<!DOCTYPE html>
<html class="cp">
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<script async data-bootload="/customize/template.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
</head>
<body>

@ -0,0 +1,511 @@
define([
'jquery',
'/api/config',
'/bower_components/chainpad-netflux/chainpad-netflux.js',
'/bower_components/chainpad-crypto/crypto.js',
'/common/toolbar2.js',
'/bower_components/textpatcher/TextPatcher.amd.js',
'json.sortify',
'/bower_components/chainpad-json-validator/json-ot.js',
'/common/cryptpad-common.js',
'/common/cryptget.js',
'/whiteboard/colors.js',
'/customize/application_config.js',
'/common/common-thumbnail.js',
'/bower_components/secure-fabric.js/dist/fabric.min.js',
'/bower_components/file-saver/FileSaver.min.js',
'less!/bower_components/components-font-awesome/css/font-awesome.min.css',
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css',
'less!/customize/src/less/cryptpad.less',
'less!/whiteboard/whiteboard.less',
'less!/customize/src/less/toolbar.less',
], function ($, Config, Realtime, Crypto, Toolbar, TextPatcher, JSONSortify, JsonOT, Cryptpad, Cryptget, Colors, AppConfig, Thumb) {
var saveAs = window.saveAs;
var Messages = Cryptpad.Messages;
var module = window.APP = { $:$ };
var Fabric = module.Fabric = window.fabric;
$(function () {
Cryptpad.addLoadingScreen();
var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError);
};
var toolbar;
var secret = Cryptpad.getSecrets();
var readOnly = secret.keys && !secret.keys.editKeyStr;
if (!secret.keys) {
secret.keys = secret.key;
}
var andThen = function () {
/* Initialize Fabric */
var canvas = module.canvas = new Fabric.Canvas('canvas');
var $canvas = $('canvas');
var $controls = $('#controls');
var $canvasContainer = $('canvas').parents('.canvas-container');
var $pickers = $('#pickers');
var $colors = $('#colors');
var $cursors = $('#cursors');
var $deleteButton = $('#delete');
var brush = {
color: '#000000',
opacity: 1
};
var $toggle = $('#toggleDraw');
var $width = $('#width');
var $widthLabel = $('label[for="width"]');
var $opacity = $('#opacity');
var $opacityLabel = $('label[for="opacity"]');
window.canvas = canvas;
var createCursor = function () {
var w = canvas.freeDrawingBrush.width;
var c = canvas.freeDrawingBrush.color;
var size = w > 30 ? w+2 : w+32;
$cursors.html('<canvas width="'+size+'" height="'+size+'"></canvas>');
var $ccanvas = $cursors.find('canvas');
var ccanvas = $ccanvas[0];
var ctx = ccanvas.getContext('2d');
var centerX = size / 2;
var centerY = size / 2;
var radius = w/2;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = c;
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = brush.color;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(size/2, 0); ctx.lineTo(size/2, 10);
ctx.moveTo(size/2, size); ctx.lineTo(size/2, size-10);
ctx.moveTo(0, size/2); ctx.lineTo(10, size/2);
ctx.moveTo(size, size/2); ctx.lineTo(size-10, size/2);
ctx.strokeStyle = '#000000';
ctx.stroke();
var img = ccanvas.toDataURL("image/png");
$controls.find('.selected > img').attr('src', img);
canvas.freeDrawingCursor = 'url('+img+') '+size/2+' '+size/2+', crosshair';
};
var updateBrushWidth = function () {
var val = $width.val();
canvas.freeDrawingBrush.width = Number(val);
$widthLabel.text(Cryptpad.Messages._getKey("canvas_widthLabel", [val]));
$('#width-val').text(val + 'px');
createCursor();
};
updateBrushWidth();
$width.on('change', updateBrushWidth);
var updateBrushOpacity = function () {
var val = $opacity.val();
brush.opacity = Number(val);
canvas.freeDrawingBrush.color = Colors.hex2rgba(brush.color, brush.opacity);
$opacityLabel.text(Cryptpad.Messages._getKey("canvas_opacityLabel", [val]));
$('#opacity-val').text((Number(val) * 100) + '%');
createCursor();
};
updateBrushOpacity();
$opacity.on('change', updateBrushOpacity);
var pickColor = function (current, cb) {
var $picker = $('<input>', {
type: 'color',
value: '#FFFFFF',
})
// TODO confirm that this is safe to remove
//.css({ visibility: 'hidden' })
.on('change', function () {
var color = this.value;
cb(color);
}).appendTo($pickers);
setTimeout(function () {
$picker.val(current);
$picker.click();
});
};
var setColor = function (c) {
c = Colors.rgb2hex(c);
brush.color = c;
canvas.freeDrawingBrush.color = Colors.hex2rgba(brush.color, brush.opacity);
module.$color.css({
'color': c,
});
createCursor();
};
var palette = AppConfig.whiteboardPalette || [
'red', 'blue', 'green', 'white', 'black', 'purple',
'gray', 'beige', 'brown', 'cyan', 'darkcyan', 'gold', 'yellow', 'pink'
];
$('.palette-color').on('click', function () {
var color = $(this).css('background-color');
setColor(color);
});
module.draw = true;
var toggleDrawMode = function () {
module.draw = !module.draw;
canvas.isDrawingMode = module.draw;
$toggle.text(module.draw ? Messages.canvas_disable : Messages.canvas_enable);
if (module.draw) { $deleteButton.hide(); }
else { $deleteButton.show(); }
};
$toggle.click(toggleDrawMode);
var deleteSelection = function () {
if (canvas.getActiveObject()) {
canvas.getActiveObject().remove();
}
if (canvas.getActiveGroup()) {
canvas.getActiveGroup()._objects.forEach(function (el) {
el.remove();
});
canvas.discardActiveGroup();
}
canvas.renderAll();
module.onLocal();
};
$deleteButton.click(deleteSelection);
$(window).on('keyup', function (e) {
if (e.which === 46) { deleteSelection (); }
});
var setEditable = function (bool) {
if (readOnly && bool) { return; }
if (bool) { $controls.css('display', 'flex'); }
else { $controls.hide(); }
canvas.isDrawingMode = bool ? module.draw : false;
if (!bool) {
canvas.deactivateAll();
canvas.renderAll();
}
canvas.forEachObject(function (object) {
object.selectable = bool;
});
$canvasContainer.find('canvas').css('border-color', bool? 'black': 'red');
};
var saveImage = module.saveImage = function () {
var defaultName = "pretty-picture.png";
Cryptpad.prompt(Messages.exportPrompt, defaultName, function (filename) {
if (!(typeof(filename) === 'string' && filename)) { return; }
$canvas[0].toBlob(function (blob) {
saveAs(blob, filename);
});
});
};
module.FM = Cryptpad.createFileManager({});
module.upload = function (title) {
var canvas = $canvas[0];
var finish = function (thumb) {
canvas.toBlob(function (blob) {
blob.name = title;
module.FM.handleFile(blob, void 0, thumb);
});
};
Thumb.fromCanvas(canvas, function (e, blob) {
// carry on even if you can't get a thumbnail
if (e) { console.error(e); }
finish(blob);
});
};
var initializing = true;
var $bar = $('#toolbar');
var Title;
var UserList;
var Metadata;
var config = module.config = {
initialState: '{}',
websocketURL: Cryptpad.getWebsocketURL(),
validateKey: secret.keys.validateKey,
readOnly: readOnly,
channel: secret.channel,
crypto: Crypto.createEncryptor(secret.keys),
transformFunction: JsonOT.transform,
};
var addColorToPalette = function (color, i) {
if (readOnly) { return; }
var $color = $('<span>', {
'class': 'palette-color',
})
.css({
'background-color': color,
})
.click(function () {
var c = Colors.rgb2hex($color.css('background-color'));
setColor(c);
})
.on('dblclick', function (e) {
e.preventDefault();
pickColor(Colors.rgb2hex($color.css('background-color')), function (c) {
$color.css({
'background-color': c,
});
palette.splice(i, 1, c);
config.onLocal();
setColor(c);
});
});
$colors.append($color);
};
var metadataCfg = {};
var updatePalette = metadataCfg.updatePalette = function (newPalette) {
palette = newPalette;
$colors.html('<div class="hidden">&nbsp;</div>');
palette.forEach(addColorToPalette);
};
updatePalette(palette);
var makeColorButton = function ($container) {
var $testColor = $('<input>', { type: 'color', value: '!' });
// if colors aren't supported, bail out
if ($testColor.attr('type') !== 'color' ||
$testColor.val() === '!') {
console.log("Colors aren't supported. Aborting");
return;
}
var $color = module.$color = $('<button>', {
id: "color-picker",
title: Messages.canvas_chooseColor,
'class': "fa fa-square rightside-button",
})
.on('click', function () {
pickColor($color.css('background-color'), function (color) {
setColor(color);
});
});
setColor('#000');
$container.append($color);
return $color;
};
config.onInit = function (info) {
UserList = Cryptpad.createUserList(info, config.onLocal, Cryptget, Cryptpad);
Title = Cryptpad.createTitle({}, config.onLocal, Cryptpad);
Metadata = Cryptpad.createMetadata(UserList, Title, metadataCfg, Cryptpad);
var configTb = {
displayed: ['title', 'useradmin', 'spinner', 'lag', 'state', 'share', 'userlist', 'newpad', 'limit', 'upgrade'],
userList: UserList.getToolbarConfig(),
share: {
secret: secret,
channel: info.channel
},
title: Title.getTitleConfig(),
common: Cryptpad,
readOnly: readOnly,
ifrw: window,
realtime: info.realtime,
network: info.network,
$container: $bar,
$contentContainer: $('#canvas-area')
};
toolbar = module.toolbar = Toolbar.create(configTb);
Title.setToolbar(toolbar);
var $rightside = toolbar.$rightside;
/* save as template */
if (!Cryptpad.isTemplate(window.location.href)) {
var templateObj = {
rt: info.realtime,
Crypt: Cryptget,
getTitle: function () { return document.title; }
};
var $templateButton = Cryptpad.createButton('template', true, templateObj);
$rightside.append($templateButton);
}
var $export = Cryptpad.createButton('export', true, {}, saveImage);
$rightside.append($export);
Cryptpad.createButton('savetodrive', true, {}, function () {})
.click(function () {
Cryptpad.prompt(Messages.exportPrompt, document.title + '.png',
function (name) {
if (name === null || !name.trim()) { return; }
module.upload(name);
});
}).appendTo($rightside);
var $forget = Cryptpad.createButton('forget', true, {}, function (err) {
if (err) { return; }
setEditable(false);
toolbar.failed();
});
$rightside.append($forget);
var editHash;
if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
makeColorButton($rightside);
}
if (!readOnly) { Cryptpad.replaceHash(editHash); }
};
// used for debugging, feel free to remove
var Catch = function (f) {
return function () {
try {
f();
} catch (e) {
console.error(e);
}
};
};
var onRemote = config.onRemote = Catch(function () {
if (initializing) { return; }
var userDoc = module.realtime.getUserDoc();
Metadata.update(userDoc);
var json = JSON.parse(userDoc);
var remoteDoc = json.content;
// TODO update palette if it has changed
canvas.loadFromJSON(remoteDoc);
canvas.renderAll();
var content = canvas.toDatalessJSON();
if (content !== remoteDoc) { Cryptpad.notify(); }
if (readOnly) { setEditable(false); }
});
setEditable(false);
var stringifyInner = function (textValue) {
var obj = {
content: textValue,
metadata: {
users: UserList.userData,
palette: palette,
defaultTitle: Title.defaultTitle,
type: 'whiteboard',
}
};
if (!initializing) {
obj.metadata.title = Title.title;
}
// stringify the json and send it into chainpad
return JSONSortify(obj);
};
var onLocal = module.onLocal = config.onLocal = Catch(function () {
if (initializing) { return; }
if (readOnly) { return; }
var content = stringifyInner(canvas.toDatalessJSON());
module.patchText(content);
});
config.onReady = function (info) {
var realtime = module.realtime = info.realtime;
module.patchText = TextPatcher.create({
realtime: realtime
});
var isNew = false;
var userDoc = module.realtime.getUserDoc();
if (userDoc === "" || userDoc === "{}") { isNew = true; }
else {
var hjson = JSON.parse(userDoc);
if (typeof(hjson) !== 'object' || Array.isArray(hjson) ||
(typeof(hjson.type) !== 'undefined' && hjson.type !== 'whiteboard')) {
Cryptpad.errorLoadingScreen(Messages.typeError);
throw new Error(Messages.typeError);
}
}
Cryptpad.removeLoadingScreen();
setEditable(true);
initializing = false;
onRemote();
/* TODO: restore palette from metadata.palette */
if (readOnly) { return; }
UserList.getLastName(toolbar.$userNameButton, isNew);
};
config.onAbort = function () {
setEditable(false);
toolbar.failed();
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
};
// TODO onConnectionStateChange
config.onConnectionChange = function (info) {
setEditable(info.state);
toolbar.failed();
if (info.state) {
initializing = true;
toolbar.reconnecting(info.myId);
Cryptpad.findOKButton().click();
} else {
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}
};
module.rt = Realtime.start(config);
canvas.on('mouse:up', onLocal);
$('#clear').on('click', function () {
canvas.clear();
onLocal();
});
$('#save').on('click', function () {
saveImage();
});
};
Cryptpad.ready(function () {
andThen();
Cryptpad.reportAppUsage();
});
Cryptpad.onError(function (info) {
if (info) {
onConnectError();
}
});
});
});

@ -0,0 +1,139 @@
@import (once) "../../customize/src/less2/include/browser.less";
@import (once) "../../customize/src/less2/include/toolbar.less";
@import (once) "../../customize/src/less2/include/markdown.less";
@import (once) '../../customize/src/less2/include/fileupload.less';
@import (once) '../../customize/src/less2/include/alertify.less';
.toolbar_main();
.fileupload_main();
.alertify_main();
// body
&.cp-app-whiteboard {
display: flex;
flex-flow: column;
height: 100%;
.middle () {
position: relative;
vertical-align: middle;
}
.hidden {
display: none;
}
// created in the html
#cp-app-whiteboard-canvas-area {
flex: 1;
display: flex;
}
// created by fabricjs. styled so defaults don't break anything
.cp-app-whiteboard-canvas-container {
margin: auto;
background: white;
& > canvas {
border: 1px solid black;
}
}
// contains user tools
#cp-app-whiteboard-controls {
display: flex;
align-items: center;
justify-content: center;
position: relative;
border-top: 1px solid black;
background: white;
padding: 1em;
& > * + * {
margin: 0;
margin-left: 1em;
}
#cp-app-whiteboard-width, #cp-app-whiteboard-opacity {
.middle;
}
#cp-app-whiteboard-clear, #cp-app-whiteboard-delete, #cp-app-whiteboard-toggledraw {
display: inline;
vertical-align: middle;
}
.cp-app-whiteboard-selected {
display: flex;
align-items: center;
justify-content: center;
z-index: 9001;
width: 100px;
height: 100px;
}
.cp-app-whiteboard-range-group {
display: flex;
flex-direction: column;
position: relative;
input[type="range"] {
background-color: inherit;
}
& > span {
cursor: default;
position: absolute;
top: 0;
right: 0;
}
}
.cp-app-whiteboard-range-group:first-of-type {
margin-left: 2em;
}
.cp-app-whiteboard-range-group:last-of-type {
margin-right: 1em;
}
}
/* Colors */
#cp-app-whiteboard-colors {
.middle;
z-index: 100;
background: white;
display: flex;
justify-content: space-between;
padding: 1em;
span.cp-app-whiteboard-palette-color {
height: 4vw;
width: 4vw;
display: block;
margin: 5px;
border: 1px solid black;
vertical-align: top;
border-radius: 50%;
transition: transform 0.1s;
&:hover {
transform: scale(1.2);
}
}
}
// used in the toolbar if supported
#cp-app-whiteboard-color-picker {
display: block;
}
// input[type=color] must exist in the dom to work correctly
// styled so that they don't break layouts
#cp-app-whiteboard-pickers {
visibility: hidden;
position: absolute;
width: 0;
height: 0;
z-index: -5;
}
}

@ -1,9 +1,38 @@
<!DOCTYPE html> <!DOCTYPE html>
<html class="cp"> <html>
<head> <head>
<title>CryptPad</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/> <meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<script async data-bootload="/customize/template.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script> <meta name="referrer" content="no-referrer" />
<script async data-bootload="main.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
<style>
html, body {
margin: 0px;
padding: 0px;
}
#sbox-iframe {
position:fixed;
top:0px;
left:0px;
bottom:0px;
right:0px;
width:100%;
height:100%;
border:none;
margin:0;
padding:0;
overflow:hidden;
}
#sbox-filePicker-iframe {
position: fixed;
top:0; left:0;
bottom:0; right:0;
width:100%;
height: 100%;
border: 0;
}
</style>
</head> </head>
<body> <body>
<iframe id="sbox-iframe">

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<script async data-bootload="/whiteboard/inner.js" data-main="/common/sframe-boot.js?ver=1.5" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
<style>
.loading-hidden { display: none; }
#editor1 { display: none; }
</style>
</head>
<body class="cp-app-whiteboard">

@ -0,0 +1,551 @@
define([
'jquery',
'/bower_components/chainpad-crypto/crypto.js',
'/bower_components/textpatcher/TextPatcher.js',
'/common/toolbar3.js',
'json.sortify',
'/bower_components/chainpad-json-validator/json-ot.js',
'/common/cryptpad-common.js',
'/common/cryptget.js',
'/bower_components/nthen/index.js',
'/common/sframe-common.js',
'/api/config',
'/common/common-realtime.js',
'/customize/pages.js',
'/customize/application_config.js',
'/common/common-thumbnail.js',
'/whiteboard/colors.js',
'/bower_components/secure-fabric.js/dist/fabric.min.js',
'/bower_components/file-saver/FileSaver.min.js',
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css',
'less!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less2/main.less',
], function (
$,
Crypto,
TextPatcher,
Toolbar,
JSONSortify,
JsonOT,
Cryptpad,
Cryptget,
nThen,
SFCommon,
ApiConfig,
CommonRealtime,
Pages,
AppConfig,
Thumb,
Colors)
{
var saveAs = window.saveAs;
var Messages = Cryptpad.Messages;
var APP = window.APP = {
Cryptpad: Cryptpad,
$: $
};
var Fabric = APP.Fabric = window.fabric;
var stringify = function (obj) {
return JSONSortify(obj);
};
var toolbar;
var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError);
};
var andThen = function (common) {
/* Initialize Fabric */
var canvas = APP.canvas = new Fabric.Canvas('cp-app-whiteboard-canvas', {
containerClass: 'cp-app-whiteboard-canvas-container'
});
var $canvas = $('canvas');
var $controls = $('#cp-app-whiteboard-controls');
var $canvasContainer = $('canvas').parents('.cp-app-whiteboard-canvas-container');
var $pickers = $('#cp-app-whiteboard-pickers');
var $colors = $('#cp-app-whiteboard-colors');
var $cursors = $('#cp-app-whiteboard-cursors');
var $deleteButton = $('#cp-app-whiteboard-delete');
var $toggle = $('#cp-app-whiteboard-toggledraw');
var $width = $('#cp-app-whiteboard-width');
var $widthLabel = $('label[for="cp-app-whiteboard-width"]');
var $opacity = $('#cp-app-whiteboard-opacity');
var $opacityLabel = $('label[for="cp-app-whiteboard-opacity"]');
// Brush
var brush = {
color: '#000000',
opacity: 1
};
var createCursor = function () {
var w = canvas.freeDrawingBrush.width;
var c = canvas.freeDrawingBrush.color;
var size = w > 30 ? w+2 : w+32;
$cursors.html('<canvas width="'+size+'" height="'+size+'"></canvas>');
var $ccanvas = $cursors.find('canvas');
var ccanvas = $ccanvas[0];
var ctx = ccanvas.getContext('2d');
var centerX = size / 2;
var centerY = size / 2;
var radius = w/2;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = c;
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = brush.color;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(size/2, 0); ctx.lineTo(size/2, 10);
ctx.moveTo(size/2, size); ctx.lineTo(size/2, size-10);
ctx.moveTo(0, size/2); ctx.lineTo(10, size/2);
ctx.moveTo(size, size/2); ctx.lineTo(size-10, size/2);
ctx.strokeStyle = '#000000';
ctx.stroke();
var img = ccanvas.toDataURL("image/png");
$controls.find('.cp-app-whiteboard-selected > img').attr('src', img);
canvas.freeDrawingCursor = 'url('+img+') '+size/2+' '+size/2+', crosshair';
};
var updateBrushWidth = function () {
var val = $width.val();
canvas.freeDrawingBrush.width = Number(val);
$widthLabel.text(Cryptpad.Messages._getKey("canvas_widthLabel", [val]));
$('#cp-app-whiteboard-width-val').text(val + 'px');
createCursor();
};
updateBrushWidth();
$width.on('change', updateBrushWidth);
var updateBrushOpacity = function () {
var val = $opacity.val();
brush.opacity = Number(val);
canvas.freeDrawingBrush.color = Colors.hex2rgba(brush.color, brush.opacity);
$opacityLabel.text(Cryptpad.Messages._getKey("canvas_opacityLabel", [val]));
$('#cp-app-whiteboard-opacity-val').text((Number(val) * 100) + '%');
createCursor();
};
updateBrushOpacity();
$opacity.on('change', updateBrushOpacity);
var pickColor = function (current, cb) {
var $picker = $('<input>', {
type: 'color',
value: '#FFFFFF',
})
.on('change', function () {
var color = this.value;
cb(color);
}).appendTo($pickers);
setTimeout(function () {
$picker.val(current);
$picker.click();
});
};
var setColor = function (c) {
c = Colors.rgb2hex(c);
brush.color = c;
canvas.freeDrawingBrush.color = Colors.hex2rgba(brush.color, brush.opacity);
APP.$color.css({
'color': c,
});
createCursor();
};
var palette = AppConfig.whiteboardPalette || [
'red', 'blue', 'green', 'white', 'black', 'purple',
'gray', 'beige', 'brown', 'cyan', 'darkcyan', 'gold', 'yellow', 'pink'
];
$('.cp-app-whiteboard-palette-color').on('click', function () {
var color = $(this).css('background-color');
setColor(color);
});
APP.draw = true;
var toggleDrawMode = function () {
APP.draw = !APP.draw;
canvas.isDrawingMode = APP.draw;
$toggle.text(APP.draw ? Messages.canvas_disable : Messages.canvas_enable);
if (APP.draw) { $deleteButton.hide(); }
else { $deleteButton.show(); }
};
$toggle.click(toggleDrawMode);
var deleteSelection = function () {
if (canvas.getActiveObject()) {
canvas.getActiveObject().remove();
}
if (canvas.getActiveGroup()) {
canvas.getActiveGroup()._objects.forEach(function (el) {
el.remove();
});
canvas.discardActiveGroup();
}
canvas.renderAll();
APP.onLocal();
};
$deleteButton.click(deleteSelection);
$(window).on('keyup', function (e) {
if (e.which === 46) { deleteSelection (); }
});
var setEditable = function (bool) {
if (readOnly && bool) { return; }
if (bool) { $controls.css('display', 'flex'); }
else { $controls.hide(); }
canvas.isDrawingMode = bool ? APP.draw : false;
if (!bool) {
canvas.deactivateAll();
canvas.renderAll();
}
canvas.forEachObject(function (object) {
object.selectable = bool;
});
$canvasContainer.find('canvas').css('border-color', bool? 'black': 'red');
};
var saveImage = APP.saveImage = function () {
var defaultName = "pretty-picture.png";
Cryptpad.prompt(Messages.exportPrompt, defaultName, function (filename) {
if (!(typeof(filename) === 'string' && filename)) { return; }
$canvas[0].toBlob(function (blob) {
saveAs(blob, filename);
});
});
};
APP.FM = common.createFileManager({});
APP.upload = function (title) {
var canvas = $canvas[0];
var finish = function (thumb) {
canvas.toBlob(function (blob) {
blob.name = title;
APP.FM.handleFile(blob, void 0, thumb);
});
};
Thumb.fromCanvas(canvas, function (e, blob) {
// carry on even if you can't get a thumbnail
if (e) { console.error(e); }
finish(blob);
});
};
var initializing = true;
var $bar = $('#cp-toolbar');
var Title;
var cpNfInner;
var metadataMgr;
var readOnly = false;
var config = {
readOnly: readOnly,
transformFunction: JsonOT.validate,
// cryptpad debug logging (default is 1)
// logLevel: 0,
validateContent: function (content) {
try {
JSON.parse(content);
return true;
} catch (e) {
console.log("Failed to parse, rejecting patch");
return false;
}
}
};
var addColorToPalette = function (color, i) {
if (readOnly) { return; }
var $color = $('<span>', {
'class': 'cp-app-whiteboard-palette-color',
})
.css({
'background-color': color,
})
.click(function () {
var c = Colors.rgb2hex($color.css('background-color'));
setColor(c);
})
.on('dblclick', function (e) {
e.preventDefault();
pickColor(Colors.rgb2hex($color.css('background-color')), function (c) {
$color.css({
'background-color': c,
});
palette.splice(i, 1, c);
config.onLocal();
setColor(c);
});
});
$colors.append($color);
};
var first = true;
var updatePalette = function (newPalette) {
if (first || stringify(palette) !== stringify(newPalette)) {
palette = newPalette;
$colors.html('<div class="hidden">&nbsp;</div>');
palette.forEach(addColorToPalette);
first = false;
}
};
var updateLocalPalette = function (newPalette) {
updatePalette(newPalette);
var metadata = JSON.parse(JSON.stringify(metadataMgr.getMetadata()));
metadata.palette = newPalette;
metadataMgr.updateMetadata(metadata);
onLocal();
};
updatePalette(palette);
var makeColorButton = function ($container) {
var $testColor = $('<input>', { type: 'color', value: '!' });
// if colors aren't supported, bail out
if ($testColor.attr('type') !== 'color' ||
$testColor.val() === '!') {
console.log("Colors aren't supported. Aborting");
return;
}
var $color = APP.$color = $('<button>', {
id: "cp-app-whiteboard-color-picker",
title: Messages.canvas_chooseColor,
'class': "fa fa-square cp-toolbar-rightside-button",
})
.on('click', function () {
pickColor($color.css('background-color'), function (color) {
setColor(color);
});
});
setColor('#000');
$container.append($color);
return $color;
};
var stringifyInner = function (textValue) {
var obj = {
content: textValue,
metadata: metadataMgr.getMetadataLazy()
};
// stringify the json and send it into chainpad
return stringify(obj);
};
var onLocal = config.onLocal = function () {
if (initializing) { return; }
if (readOnly) { return; }
var content = stringifyInner(canvas.toDatalessJSON());
APP.patchText(content);
};
config.onInit = function (info) {
readOnly = metadataMgr.getPrivateData().readOnly;
Title = common.createTitle({}, config.onLocal);
var configTb = {
displayed: ['title', 'useradmin', 'spinner', 'share', 'userlist', 'newpad', 'limit'],
title: Title.getTitleConfig(),
metadataMgr: metadataMgr,
readOnly: readOnly,
realtime: info.realtime,
common: Cryptpad,
sfCommon: common,
$container: $bar,
$contentContainer: $('#cp-app-whiteboard-canvas-area')
};
toolbar = APP.toolbar = Toolbar.create(configTb);
Title.setToolbar(toolbar);
var $rightside = toolbar.$rightside;
var $drawer = toolbar.$drawer;
/* save as template */
if (!metadataMgr.getPrivateData().isTemplate) {
var templateObj = {
rt: info.realtime,
getTitle: function () { return metadataMgr.getMetadata().title; }
};
var $templateButton = common.createButton('template', true, templateObj);
$rightside.append($templateButton);
}
/* add an export button */
var $export = common.createButton('export', true, {}, saveImage);
$rightside.append($export);
common.createButton('savetodrive', true, {}, function () {})
.click(function () {
Cryptpad.prompt(Messages.exportPrompt, document.title + '.png',
function (name) {
if (name === null || !name.trim()) { return; }
APP.upload(name);
});
}).appendTo($rightside);
var $forget = common.createButton('forget', true, {}, function (err) {
if (err) { return; }
setEditable(false);
});
$rightside.append($forget);
if (!readOnly) {
makeColorButton($rightside);
}
metadataMgr.onChange(function () {
var md = metadataMgr.getMetadata();
if (md.palette) {
updatePalette(md.palette);
}
});
};
config.onReady = function (info) {
if (APP.realtime !== info.realtime) {
var realtime = APP.realtime = info.realtime;
APP.patchText = TextPatcher.create({
realtime: realtime,
//logging: true
});
}
var userDoc = APP.realtime.getUserDoc();
var isNew = false;
if (userDoc === "" || userDoc === "{}") { isNew = true; }
var newDoc = "";
if (userDoc !== "") {
var hjson = JSON.parse(userDoc);
if (hjson && hjson.metadata) {
metadataMgr.updateMetadata(hjson.metadata);
}
if (typeof (hjson) !== 'object' || Array.isArray(hjson) ||
(hjson.metadata && typeof(hjson.metadata.type) !== 'undefined' &&
hjson.metadata.type !== 'whiteboard')) {
var errorText = Messages.typeError;
Cryptpad.errorLoadingScreen(errorText);
throw new Error(errorText);
}
} else {
Title.updateTitle(Cryptpad.initialName || Title.defaultTitle);
}
Cryptpad.removeLoadingScreen();
setEditable(!readOnly);
initializing = false;
config.onRemote();
if (readOnly) { return; }
if (isNew) {
common.openTemplatePicker();
}
};
config.onRemote = function () {
if (initializing) { return; }
var userDoc = APP.realtime.getUserDoc();
var json = JSON.parse(userDoc);
var remoteDoc = json.content;
if (json.metadata) {
metadataMgr.updateMetadata(json.metadata);
}
// TODO update palette if it has changed
canvas.loadFromJSON(remoteDoc);
canvas.renderAll();
var content = canvas.toDatalessJSON();
if (content !== remoteDoc) { common.notify(); }
if (readOnly) { setEditable(false); }
};
config.onAbort = function () {
// inform of network disconnect
setEditable(false);
toolbar.failed();
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
};
config.onConnectionChange = function (info) {
setEditable(info.state);
if (info.state) {
initializing = true;
Cryptpad.findOKButton().click();
} else {
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}
};
config.onError = onConnectError;
cpNfInner = common.startRealtime(config);
metadataMgr = cpNfInner.metadataMgr;
cpNfInner.onInfiniteSpinner(function () {
setEditable(false);
Cryptpad.confirm(Messages.realtime_unrecoverableError, function (yes) {
if (!yes) { return; }
common.gotoURL();
});
});
canvas.on('mouse:up', onLocal);
$('#clear').on('click', function () {
canvas.clear();
onLocal();
});
$('#save').on('click', function () {
saveImage();
});
Cryptpad.onLogout(function () { setEditable(false); });
};
var main = function () {
var common;
nThen(function (waitFor) {
$(waitFor(function () {
Cryptpad.addLoadingScreen();
$('body').append(Pages['/whiteboard/']());
}));
SFCommon.create(waitFor(function (c) { APP.common = common = c; }));
}).nThen(function (/*waitFor*/) {
Cryptpad.onError(function (info) {
if (info && info.type === "store") {
onConnectError();
}
});
andThen(common);
});
};
main();
});

@ -1,511 +1,41 @@
// Load #1, load as little as possible because we are in a race to get the loading screen up.
define([ define([
'jquery', '/bower_components/nthen/index.js',
'/api/config', '/api/config',
'/bower_components/chainpad-netflux/chainpad-netflux.js', 'jquery',
'/bower_components/chainpad-crypto/crypto.js', '/common/requireconfig.js',
'/common/toolbar2.js', '/common/sframe-common-outer.js'
'/bower_components/textpatcher/TextPatcher.amd.js', ], function (nThen, ApiConfig, $, RequireConfig, SFCommonO) {
'json.sortify', var requireConfig = RequireConfig();
'/bower_components/chainpad-json-validator/json-ot.js',
'/common/cryptpad-common.js', // Loaded in load #2
'/common/cryptget.js', nThen(function (waitFor) {
'/whiteboard/colors.js', $(waitFor());
'/customize/application_config.js', }).nThen(function (waitFor) {
'/common/common-thumbnail.js', var req = {
'/bower_components/secure-fabric.js/dist/fabric.min.js', cfg: requireConfig,
'/bower_components/file-saver/FileSaver.min.js', req: [ '/common/loading.js' ],
pfx: window.location.origin
'less!/bower_components/components-font-awesome/css/font-awesome.min.css', };
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css', window.rc = requireConfig;
'less!/customize/src/less/cryptpad.less', window.apiconf = ApiConfig;
'less!/whiteboard/whiteboard.less', $('#sbox-iframe').attr('src',
'less!/customize/src/less/toolbar.less', ApiConfig.httpSafeOrigin + '/whiteboard/inner.html?' + requireConfig.urlArgs +
], function ($, Config, Realtime, Crypto, Toolbar, TextPatcher, JSONSortify, JsonOT, Cryptpad, Cryptget, Colors, AppConfig, Thumb) { '#' + encodeURIComponent(JSON.stringify(req)));
var saveAs = window.saveAs;
var Messages = Cryptpad.Messages; // This is a cheap trick to avoid loading sframe-channel in parallel with the
// loading screen setup.
var module = window.APP = { $:$ }; var done = waitFor();
var Fabric = module.Fabric = window.fabric; var onMsg = function (msg) {
var data = JSON.parse(msg.data);
$(function () { if (data.q !== 'READY') { return; }
Cryptpad.addLoadingScreen(); window.removeEventListener('message', onMsg);
var onConnectError = function () { var _done = done;
Cryptpad.errorLoadingScreen(Messages.websocketError); done = function () { };
}; _done();
var toolbar; };
window.addEventListener('message', onMsg);
var secret = Cryptpad.getSecrets(); }).nThen(function (/*waitFor*/) {
var readOnly = secret.keys && !secret.keys.editKeyStr; SFCommonO.start();
if (!secret.keys) {
secret.keys = secret.key;
}
var andThen = function () {
/* Initialize Fabric */
var canvas = module.canvas = new Fabric.Canvas('canvas');
var $canvas = $('canvas');
var $controls = $('#controls');
var $canvasContainer = $('canvas').parents('.canvas-container');
var $pickers = $('#pickers');
var $colors = $('#colors');
var $cursors = $('#cursors');
var $deleteButton = $('#delete');
var brush = {
color: '#000000',
opacity: 1
};
var $toggle = $('#toggleDraw');
var $width = $('#width');
var $widthLabel = $('label[for="width"]');
var $opacity = $('#opacity');
var $opacityLabel = $('label[for="opacity"]');
window.canvas = canvas;
var createCursor = function () {
var w = canvas.freeDrawingBrush.width;
var c = canvas.freeDrawingBrush.color;
var size = w > 30 ? w+2 : w+32;
$cursors.html('<canvas width="'+size+'" height="'+size+'"></canvas>');
var $ccanvas = $cursors.find('canvas');
var ccanvas = $ccanvas[0];
var ctx = ccanvas.getContext('2d');
var centerX = size / 2;
var centerY = size / 2;
var radius = w/2;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = c;
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = brush.color;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(size/2, 0); ctx.lineTo(size/2, 10);
ctx.moveTo(size/2, size); ctx.lineTo(size/2, size-10);
ctx.moveTo(0, size/2); ctx.lineTo(10, size/2);
ctx.moveTo(size, size/2); ctx.lineTo(size-10, size/2);
ctx.strokeStyle = '#000000';
ctx.stroke();
var img = ccanvas.toDataURL("image/png");
$controls.find('.selected > img').attr('src', img);
canvas.freeDrawingCursor = 'url('+img+') '+size/2+' '+size/2+', crosshair';
};
var updateBrushWidth = function () {
var val = $width.val();
canvas.freeDrawingBrush.width = Number(val);
$widthLabel.text(Cryptpad.Messages._getKey("canvas_widthLabel", [val]));
$('#width-val').text(val + 'px');
createCursor();
};
updateBrushWidth();
$width.on('change', updateBrushWidth);
var updateBrushOpacity = function () {
var val = $opacity.val();
brush.opacity = Number(val);
canvas.freeDrawingBrush.color = Colors.hex2rgba(brush.color, brush.opacity);
$opacityLabel.text(Cryptpad.Messages._getKey("canvas_opacityLabel", [val]));
$('#opacity-val').text((Number(val) * 100) + '%');
createCursor();
};
updateBrushOpacity();
$opacity.on('change', updateBrushOpacity);
var pickColor = function (current, cb) {
var $picker = $('<input>', {
type: 'color',
value: '#FFFFFF',
})
// TODO confirm that this is safe to remove
//.css({ visibility: 'hidden' })
.on('change', function () {
var color = this.value;
cb(color);
}).appendTo($pickers);
setTimeout(function () {
$picker.val(current);
$picker.click();
});
};
var setColor = function (c) {
c = Colors.rgb2hex(c);
brush.color = c;
canvas.freeDrawingBrush.color = Colors.hex2rgba(brush.color, brush.opacity);
module.$color.css({
'color': c,
});
createCursor();
};
var palette = AppConfig.whiteboardPalette || [
'red', 'blue', 'green', 'white', 'black', 'purple',
'gray', 'beige', 'brown', 'cyan', 'darkcyan', 'gold', 'yellow', 'pink'
];
$('.palette-color').on('click', function () {
var color = $(this).css('background-color');
setColor(color);
});
module.draw = true;
var toggleDrawMode = function () {
module.draw = !module.draw;
canvas.isDrawingMode = module.draw;
$toggle.text(module.draw ? Messages.canvas_disable : Messages.canvas_enable);
if (module.draw) { $deleteButton.hide(); }
else { $deleteButton.show(); }
};
$toggle.click(toggleDrawMode);
var deleteSelection = function () {
if (canvas.getActiveObject()) {
canvas.getActiveObject().remove();
}
if (canvas.getActiveGroup()) {
canvas.getActiveGroup()._objects.forEach(function (el) {
el.remove();
});
canvas.discardActiveGroup();
}
canvas.renderAll();
module.onLocal();
};
$deleteButton.click(deleteSelection);
$(window).on('keyup', function (e) {
if (e.which === 46) { deleteSelection (); }
});
var setEditable = function (bool) {
if (readOnly && bool) { return; }
if (bool) { $controls.css('display', 'flex'); }
else { $controls.hide(); }
canvas.isDrawingMode = bool ? module.draw : false;
if (!bool) {
canvas.deactivateAll();
canvas.renderAll();
}
canvas.forEachObject(function (object) {
object.selectable = bool;
});
$canvasContainer.find('canvas').css('border-color', bool? 'black': 'red');
};
var saveImage = module.saveImage = function () {
var defaultName = "pretty-picture.png";
Cryptpad.prompt(Messages.exportPrompt, defaultName, function (filename) {
if (!(typeof(filename) === 'string' && filename)) { return; }
$canvas[0].toBlob(function (blob) {
saveAs(blob, filename);
});
});
};
module.FM = Cryptpad.createFileManager({});
module.upload = function (title) {
var canvas = $canvas[0];
var finish = function (thumb) {
canvas.toBlob(function (blob) {
blob.name = title;
module.FM.handleFile(blob, void 0, thumb);
});
};
Thumb.fromCanvas(canvas, function (e, blob) {
// carry on even if you can't get a thumbnail
if (e) { console.error(e); }
finish(blob);
});
};
var initializing = true;
var $bar = $('#toolbar');
var Title;
var UserList;
var Metadata;
var config = module.config = {
initialState: '{}',
websocketURL: Cryptpad.getWebsocketURL(),
validateKey: secret.keys.validateKey,
readOnly: readOnly,
channel: secret.channel,
crypto: Crypto.createEncryptor(secret.keys),
transformFunction: JsonOT.transform,
};
var addColorToPalette = function (color, i) {
if (readOnly) { return; }
var $color = $('<span>', {
'class': 'palette-color',
})
.css({
'background-color': color,
})
.click(function () {
var c = Colors.rgb2hex($color.css('background-color'));
setColor(c);
})
.on('dblclick', function (e) {
e.preventDefault();
pickColor(Colors.rgb2hex($color.css('background-color')), function (c) {
$color.css({
'background-color': c,
});
palette.splice(i, 1, c);
config.onLocal();
setColor(c);
});
});
$colors.append($color);
};
var metadataCfg = {};
var updatePalette = metadataCfg.updatePalette = function (newPalette) {
palette = newPalette;
$colors.html('<div class="hidden">&nbsp;</div>');
palette.forEach(addColorToPalette);
};
updatePalette(palette);
var makeColorButton = function ($container) {
var $testColor = $('<input>', { type: 'color', value: '!' });
// if colors aren't supported, bail out
if ($testColor.attr('type') !== 'color' ||
$testColor.val() === '!') {
console.log("Colors aren't supported. Aborting");
return;
}
var $color = module.$color = $('<button>', {
id: "color-picker",
title: Messages.canvas_chooseColor,
'class': "fa fa-square rightside-button",
})
.on('click', function () {
pickColor($color.css('background-color'), function (color) {
setColor(color);
});
});
setColor('#000');
$container.append($color);
return $color;
};
config.onInit = function (info) {
UserList = Cryptpad.createUserList(info, config.onLocal, Cryptget, Cryptpad);
Title = Cryptpad.createTitle({}, config.onLocal, Cryptpad);
Metadata = Cryptpad.createMetadata(UserList, Title, metadataCfg, Cryptpad);
var configTb = {
displayed: ['title', 'useradmin', 'spinner', 'lag', 'state', 'share', 'userlist', 'newpad', 'limit', 'upgrade'],
userList: UserList.getToolbarConfig(),
share: {
secret: secret,
channel: info.channel
},
title: Title.getTitleConfig(),
common: Cryptpad,
readOnly: readOnly,
ifrw: window,
realtime: info.realtime,
network: info.network,
$container: $bar,
$contentContainer: $('#canvas-area')
};
toolbar = module.toolbar = Toolbar.create(configTb);
Title.setToolbar(toolbar);
var $rightside = toolbar.$rightside;
/* save as template */
if (!Cryptpad.isTemplate(window.location.href)) {
var templateObj = {
rt: info.realtime,
Crypt: Cryptget,
getTitle: function () { return document.title; }
};
var $templateButton = Cryptpad.createButton('template', true, templateObj);
$rightside.append($templateButton);
}
var $export = Cryptpad.createButton('export', true, {}, saveImage);
$rightside.append($export);
Cryptpad.createButton('savetodrive', true, {}, function () {})
.click(function () {
Cryptpad.prompt(Messages.exportPrompt, document.title + '.png',
function (name) {
if (name === null || !name.trim()) { return; }
module.upload(name);
});
}).appendTo($rightside);
var $forget = Cryptpad.createButton('forget', true, {}, function (err) {
if (err) { return; }
setEditable(false);
toolbar.failed();
});
$rightside.append($forget);
var editHash;
if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
makeColorButton($rightside);
}
if (!readOnly) { Cryptpad.replaceHash(editHash); }
};
// used for debugging, feel free to remove
var Catch = function (f) {
return function () {
try {
f();
} catch (e) {
console.error(e);
}
};
};
var onRemote = config.onRemote = Catch(function () {
if (initializing) { return; }
var userDoc = module.realtime.getUserDoc();
Metadata.update(userDoc);
var json = JSON.parse(userDoc);
var remoteDoc = json.content;
// TODO update palette if it has changed
canvas.loadFromJSON(remoteDoc);
canvas.renderAll();
var content = canvas.toDatalessJSON();
if (content !== remoteDoc) { Cryptpad.notify(); }
if (readOnly) { setEditable(false); }
});
setEditable(false);
var stringifyInner = function (textValue) {
var obj = {
content: textValue,
metadata: {
users: UserList.userData,
palette: palette,
defaultTitle: Title.defaultTitle,
type: 'whiteboard',
}
};
if (!initializing) {
obj.metadata.title = Title.title;
}
// stringify the json and send it into chainpad
return JSONSortify(obj);
};
var onLocal = module.onLocal = config.onLocal = Catch(function () {
if (initializing) { return; }
if (readOnly) { return; }
var content = stringifyInner(canvas.toDatalessJSON());
module.patchText(content);
});
config.onReady = function (info) {
var realtime = module.realtime = info.realtime;
module.patchText = TextPatcher.create({
realtime: realtime
});
var isNew = false;
var userDoc = module.realtime.getUserDoc();
if (userDoc === "" || userDoc === "{}") { isNew = true; }
else {
var hjson = JSON.parse(userDoc);
if (typeof(hjson) !== 'object' || Array.isArray(hjson) ||
(typeof(hjson.type) !== 'undefined' && hjson.type !== 'whiteboard')) {
Cryptpad.errorLoadingScreen(Messages.typeError);
throw new Error(Messages.typeError);
}
}
Cryptpad.removeLoadingScreen();
setEditable(true);
initializing = false;
onRemote();
/* TODO: restore palette from metadata.palette */
if (readOnly) { return; }
UserList.getLastName(toolbar.$userNameButton, isNew);
};
config.onAbort = function () {
setEditable(false);
toolbar.failed();
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
};
// TODO onConnectionStateChange
config.onConnectionChange = function (info) {
setEditable(info.state);
toolbar.failed();
if (info.state) {
initializing = true;
toolbar.reconnecting(info.myId);
Cryptpad.findOKButton().click();
} else {
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}
};
module.rt = Realtime.start(config);
canvas.on('mouse:up', onLocal);
$('#clear').on('click', function () {
canvas.clear();
onLocal();
});
$('#save').on('click', function () {
saveImage();
});
};
Cryptpad.ready(function () {
andThen();
Cryptpad.reportAppUsage();
});
Cryptpad.onError(function (info) {
if (info) {
onConnectError();
}
});
}); });
}); });

Loading…
Cancel
Save