Move slide to secure iframe

This commit is contained in:
yflory 2017-09-07 18:56:58 +02:00
parent 0423a5f4e2
commit f2aaaa9751
27 changed files with 2728 additions and 867 deletions

View File

@ -1,5 +1,5 @@
// html
.noscroll_main () {
.app-noscroll_main () {
height: 100%;
width: 100%;
padding: 0px;

View File

@ -0,0 +1,46 @@
.app-print_main () {
// Current scope is <html>
@media print {
height: auto;
max-height: none;
overflow: visible;
display:block;
@page {
margin: 0;
size: landscape;
}
// Slide app
body.cp-app-slide {
display: block;
.CodeMirror, #cme_toolbox {
display: none;
}
* {
visibility: hidden;
height: auto;
max-height: none;
}
.cp-app-slide-viewer #cp-app-slide-print {
display: block;
visibility: visible;
* {
visibility: visible;
}
}
.cp-app-slide-viewer #cp-app-slide-modal {
display: none !important;
}
.cp-app-slide-viewer {
flex: 1 !important;
overflow: visible !important;
}
.cp-toolbar-userlist-drawer {
display: none !important;
}
#cp-app-slide-editor {
height: auto;
display: block;
}
}
}
}

View File

@ -14,10 +14,16 @@ body.cp-page-terms { @import "./pages/page-terms.less"; }
// Set the HTML style for the apps which shouldn't have a body scrollbar
html.cp-app-noscroll {
@import "./include/app-noscroll.less";
.noscroll_main();
.app-noscroll_main();
}
// Set the HTML style for printing slides
html.cp-app-print {
@import "./include/app-print.less";
.app-print_main();
}
body.cp-app-pad { @import "../../../pad/app-pad.less"; }
body.cp-app-code { @import "../../../code/app-code.less"; }
body.cp-app-slide { @import "../../../slide/app-slide.less"; }
body.cp-app-filepicker { @import "../../../filepicker/app-filepicker.less"; }

View File

@ -24,7 +24,7 @@
resize: horizontal;
font-size: initial;
}
.CodeMirror.fullPage {
.CodeMirror.cp-app-code-fullpage {
//min-width: 100%;
max-width: 100%;
resize: none;

View File

@ -86,6 +86,39 @@ define([
var isHistoryMode = false;
var setEditable = APP.setEditable = function (bool) {
if (readOnly && bool) { return; }
editor.setOption('readOnly', !bool);
};
var Title;
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 canonicalize = function (t) { return t.replace(/\r\n/g, '\n'); };
var setHistory = function (bool, update) {
isHistoryMode = bool;
setEditable(!bool);
if (!bool && update) {
config.onRemote();
}
};
var $contentContainer = $('#cp-app-code-editor');
var $previewContainer = $('#cp-app-code-preview');
var $preview = $('#cp-app-code-preview-content');
@ -120,39 +153,6 @@ define([
typeof(useTabs) === 'boolean'? useTabs: false);
};
var setEditable = APP.setEditable = function (bool) {
if (readOnly && bool) { return; }
editor.setOption('readOnly', !bool);
};
var Title;
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 canonicalize = function (t) { return t.replace(/\r\n/g, '\n'); };
var setHistory = function (bool, update) {
isHistoryMode = bool;
setEditable(!bool);
if (!bool && update) {
config.onRemote();
}
};
CommonRealtime.onInfiniteSpinner(function () { setEditable(false); });
setEditable(false);
@ -336,14 +336,14 @@ define([
$previewContainer.toggle();
if ($previewContainer.is(':visible')) {
forceDrawPreview();
$codeMirror.removeClass('fullPage');
$previewButton.addClass('active');
$codeMirror.removeClass('cp-ap-code-fullpage');
$previewButton.addClass('cp-toolbar-button-active');
common.setPadAttribute('previewMode', true, function (e) {
if (e) { return console.log(e); }
});
} else {
$codeMirror.addClass('fullPage');
$previewButton.removeClass('active');
$codeMirror.addClass('cp-app-code-fullpage');
$previewButton.removeClass('cp-toolbar-button-active');
common.setPadAttribute('previewMode', false, function (e) {
if (e) { return console.log(e); }
});
@ -574,30 +574,7 @@ define([
Cryptpad.onLogout(function () { setEditable(false); });
};
/*
var interval = 100;
var second = function (CM) {
Cryptpad.ready(function () {
andThen(CM);
Cryptpad.reportAppUsage();
});
Cryptpad.onError(function (info) {
if (info && info.type === "store") {
onConnectError();
}
});
};
var first = function () {
if (ifrw.CodeMirror) {
second(ifrw.CodeMirror);
} else {
console.log("CodeMirror was not defined. Trying again in %sms", interval);
setTimeout(first, interval);
}
};
first();*/
var CMEDITOR_CHECK_INTERVAL = 100;
var cmEditorAvailable = function (cb) {
var intr;
@ -628,7 +605,7 @@ define([
}));
SFCommon.create(waitFor(function (c) { APP.common = common = c; }));
}).nThen(function (/*waitFor*/) {
CodeMirror = Cryptpad.createCodemirror(window, Cryptpad, null, CM);
CodeMirror = common.initCodeMirrorApp(null, CM);
$('.CodeMirror').addClass('fullPage');
editor = CodeMirror.editor;
Cryptpad.onError(function (info) {

View File

@ -493,11 +493,6 @@ define([
if (cb) { cb(err, data); }
});
};
/*common.setAttribute = function (attr, value, cb) {
getStore().set(["cryptpad", attr].join('.'), value, function (err, data) {
if (cb) { cb(err, data); }
});
};*/
common.setLSAttribute = function (attr, value) {
localStorage[attr] = value;
};
@ -512,11 +507,6 @@ define([
cb(err, data);
});
};
/*common.getAttribute = function (attr, cb) {
getStore().get(["cryptpad", attr].join('.'), function (err, data) {
cb(err, data);
});
};*/
/* this returns a reference to your proxy. changing it will change your drive.
*/
@ -1717,7 +1707,7 @@ define([
var setActive = function ($el) {
if ($el.length !== 1) { return; }
$innerblock.find('.cp-dropdown-element-active').removeClass('cp-dropdown-element(active');
$innerblock.find('.cp-dropdown-element-active').removeClass('cp-dropdown-element-active');
$el.addClass('cp-dropdown-element-active');
var scroll = $el.position().top + $innerblock.scrollTop();
if (scroll < $innerblock.scrollTop()) {

View File

@ -8,7 +8,7 @@ define([], function () {
var version = userObject.version || 0;
// Migration 1: pad attributes moved to filesData
var migrateAttributes = function () {
var migratePadAttributesToData = function () {
var files = userObject && userObject.drive;
if (!files) { return; }
@ -39,7 +39,7 @@ define([], function () {
// Migration done
};
if (version < 1) {
migrateAttributes();
migratePadAttributesToData();
Cryptpad.feedback('Migrate-1', true);
userObject.version = version = 1;
}

View File

@ -0,0 +1,312 @@
define([
'jquery',
'/common/modes.js',
'/common/themes.js',
'/common/cryptpad-common.js',
'/bower_components/file-saver/FileSaver.min.js'
], function ($, Modes, Themes, Cryptpad) {
var saveAs = window.saveAs;
var module = {};
module.create = function (Common, defaultMode, CMeditor) {
var exp = {};
var Messages = Cryptpad.Messages;
var CodeMirror = exp.CodeMirror = CMeditor;
CodeMirror.modeURL = "cm/mode/%N/%N";
var $pad = $('#pad-iframe');
var $textarea = exp.$textarea = $('#editor1');
if (!$textarea.length) { $textarea = exp.$textarea = $pad.contents().find('#editor1'); }
var Title;
var onLocal = function () {};
var $rightside;
var $drawer;
exp.init = function (local, title, toolbar) {
if (typeof local === "function") {
onLocal = local;
}
Title = title;
$rightside = toolbar.$rightside;
$drawer = toolbar.$drawer;
};
var editor = exp.editor = CMeditor.fromTextArea($textarea[0], {
lineNumbers: true,
lineWrapping: true,
autoCloseBrackets: true,
matchBrackets : true,
showTrailingSpace : true,
styleActiveLine : true,
search: true,
highlightSelectionMatches: {showToken: /\w+/},
extraKeys: {"Shift-Ctrl-R": undefined},
foldGutter: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
mode: defaultMode || "javascript",
readOnly: true
});
editor.setValue(Messages.codeInitialState);
var setMode = exp.setMode = function (mode, cb) {
exp.highlightMode = mode;
if (mode !== "text") {
CMeditor.autoLoadMode(editor, mode);
}
editor.setOption('mode', mode);
if (exp.$language) {
var name = exp.$language.find('a[data-value="' + mode + '"]').text() || undefined;
name = name ? Messages.languageButton + ' ('+name+')' : Messages.languageButton;
exp.$language.setValue(mode, name);
}
if(cb) { cb(mode); }
};
var setTheme = exp.setTheme = (function () {
var path = '/common/theme/';
var $head = $(window.document.head);
var themeLoaded = exp.themeLoaded = function (theme) {
return $head.find('link[href*="'+theme+'"]').length;
};
var loadTheme = exp.loadTheme = function (theme) {
$head.append($('<link />', {
rel: 'stylesheet',
href: path + theme + '.css',
}));
};
return function (theme, $select) {
if (!theme) {
editor.setOption('theme', 'default');
} else {
if (!themeLoaded(theme)) {
loadTheme(theme);
}
editor.setOption('theme', theme);
}
if ($select) {
var name = theme || undefined;
name = name ? Messages.themeButton + ' ('+theme+')' : Messages.themeButton;
$select.setValue(theme, name);
}
};
}());
exp.getHeadingText = function () {
var lines = editor.getValue().split(/\n/);
var text = '';
lines.some(function (line) {
// lines including a c-style comment are also valuable
var clike = /^\s*(\/\*|\/\/)(.*)?(\*\/)*$/;
if (clike.test(line)) {
line.replace(clike, function (a, one, two) {
if (!(two && two.replace)) { return; }
text = two.replace(/\*\/\s*$/, '').trim();
});
return true;
}
// lisps?
var lispy = /^\s*(;|#\|)+(.*?)$/;
if (lispy.test(line)) {
line.replace(lispy, function (a, one, two) {
text = two;
});
return true;
}
// lines beginning with a hash are potentially valuable
// works for markdown, python, bash, etc.
var hash = /^#+(.*?)$/;
if (hash.test(line)) {
line.replace(hash, function (a, one) {
text = one;
});
return true;
}
// TODO make one more pass for multiline comments
});
return text.trim();
};
exp.configureLanguage = function (cb, onModeChanged) {
var options = [];
Modes.list.forEach(function (l) {
options.push({
tag: 'a',
attributes: {
'data-value': l.mode,
'href': '#',
},
content: l.language // Pretty name of the language value
});
});
var dropdownConfig = {
text: 'Mode', // Button initial text
options: options, // Entries displayed in the menu
left: true, // Open to the left of the button
isSelect: true,
feedback: 'CODE_LANGUAGE',
};
var $block = exp.$language = Cryptpad.createDropdown(dropdownConfig);
$block.find('button').attr('title', Messages.languageButtonTitle);
$block.find('a').click(function () {
setMode($(this).attr('data-value'), onModeChanged);
onLocal();
});
if ($drawer) { $drawer.append($block); }
if (cb) { cb(); }
};
exp.configureTheme = function (cb) {
/* Remember the user's last choice of theme using localStorage */
var themeKey = ['codemirror', 'theme'];
var todo = function (err, lastTheme) {
lastTheme = lastTheme || 'default';
var options = [];
Themes.forEach(function (l) {
options.push({
tag: 'a',
attributes: {
'data-value': l.name,
'href': '#',
},
content: l.name // Pretty name of the language value
});
});
var dropdownConfig = {
text: 'Theme', // Button initial text
options: options, // Entries displayed in the menu
left: true, // Open to the left of the button
isSelect: true,
initialValue: lastTheme,
feedback: 'CODE_THEME',
};
var $block = exp.$theme = Cryptpad.createDropdown(dropdownConfig);
$block.find('button').attr('title', Messages.themeButtonTitle);
setTheme(lastTheme, $block);
$block.find('a').click(function () {
var theme = $(this).attr('data-value');
setTheme(theme, $block);
Common.setAttribute(themeKey, theme);
});
if ($drawer) { $drawer.append($block); }
if (cb) { cb(); }
};
Common.getAttribute(themeKey, todo);
};
exp.exportText = function () {
var text = editor.getValue();
var ext = Modes.extensionOf(exp.highlightMode);
var title = Cryptpad.fixFileName(Title ? Title.suggestTitle('cryptpad') : "?") + (ext || '.txt');
Cryptpad.prompt(Messages.exportPrompt, title, function (filename) {
if (filename === null) { return; }
var blob = new Blob([text], {
type: 'text/plain;charset=utf-8'
});
saveAs(blob, filename);
});
};
exp.importText = function (content, file) {
var $bar = $('#cme_toolbox');
var mode;
var mime = CodeMirror.findModeByMIME(file.type);
if (!mime) {
var ext = /.+\.([^.]+)$/.exec(file.name);
if (ext[1]) {
mode = CMeditor.findModeByExtension(ext[1]);
mode = mode && mode.mode || null;
}
} else {
mode = mime && mime.mode || null;
}
if (mode && Modes.list.some(function (o) { return o.mode === mode; })) {
setMode(mode);
$bar.find('#language-mode').val(mode);
} else {
console.log("Couldn't find a suitable highlighting mode: %s", mode);
setMode('text');
$bar.find('#language-mode').val('text');
}
editor.setValue(content);
onLocal();
};
var cursorToPos = function(cursor, oldText) {
var cLine = cursor.line;
var cCh = cursor.ch;
var pos = 0;
var textLines = oldText.split("\n");
for (var line = 0; line <= cLine; line++) {
if(line < cLine) {
pos += textLines[line].length+1;
}
else if(line === cLine) {
pos += cCh;
}
}
return pos;
};
var posToCursor = function(position, newText) {
var cursor = {
line: 0,
ch: 0
};
var textLines = newText.substr(0, position).split("\n");
cursor.line = textLines.length - 1;
cursor.ch = textLines[cursor.line].length;
return cursor;
};
exp.setValueAndCursor = function (oldDoc, remoteDoc, TextPatcher) {
var scroll = editor.getScrollInfo();
//get old cursor here
var oldCursor = {};
oldCursor.selectionStart = cursorToPos(editor.getCursor('from'), oldDoc);
oldCursor.selectionEnd = cursorToPos(editor.getCursor('to'), oldDoc);
editor.setValue(remoteDoc);
editor.save();
var op = TextPatcher.diff(oldDoc, remoteDoc);
var selects = ['selectionStart', 'selectionEnd'].map(function (attr) {
return TextPatcher.transformCursor(oldCursor[attr], op);
});
if(selects[0] === selects[1]) {
editor.setCursor(posToCursor(selects[0], remoteDoc));
}
else {
editor.setSelection(posToCursor(selects[0], remoteDoc), posToCursor(selects[1], remoteDoc));
}
editor.scrollTo(scroll.left, scroll.top);
};
return exp;
};
return module;
});

View File

@ -26,6 +26,7 @@ define([
var AppConfig = common.getAppConfig();
var button;
var size = "17px";
var sframeChan = common.getSframeChannel();
switch (type) {
case 'export':
button = $('<button>', {
@ -110,7 +111,7 @@ define([
console.error("Parse error while setting the title", e);
}
}
ctx.sframeChan.query('Q_SAVE_AS_TEMPLATE', {
sframeChan.query('Q_SAVE_AS_TEMPLATE', {
title: title,
toSave: toSave
}, function () {
@ -136,12 +137,12 @@ define([
button
.click(common.prepareFeedback(type))
.click(function() {
var msg = isLoggedIn() ? Messages.forgetPrompt : Messages.fm_removePermanentlyDialog;
var msg = common.isLoggedIn() ? Messages.forgetPrompt : Messages.fm_removePermanentlyDialog;
Cryptpad.confirm(msg, function (yes) {
if (!yes) { return; }
ctx.sframeChan.query('Q_MOVE_TO_TRASH', null, function (err) {
sframeChan.query('Q_MOVE_TO_TRASH', null, function (err) {
if (err) { return void callback(err); }
var cMsg = isLoggedIn() ? Messages.movedToTrash : Messages.deleted;
var cMsg = common.isLoggedIn() ? Messages.movedToTrash : Messages.deleted;
Cryptpad.alert(cMsg, undefined, true);
callback();
return;
@ -151,6 +152,13 @@ define([
});
}
break;
case 'present':
button = $('<button>', {
title: Messages.presentButtonTitle,
'class': "fa fa-play-circle cp-app-slide-present-button", // used in slide.js
style: 'font:'+size+' FontAwesome'
});
break;
case 'history':
if (!AppConfig.enableHistory) {
button = $('<span>');

View File

@ -234,7 +234,21 @@ define([
});
});
// Present mode URL
sframeChan.on('Q_PRESENT_URL_GET_VALUE', function (data, cb) {
var parsed = Cryptpad.parsePadUrl(window.location.href);
cb(parsed.hashData && parsed.hashData.present);
});
sframeChan.on('EV_PRESENT_URL_SET_VALUE', function (data) {
var parsed = Cryptpad.parsePadUrl(window.location.href);
window.location.href = parsed.getUrl({
embed: parsed.hashData.embed,
present: data
});
});
// File upload
var onFileUpload = function (sframeChan, data, cb) {
var sendEvent = function (data) {
sframeChan.event("EV_FILE_UPLOAD_STATE", data);
@ -270,6 +284,7 @@ define([
onFileUpload(sframeChan, data, cb);
});
// File picker
var FP = {};
var initFilePicker = function (types) {
var config = {};

View File

@ -1,7 +1,7 @@
define(['jquery'], function ($) {
var module = {};
module.create = function (Common, cfg, onLocal) {
module.create = function (Common, cfg) {
var exp = {};
var metadataMgr = Common.getMetadataMgr();
var sframeChan = Common.getSframeChannel();

View File

@ -8,12 +8,14 @@ define([
'/common/sframe-common-interface.js',
'/common/sframe-common-history.js',
'/common/sframe-common-file.js',
'/common/sframe-common-codemirror.js',
'/common/metadata-manager.js',
'/customize/application_config.js',
'/common/cryptpad-common.js',
'/common/common-realtime.js'
], function ($, nThen, Messages, CpNfInner, SFrameChannel, Title, UI, History, File, MetadataMgr,
], function ($, nThen, Messages, CpNfInner, SFrameChannel, Title, UI, History, File, CodeMirror,
MetadataMgr,
AppConfig, Cryptpad, CommonRealtime) {
// Chainpad Netflux Inner
@ -36,7 +38,7 @@ define([
funcs.getSframeChannel = function () { return ctx.sframeChan; };
funcs.getAppConfig = function () { return AppConfig; };
var isLoggedIn = funcs.isLoggedIn = function () {
funcs.isLoggedIn = function () {
if (!ctx.cpNfInner) { throw new Error("cpNfInner is not ready!"); }
return ctx.cpNfInner.metadataMgr.getPrivateData().accountName;
};
@ -69,12 +71,8 @@ define([
funcs.uploadFile = callWithCommon(File.uploadFile);
funcs.createFileManager = callWithCommon(File.create);
// Misc
funcs.setDisplayName = function (name, cb) {
cb = cb || $.noop;
ctx.sframeChan.query('Q_SETTINGS_SET_DISPLAY_NAME', name, cb);
};
// CodeMirror
funcs.initCodeMirrorApp = callWithCommon(CodeMirror.create);
// Window
funcs.logout = function (cb) {
@ -91,6 +89,13 @@ define([
ctx.sframeChan.query('Q_SET_LOGIN_REDIRECT', null, cb);
};
funcs.isPresentUrl = function (cb) {
ctx.sframeChan.query('Q_PRESENT_URL_GET_VALUE', null, cb);
};
funcs.setPresentUrl = function (value) {
ctx.sframeChan.event('EV_PRESENT_URL_SET_VALUE', value);
};
// Store
funcs.sendAnonRpcMsg = function (msg, content, cb) {
ctx.sframeChan.query('Q_ANON_RPC_MESSAGE', {
@ -148,6 +153,11 @@ define([
return !data.readOnly || !data.availableHashes.editHash;
};
funcs.setDisplayName = function (name, cb) {
cb = cb || $.noop;
ctx.sframeChan.query('Q_SETTINGS_SET_DISPLAY_NAME', name, cb);
};
// Friends
var pendingFriends = [];
funcs.getPendingFriends = function () {

View File

@ -109,4 +109,8 @@ define({
'Q_UPLOAD_FILE': true,
'EV_FILE_UPLOAD_STATE': true,
'Q_CANCEL_PENDING_FILE_UPLOAD': true,
// Present mode URL
'Q_PRESENT_URL_GET_VALUE': true,
'EV_PRESENT_URL_SET_VALUE': true,
});

40
www/oldslide/index.html Normal file
View File

@ -0,0 +1,40 @@
<!DOCTYPE html>
<html class="cp slide">
<head>
<title>CryptPad</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer" />
<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>
<style>
html, body {
overflow-y: hidden;
}
#iframe-container {
position: fixed;
top: 0px;
bottom: 0px;
right: 0px;
left: 0px;
padding: 0px;
}
#pad-iframe {
width:100%;
height:100%;
border:none;
margin:0;
padding:0;
overflow:hidden;
box-sizing: border-box;
}
body #pad-iframe.fullscreen {
top: 0px;
height: 100%;
}
</style>
</head>
<body>
<div id="iframe-container">
<iframe id="pad-iframe", name="pad-iframe"></iframe><script src="/common/noscriptfix.js"></script>
</div>

33
www/oldslide/inner.html Normal file
View File

@ -0,0 +1,33 @@
<!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"/>
<link rel="stylesheet" href="/bower_components/components-font-awesome/css/font-awesome.min.css">
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script async data-bootload="inner.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
<style>.loading-hidden { display: none; } </style>
</head>
<body class="loading-hidden">
<div id="bar"></div>
<!-- <textarea></textarea>-->
<div id="cme_toolbox" class="toolbar-container"></div>
<div id="editorContainer">
<textarea id="editor1" name="editor1"></textarea>
<div class="cp-app-slide-viewer slide" tabindex="2">
<div id="modal">
<div id="button_exit" class="button"><span class="fa fa-times"></span></div>
<div id="button_left" class="button"><span class="fa fa-chevron-left"></span></div>
<div id="button_right" class="button"><span class="fa fa-chevron-right"></span></div>
<div id="content"></div>
</div>
<div id="print"></div>
</div>
</div>
<div id="nope"></div>
<div id="colorPicker_check"></div>
</body>
</html>

41
www/oldslide/inner.js Normal file
View File

@ -0,0 +1,41 @@
define([
'jquery',
'cm/lib/codemirror',
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css',
'less!/customize/src/less/toolbar.less',
'less!/customize/src/less/cryptpad.less',
'less!/slide/slide.less',
'css!cm/lib/codemirror.css',
'css!cm/addon/dialog/dialog.css',
'css!cm/addon/fold/foldgutter.css',
'cm/mode/markdown/markdown',
'cm/addon/mode/loadmode',
'cm/mode/meta',
'cm/addon/mode/overlay',
'cm/addon/mode/multiplex',
'cm/addon/mode/simple',
'cm/addon/edit/closebrackets',
'cm/addon/edit/matchbrackets',
'cm/addon/edit/trailingspace',
'cm/addon/selection/active-line',
'cm/addon/search/search',
'cm/addon/search/match-highlighter',
'cm/addon/search/searchcursor',
'cm/addon/dialog/dialog',
'cm/addon/fold/foldcode',
'cm/addon/fold/foldgutter',
'cm/addon/fold/brace-fold',
'cm/addon/fold/xml-fold',
'cm/addon/fold/markdown-fold',
'cm/addon/fold/comment-fold',
'cm/addon/display/placeholder',
], function ($, CMeditor) {
window.CodeMirror = CMeditor;
$('.loading-hidden').removeClass('loading-hidden');
});

680
www/oldslide/main.js Normal file
View File

@ -0,0 +1,680 @@
define([
'jquery',
'/bower_components/chainpad-crypto/crypto.js',
'/bower_components/chainpad-netflux/chainpad-netflux.js',
'/bower_components/textpatcher/TextPatcher.js',
'/common/toolbar2.js',
'json.sortify',
'/bower_components/chainpad-json-validator/json-ot.js',
'/common/cryptpad-common.js',
'/common/cryptget.js',
'/slide/slide.js',
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less/cryptpad.less',
], function ($, Crypto, Realtime, TextPatcher, Toolbar, JSONSortify, JsonOT, Cryptpad, Cryptget, Slide) {
var Messages = Cryptpad.Messages;
var module = window.APP = {
Cryptpad: Cryptpad,
TextPatcher: TextPatcher,
Slide: Slide,
};
var APP = window.APP;
var SLIDE_BACKCOLOR_ID = "cryptpad-backcolor";
var SLIDE_COLOR_ID = "cryptpad-color";
$(function () {
Cryptpad.addLoadingScreen();
var stringify = function (obj) {
return JSONSortify(obj);
};
var ifrw = module.ifrw = $('#pad-iframe')[0].contentWindow;
var toolbar;
var editor;
var secret = Cryptpad.getSecrets();
var readOnly = secret.keys && !secret.keys.editKeyStr;
Slide.readOnly = readOnly;
if (!secret.keys) {
secret.keys = secret.key;
}
var presentMode = Slide.isPresentURL();
var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError);
};
var andThen = function (CMeditor) {
var $iframe = $('#pad-iframe').contents();
var $contentContainer = $iframe.find('#editorContainer');
var CodeMirror = Cryptpad.createCodemirror(ifrw, Cryptpad, null, CMeditor);
editor = CodeMirror.editor;
var $bar = $('#pad-iframe')[0].contentWindow.$('#cme_toolbox');
var $pad = $('#pad-iframe');
var isHistoryMode = false;
var setEditable = module.setEditable = function (bool) {
if (readOnly && bool) { return; }
editor.setOption('readOnly', !bool);
};
var Title;
var UserList;
var Metadata;
var setTabTitle = function (title) {
var slideNumber = '';
if (Slide.shown) { //Slide.index && Slide.content.length) {
slideNumber = ' (' + Slide.index + '/' + Slide.content.length + ')';
}
document.title = title + slideNumber;
};
var initialState = Messages.slideInitialState;
var $modal = $pad.contents().find('#modal');
var $content = $pad.contents().find('#content');
var $print = $pad.contents().find('#print');
var slideOptions = {};
$content.click(function (e) {
if (!e.target) { return; }
var $t = $(e.target);
if ($t.is('a') || $t.parents('a').length) {
e.preventDefault();
var $a = $t.is('a') ? $t : $t.parents('a').first();
var href = $a.attr('href');
window.open(href);
}
});
Slide.setModal($modal, $content, $pad, ifrw, slideOptions, initialState);
var enterPresentationMode = function (shouldLog) {
Slide.show(true, editor.getValue());
if (shouldLog) {
Cryptpad.log(Messages.presentSuccess);
}
};
if (presentMode) {
enterPresentationMode(true);
}
var textColor;
var backColor;
var config = {
initialState: '{}',
websocketURL: Cryptpad.getWebsocketURL(),
channel: secret.channel,
// our public key
validateKey: secret.keys.validateKey || undefined,
readOnly: readOnly,
crypto: Crypto.createEncryptor(secret.keys),
transformFunction: JsonOT.validate,
network: Cryptpad.getNetwork()
};
var canonicalize = function (t) { return t.replace(/\r\n/g, '\n'); };
var setHistory = function (bool, update) {
isHistoryMode = bool;
setEditable(!bool);
if (!bool && update) {
config.onRemote();
}
};
var initializing = true;
var stringifyInner = function (textValue) {
var obj = {
content: textValue,
metadata: {
users: UserList.userData,
defaultTitle: Title.defaultTitle,
slideOptions: slideOptions
}
};
if (!initializing) {
obj.metadata.title = Title.title;
}
if (textColor) {
obj.metadata.color = textColor;
}
if (backColor) {
obj.metadata.backColor = backColor;
}
// stringify the json and send it into chainpad
return stringify(obj);
};
var onLocal = config.onLocal = function () {
if (initializing) { return; }
if (isHistoryMode) { return; }
if (readOnly) { return; }
editor.save();
var textValue = canonicalize(CodeMirror.$textarea.val());
var shjson = stringifyInner(textValue);
module.patchText(shjson);
Slide.update(textValue);
if (module.realtime.getUserDoc() !== shjson) {
console.error("realtime.getUserDoc() !== shjson");
}
};
var metadataCfg = {
slideOptions: function (newOpt) {
if (stringify(newOpt) !== stringify(slideOptions)) {
$.extend(slideOptions, newOpt);
// TODO: manage realtime + cursor in the "options" modal ??
Slide.updateOptions();
}
}
};
var updateColors = metadataCfg.slideColors = function (text, back) {
if (text) {
textColor = text;
$modal.css('color', text);
$modal.css('border-color', text);
$pad.contents().find('#' + SLIDE_COLOR_ID).css('color', text);
}
if (back) {
backColor = back;
$modal.css('background-color', back);
//$pad.contents().find('#' + SLIDE_COLOR_ID).css('background', back);
$pad.contents().find('#' + SLIDE_BACKCOLOR_ID).css('color', back);
}
};
var createPrintDialog = function () {
var slideOptionsTmp = {
title: false,
slide: false,
date: false,
transition: true,
style: ''
};
$.extend(slideOptionsTmp, slideOptions);
var $container = $('<div class="alertify">');
var $container2 = $('<div class="dialog">').appendTo($container);
var $div = $('<div id="printOptions">').appendTo($container2);
var $p = $('<p>', {'class': 'msg'}).appendTo($div);
$('<b>').text(Messages.printOptions).appendTo($p);
$p.append($('<br>'));
// Slide number
$('<input>', {type: 'checkbox', id: 'checkNumber', checked: slideOptionsTmp.slide}).on('change', function () {
var c = this.checked;
slideOptionsTmp.slide = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'checkNumber'}).text(Messages.printSlideNumber).appendTo($p);
$p.append($('<br>'));
// Date
$('<input>', {type: 'checkbox', id: 'checkDate', checked: slideOptionsTmp.date}).on('change', function () {
var c = this.checked;
slideOptionsTmp.date = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'checkDate'}).text(Messages.printDate).appendTo($p);
$p.append($('<br>'));
// Title
$('<input>', {type: 'checkbox', id: 'checkTitle', checked: slideOptionsTmp.title}).on('change', function () {
var c = this.checked;
slideOptionsTmp.title = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'checkTitle'}).text(Messages.printTitle).appendTo($p);
$p.append($('<br>'));
// Transition
$('<input>', {type: 'checkbox', id: 'checkTransition', checked: slideOptionsTmp.transition}).on('change', function () {
var c = this.checked;
slideOptionsTmp.transition = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'checkTransition'}).text(Messages.printTransition).appendTo($p);
$p.append($('<br>'));
// CSS
$('<label>', {'for': 'cssPrint'}).text(Messages.printCSS).appendTo($p);
$p.append($('<br>'));
var $textarea = $('<textarea>', {'id':'cssPrint'}).css({'width':'100%', 'height':'100px'}).appendTo($p)
.on('keydown keyup', function (e) {
e.stopPropagation();
});
$textarea.val(slideOptionsTmp.style);
window.setTimeout(function () { $textarea.focus(); }, 0);
var h;
var todo = function () {
$.extend(slideOptions, slideOptionsTmp);
slideOptions.style = $textarea.val();
onLocal();
$container.remove();
Cryptpad.stopListening(h);
};
var todoCancel = function () {
$container.remove();
Cryptpad.stopListening(h);
};
h = Cryptpad.listenForKeys(todo, todoCancel);
var $nav = $('<nav>').appendTo($div);
$('<button>', {'class': 'cancel'}).text(Messages.cancelButton).appendTo($nav).click(todoCancel);
$('<button>', {'class': 'ok'}).text(Messages.settings_save).appendTo($nav).click(todo);
return $container;
};
config.onInit = function (info) {
UserList = Cryptpad.createUserList(info, config.onLocal, Cryptget, Cryptpad);
var titleCfg = {
updateLocalTitle: setTabTitle,
getHeadingText: CodeMirror.getHeadingText
};
Title = Cryptpad.createTitle(titleCfg, config.onLocal, Cryptpad);
Slide.setTitle(Title);
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: ifrw,
realtime: info.realtime,
network: info.network,
$container: $bar,
$contentContainer: $contentContainer
};
toolbar = module.toolbar = Toolbar.create(configTb);
Title.setToolbar(toolbar);
CodeMirror.init(config.onLocal, Title, toolbar);
var $rightside = toolbar.$rightside;
var $drawer = toolbar.$drawer;
var editHash;
if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
}
/* add a history button */
var histConfig = {
onLocal: config.onLocal,
onRemote: config.onRemote,
setHistory: setHistory,
applyVal: function (val) {
var remoteDoc = JSON.parse(val || '{}').content;
editor.setValue(remoteDoc || '');
editor.save();
},
$toolbar: $bar
};
var $hist = Cryptpad.createButton('history', true, {histConfig: histConfig});
$drawer.append($hist);
/* 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);
}
/* add an export button */
var $export = Cryptpad.createButton('export', true, {}, CodeMirror.exportText);
$drawer.append($export);
if (!readOnly) {
/* add an import button */
var $import = Cryptpad.createButton('import', true, {}, CodeMirror.importText);
$drawer.append($import);
}
/* add a forget button */
var forgetCb = function (err) {
if (err) { return; }
setEditable(false);
};
var $forgetPad = Cryptpad.createButton('forget', true, {}, forgetCb);
$rightside.append($forgetPad);
var fileDialogCfg = {
$body: $iframe.find('body'),
onSelect: function (href) {
var parsed = Cryptpad.parsePadUrl(href);
var hexFileName = Cryptpad.base64ToHex(parsed.hashData.channel);
var src = '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName;
var mt = '<media-tag src="' + src + '" data-crypto-key="cryptpad:' + parsed.hashData.key + '"></media-tag>';
editor.replaceSelection(mt);
},
data: APP
};
$('<button>', {
title: Messages.filePickerButton,
'class': 'rightside-button fa fa-picture-o',
style: 'font-size: 17px'
}).click(function () {
Cryptpad.createFileDialog(fileDialogCfg);
}).appendTo($rightside);
var $previewButton = APP.$previewButton = Cryptpad.createButton(null, true);
$previewButton.removeClass('fa-question').addClass('fa-eye');
$previewButton.attr('title', Messages.previewButtonTitle);
$previewButton.click(function () {
var $c = $iframe.find('#editorContainer');
if ($c.hasClass('preview')) {
Cryptpad.setPadAttribute('previewMode', false, function (e) {
if (e) { return console.log(e); }
});
$previewButton.removeClass('active');
return void $c.removeClass('preview');
}
Cryptpad.setPadAttribute('previewMode', true, function (e) {
if (e) { return console.log(e); }
});
$c.addClass('preview');
$previewButton.addClass('active');
Slide.updateFontSize();
});
$rightside.append($previewButton);
var $printButton = $('<button>', {
title: Messages.printButtonTitle,
'class': 'rightside-button fa fa-print',
style: 'font-size: 17px'
}).click(function () {
Slide.update(editor.getValue(), true);
$print.html($content.html());
Cryptpad.confirm("Are you sure you want to print?", function (yes) {
if (yes) {
window.frames["pad-iframe"].focus();
window.frames["pad-iframe"].print();
}
}, {ok: Messages.printButton});
Cryptpad.feedback('PRINT_SLIDES');
//$('body').append(createPrintDialog());
}).append($('<span>', {'class': 'drawer'}).text(Messages.printText));
$drawer.append($printButton);
var $slideOptions = $('<button>', {
title: Messages.slideOptionsTitle,
'class': 'rightside-button fa fa-cog',
style: 'font-size: 17px'
}).click(function () {
$('body').append(createPrintDialog());
}).append($('<span>', {'class': 'drawer'}).text(Messages.slideOptionsText));
$drawer.append($slideOptions);
var $present = Cryptpad.createButton('present', true)
.click(function () {
enterPresentationMode(true);
});
if (presentMode) {
$present.hide();
}
$rightside.append($present);
var configureColors = function () {
var $back = $('<button>', {
id: SLIDE_BACKCOLOR_ID,
'class': 'fa fa-square rightside-button',
'style': 'font-family: FontAwesome; color: #000;',
title: Messages.backgroundButtonTitle
});
var $text = $('<button>', {
id: SLIDE_COLOR_ID,
'class': 'fa fa-i-cursor rightside-button',
'style': 'font-family: FontAwesome; font-weight: bold; color: #fff;',
title: Messages.colorButtonTitle
});
var $testColor = $('<input>', { type: 'color', value: '!' });
var $check = $pad.contents().find("#colorPicker_check");
if ($testColor.attr('type') !== "color" || $testColor.val() === '!') { return; }
$back.on('click', function() {
var $picker = $('<input>', { type: 'color', value: backColor })
.css({ display: 'none', })
.on('change', function() {
updateColors(undefined, this.value);
onLocal();
});
$check.append($picker);
setTimeout(function() {
$picker.click();
}, 0);
});
$text.on('click', function() {
var $picker = $('<input>', { type: 'color', value: textColor })
.css({ display: 'none', })
.on('change', function() {
updateColors(this.value, undefined);
onLocal();
$check.html('');
});
$check.append($picker);
setTimeout(function() {
$picker.click();
}, 0);
});
$rightside.append($back).append($text);
};
configureColors();
CodeMirror.configureTheme();
if (presentMode) {
$('#top-bar').hide();
}
// set the hash
if (!window.location.hash || window.location.hash === '#') {
Cryptpad.replaceHash(editHash);
}
};
config.onReady = function (info) {
if (module.realtime !== info.realtime) {
var realtime = module.realtime = info.realtime;
module.patchText = TextPatcher.create({
realtime: realtime,
//logging: true
});
}
var userDoc = module.realtime.getUserDoc();
var isNew = false;
if (userDoc === "" || userDoc === "{}") { isNew = true; }
var newDoc = "";
if(userDoc !== "") {
var hjson = JSON.parse(userDoc);
newDoc = hjson.content;
if (typeof (hjson) !== 'object' || Array.isArray(hjson) ||
(typeof(hjson.type) !== 'undefined' && hjson.type !== 'slide')) {
var errorText = Messages.typeError;
Cryptpad.errorLoadingScreen(errorText);
throw new Error(errorText);
}
if (hjson.highlightMode) {
CodeMirror.setMode(hjson.highlightMode);
}
}
if (!CodeMirror.highlightMode) {
CodeMirror.setMode('markdown');
}
// Update the user list (metadata) from the hyperjson
Metadata.update(userDoc);
editor.setValue(newDoc || initialState);
if (Cryptpad.initialName && Title.isDefaultTitle()) {
Title.updateTitle(Cryptpad.initialName);
}
Cryptpad.getPadAttribute('previewMode', function (e, data) {
if (e) { return void console.error(e); }
if ([true, undefined].indexOf(data) !== -1 && APP.$previewButton) {
APP.$previewButton.click();
}
});
Slide.onChange(function (o, n, l) {
var slideNumber = '';
if (n !== null) {
if (Slide.shown) { //Slide.index && Slide.content.length) {
slideNumber = ' (' + (++n) + '/' + l + ')';
}
}
document.title = Title.title + slideNumber;
});
Cryptpad.removeLoadingScreen();
setEditable(true);
initializing = false;
onLocal(); // push local state to avoid parse errors later.
Slide.update(editor.getValue());
if (readOnly) { return; }
UserList.getLastName(toolbar.$userNameButton, isNew);
var fmConfig = {
dropArea: $iframe.find('.CodeMirror'),
body: $iframe.find('body'),
onUploaded: function (ev, data) {
//var cursor = editor.getCursor();
//var cleanName = data.name.replace(/[\[\]]/g, '');
//var text = '!['+cleanName+']('+data.url+')';
var parsed = Cryptpad.parsePadUrl(data.url);
var hexFileName = Cryptpad.base64ToHex(parsed.hashData.channel);
var src = '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName;
var mt = '<media-tag src="' + src + '" data-crypto-key="cryptpad:' + parsed.hashData.key + '"></media-tag>';
editor.replaceSelection(mt);
}
};
APP.FM = Cryptpad.createFileManager(fmConfig);
};
config.onRemote = function () {
if (initializing) { return; }
if (isHistoryMode) { return; }
var oldDoc = canonicalize(CodeMirror.$textarea.val());
var shjson = module.realtime.getUserDoc();
// Update the user list (metadata) from the hyperjson
Metadata.update(shjson);
var hjson = JSON.parse(shjson);
var remoteDoc = hjson.content;
var highlightMode = hjson.highlightMode;
if (highlightMode && highlightMode !== CodeMirror.highlightMode) {
CodeMirror.setMode(highlightMode);
}
CodeMirror.setValueAndCursor(oldDoc, remoteDoc, TextPatcher);
if (!readOnly) {
var textValue = canonicalize(CodeMirror.$textarea.val());
var shjson2 = stringifyInner(textValue);
if (shjson2 !== shjson) {
console.error("shjson2 !== shjson");
TextPatcher.log(shjson, TextPatcher.diff(shjson, shjson2));
module.patchText(shjson2);
}
}
Slide.update(remoteDoc);
if (oldDoc !== remoteDoc) {
Cryptpad.notify();
}
};
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);
toolbar.failed();
if (info.state) {
initializing = true;
toolbar.reconnecting(info.myId);
Cryptpad.findOKButton().click();
} else {
if (!Slide.isPresentURL()) {
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}
}
};
config.onError = onConnectError;
module.realtime = Realtime.start(config);
editor.on('change', onLocal);
Cryptpad.onLogout(function () { setEditable(false); });
};
var interval = 100;
var second = function (CM) {
Cryptpad.ready(function () {
andThen(CM);
Cryptpad.reportAppUsage();
});
Cryptpad.onError(function (info) {
if (info && info.type === "store") {
onConnectError();
}
});
};
var first = function () {
if (ifrw.CodeMirror) {
// it exists, call your continuation
second(ifrw.CodeMirror);
} else {
console.log("CodeMirror was not defined. Trying again in %sms", interval);
// try again in 'interval' ms
setTimeout(first, interval);
}
};
first();
});
});

321
www/oldslide/slide.js Normal file
View File

@ -0,0 +1,321 @@
define([
'jquery',
'/common/diffMarked.js',
'/common/cryptpad-common.js',
],function ($, DiffMd, Cryptpad) {
var Slide = {
index: 0,
lastIndex: 0,
content: [],
changeHandlers: [],
};
var ifrw;
var $modal;
var $content;
var $pad;
var placeholder;
var options;
var separator = '<hr data-pewpew="pezpez">';
var separatorReg = /<hr data\-pewpew="pezpez">/g;
var slideClass = 'slide-frame';
var Title;
Slide.onChange = function (f) {
if (typeof(f) === 'function') {
Slide.changeHandlers.push(f);
}
};
var getNumberOfSlides = Slide.getNumberOfSlides = function () {
return $content.find('.' + slideClass).length;
};
var change = function (oldIndex, newIndex) {
if (Slide.changeHandlers.length) {
Slide.changeHandlers.some(function (f) {
f(oldIndex, newIndex, getNumberOfSlides());
});
}
};
var updateFontSize = Slide.updateFontSize = function () {
// 20vh
// 20 * 16 / 9vw
var wbase = 20;
var vh = 20;
var $elem = $(window);
if (!Slide.shown) {
wbase = 10;
vh *= $content.height()/$(window).height();
$elem = $content;
}
if ($elem.width() > 16/9*$elem.height()) {
$content.css('font-size', vh+'vh');
// $print.css('font-size', '20vh');
return;
}
$content.css('font-size', (wbase*9/16)+'vw');
// $print.css('font-size', (20*9/16)+'vw');
};
var fixCSS = function (css) {
var append = '.cp #print .slide-frame ';
var append2 = '.cp div#modal #content .slide-frame ';
return css.replace(/(\n*)([^\n}]+)\s*\{/g, '$1' + append + '$2,' + append2 + '$2 {');
};
var goTo = Slide.goTo = function (i) {
i = i || 0;
Slide.index = i;
$content.find('.slide-container').first().css('margin-left', -(i*100)+'%');
updateFontSize();
change(Slide.lastIndex, Slide.index);
$modal.find('#button_left > span').css({
opacity: Slide.index === 0? 0: 1
});
$modal.find('#button_right > span').css({
opacity: Slide.index === (getNumberOfSlides() -1)? 0: 1
});
};
var draw = Slide.draw = function (i) {
if (typeof(Slide.content) !== 'string') { return; }
var c = Slide.content;
var m = '<span class="slide-container"><span class="'+slideClass+'">'+DiffMd.render(c).replace(separatorReg, '</span></span><span class="slide-container"><span class="'+slideClass+'">')+'</span></span>';
DiffMd.apply(m, $content);
var length = getNumberOfSlides();
$modal.find('style.slideStyle').remove();
if (options.style && Slide.shown) {
$modal.prepend($('<style>', {'class': 'slideStyle'}).text(fixCSS(options.style)));
}
$content.find('.slide-frame').each(function (i, el) {
if (options.slide) {
$('<div>', {'class': 'slideNumber'}).text((i+1)+'/'+length).appendTo($(el));
}
if (options.date) {
$('<div>', {'class': 'slideDate'}).text(new Date().toLocaleDateString()).appendTo($(el));
}
if (options.title) {
$('<div>', {'class': 'slideTitle'}).text(Title.title).appendTo($(el));
}
});
$content.removeClass('transition');
if (options.transition || typeof(options.transition) === "undefined") {
$content.addClass('transition');
}
//$content.find('.' + slideClass).hide();
//$content.find('.' + slideClass + ':eq( ' + i + ' )').show();
//$content.css('margin-left', -(i*100)+'vw');
goTo(Math.min(i, getNumberOfSlides() - 1));
};
Slide.updateOptions = function () {
draw(Slide.index);
};
var isPresentURL = Slide.isPresentURL = function () {
var parsed = Cryptpad.parsePadUrl(window.location.href);
return parsed && parsed.hashData && parsed.hashData.present;
};
var show = Slide.show = function (bool, content) {
var parsed = Cryptpad.parsePadUrl(window.location.href);
var hashData = parsed.hashData || {};
Slide.shown = bool;
if (bool) {
Slide.update(content);
Slide.draw(Slide.index);
$modal.addClass('shown');
$(ifrw).focus();
change(null, Slide.index);
if (!isPresentURL()) {
window.location += parsed.getUrl({present: true, embed: hashData.embed});
}
$pad.contents().find('.cryptpad-present-button').hide();
$pad.contents().find('.cryptpad-source-button').show();
$pad.addClass('fullscreen');
$('#iframe-container').addClass('fullscreen');
$('.top-bar').hide();
updateFontSize();
return;
}
window.location = parsed.getUrl({embed: hashData.embed});
change(Slide.index, null);
$pad.contents().find('.cryptpad-present-button').show();
$pad.contents().find('.cryptpad-source-button').hide();
$pad.removeClass('fullscreen');
$('#iframe-container').removeClass('fullscreen');
$('.top-bar').show();
$modal.removeClass('shown');
updateFontSize();
};
Slide.update = function (content) {
updateFontSize();
//if (!init) { return; }
if (!content) { content = ''; }
var old = Slide.content;
Slide.content = content.replace(/\n\s*\-\-\-\s*\n/g, '\n\n'+separator+'\n\n');
if (old !== Slide.content) {
draw(Slide.index);
return;
}
change(Slide.lastIndex, Slide.index);
};
Slide.left = function () {
console.log('left');
Slide.lastIndex = Slide.index;
var i = Slide.index = Math.max(0, Slide.index - 1);
Slide.goTo(i);
};
Slide.right = function () {
console.log('right');
Slide.lastIndex = Slide.index;
var i = Slide.index = Math.min(getNumberOfSlides() -1, Slide.index + 1);
Slide.goTo(i);
};
Slide.first = function () {
console.log('first');
Slide.lastIndex = Slide.index;
var i = Slide.index = 0;
Slide.goTo(i);
};
Slide.last = function () {
console.log('end');
Slide.lastIndex = Slide.index;
var i = Slide.index = getNumberOfSlides() - 1;
Slide.goTo(i);
};
var addEvent = function () {
var icon_to;
$modal.mousemove(function () {
var $buttons = $modal.find('.button');
$buttons.show();
if (icon_to) { window.clearTimeout(icon_to); }
icon_to = window.setTimeout(function() {
$buttons.fadeOut();
}, 1000);
});
$modal.find('#button_exit').click(function () {
var ev = $.Event("keyup");
ev.which = 27;
$modal.trigger(ev);
});
$modal.find('#button_left').click(function () {
var ev = $.Event("keyup");
ev.which = 37;
$modal.trigger(ev);
});
$modal.find('#button_right').click(function () {
console.log('right');
var ev = $.Event("keyup");
ev.which = 39;
$modal.trigger(ev);
});
$pad.contents().find('.CodeMirror').keyup(function (e) { e.stopPropagation(); });
$(ifrw).on('keyup', function (e) {
//if (!Slide.shown) { return; }
if (e.ctrlKey) { return; }
switch(e.which) {
case 33: // pageup
case 38: // up
case 37: // left
Slide.left();
break;
case 34: // pagedown
case 32: // space
case 40: // down
case 39: // right
Slide.right();
break;
case 36: // home
Slide.first();
break;
case 35: // end
Slide.last();
break;
case 27: // esc
show(false);
break;
default:
console.log(e.which);
}
});
};
$(window).resize(Slide.updateFontSize);
// Swipe
var addSwipeEvents = function () {
var touch = {
maxTime: 2000,
minXDist: 150,
maxYDist: 100
};
var resetSwipe = function () {
touch.x = 0;
touch.y = 0;
touch.time = 0;
};
$content.on('touchstart', function (e) {
e.preventDefault();
resetSwipe();
var t = e.originalEvent.changedTouches[0];
touch.x = t.pageX;
touch.y = t.pageY;
touch.time = new Date().getTime();
});
$content.on('touchend', function (e) {
e.preventDefault();
var t = e.originalEvent.changedTouches[0];
var xDist = t.pageX - touch.x;
var yDist = t.pageY - touch.y;
var time = new Date().getTime() - touch.time;
if (time <= touch.maxTime && Math.abs(xDist) >= touch.minXDist && Math.abs(yDist) <= touch.maxYDist) {
if (xDist < 0) {
Slide.right();
return;
}
Slide.left();
}
});
$content.on('touchmove', function (e){
e.preventDefault();
});
};
Slide.setModal = function ($m, $c, $p, iframe, opt, ph) {
$modal = Slide.$modal = $m;
$content = Slide.$content = $c;
$pad = Slide.$pad = $p;
ifrw = Slide.ifrw = iframe;
placeholder = Slide.placeholder = ph;
options = Slide.options = opt;
addEvent();
addSwipeEvents();
};
Slide.setTitle = function (titleObj) {
Title = titleObj;
};
return Slide;
});

View File

@ -149,20 +149,21 @@ define([
}).on('change', function () {
var val = parseInt($input.val());
if (typeof(val) !== 'number') { return; }
proxy.settings.indentUnit = val;
Cryptpad.setAttribute(['codemirror', 'indentUnit'], val);
}).appendTo($inputBlock);
proxy.on('change', [ 'settings', 'indentUnit', ], function (o, n) { $input.val(n); });
proxy.on('change', [ 'settings', 'codemirror', 'indentUnit', ], function (o, n) {
$input.val(n);
});
//Cryptpad.getAttribute('indentUnit', function (e, val) {
//if (e) { return void console.error(e); }
var val = proxy.settings.indentUnit;
Cryptpad.getAttribute(['codemirror', 'indentUnit'], function (e, val) {
if (e) { return void console.error(e); }
if (typeof(val) !== 'number') {
$input.val(2);
} else {
$input.val(val);
}
//});
});
return $div;
};
@ -187,12 +188,18 @@ define([
}).on('change', function () {
var val = $input.is(':checked');
if (typeof(val) !== 'boolean') { return; }
proxy.settings[key] = val;
Cryptpad.setAttribute(['codemirror', key], val);
}).appendTo($inputBlock);
$input[0].checked = !!proxy.settings[key];
proxy.on('change', ['settings', key], function (o, n) { $input[0].checked = !!n; });
proxy.on('change', ['settings', 'codemirror', key], function (o, n) {
$input[0].checked = !!n;
});
Cryptpad.getAttribute(['codemirror', key], function (e, val) {
if (e) { return void console.error(e); }
$input[0].checked = !!val;
});
return $div;
};

323
www/slide/app-slide.less Normal file
View File

@ -0,0 +1,323 @@
@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';
@import (once) "../../customize/src/less2/include/mediatag.less";
.mediatag_base();
.toolbar_main();
.fileupload_main();
.alertify_main();
// body
font-size: unset;
display: flex;
flex-flow: column;
@slide-default-bg: #000;
.size (@n) {
// font-size: @n * 1vmin;
// line-height: @n * 1.1vmin;
font-size: @n * 10%;
// line-height: @n * 11%;
line-height: 110%;
}
h1 { font-size: 40px; }
h2 { font-size: 37px; }
h3 { font-size: 34px; }
h4 { font-size: 31px; }
h5 { font-size: 27px; }
h6 { font-size: 24px; }
.CodeMirror {
height: 100%;
font-size: initial;
}
.CodeMirror-focused .cm-matchhighlight {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFklEQVQI12NgYGBgkKzc8x9CMDAwAAAmhwSbidEoSQAAAABJRU5ErkJggg==);
background-position: bottom;
background-repeat: repeat-x;
}
#cp-app-slide-colorpicker {
display: block;
}
#cme_toolbox {
z-index: 10000;
}
#cp-app-slide-editor {
flex: 1;
display: flex;
flex-flow: row;
height: 100%;
overflow: hidden;
.CodeMirror {
resize: none;
width: 100vw;
}
&.cp-app-slide-preview {
.CodeMirror {
//resize: horizontal;
width: 50vw;
}
}
}
.cp-app-slide-preview {
.cp-app-slide-viewer {
width: 50vw;
overflow: hidden;
div#cp-app-slide-modal:not(.cp-app-slide-shown) {
position: relative;
top: auto;
left: auto;
width: auto;
display: block;
height: 100%;
#cp-app-slide-modal-content {
.cp-app-slide-container {
width: 100%;
}
.cp-app-slide-frame {
width: 50vw;
height: 28.125vw; // height:width ratio = 9/16 = .5625
max-height: ~"calc(100vh - 96px)";
max-width: ~"calc(16 / 9 * (100vh - 96px))";
//max-height: 100vh;
//max-width: 177.78vh; // 16/9 = 1.778
}
}
#cp-app-slide-modal-exit {
visibility: hidden;
}
}
}
.CodeMirror {
flex: 1;
}
}
/* Slide position (print mode) */
@ratio:0.9;
#cp-app-slide-print {
position: relative;
display: none;
font-size: @ratio*11.25vw;
.cp-app-slide-frame {
display: flex !important;
flex-flow: column;
padding: 0.5em;
margin: auto;
border: 1px solid black;
height: @ratio*56.25vw;
width: @ratio*100vw;
page-break-after: always;
position: relative;
box-sizing: border-box;
overflow: hidden;
li {
min-width: @ratio*50vw;
}
h1 {
padding-top: 0;
}
}
.cp-app-slide-container {
width: 90vw;
height: 100vh;
margin: 0vh 5vw !important;
display: flex;
&:last-child {
height: ~"calc(100vh - 2px)";
}
}
}
/* Slide position (present mode) */
div#cp-app-slide-modal {
display: none;
background-color: black;
color: white;
/* Navigation buttons */
.cp-app-slide-modal-button {
position: absolute;
cursor: pointer;
font-size: 30px;
opacity: 0.6;
display: none;
z-index: 9001;
}
.cp-app-slie-modal-button:hover {
opacity: 1;
display: block !important;
}
#cp-app-slide-modal-exit {
left: 20px;
top: 20px;
}
#cp-app-slide-modal-left {
left: 6vw;
bottom: 10vh;
}
#cp-app-slide-modal-right {
right: 6vw;
bottom: 10vh;
}
&.cp-app-slide-shown {
display: block;
position: fixed;
top: 0px;
left: 0px;
z-index: 100000;
height: 100vh;
width: 100%;
}
#cp-app-slide-modal-content {
font-size: 20vh;
position: relative;
height: 100%;
overflow: visible;
white-space: nowrap;
.cp-app-slide-frame {
overflow: hidden;
display: flex;
flex-flow: column !important;
box-sizing: border-box;
border: 1px solid;
white-space: normal;
vertical-align: middle;
padding: 0.5em;
width: 100vw;
height: 56.25vw; // height:width ratio = 9/16 = .5625
max-height: 100vh;
max-width: 177.78vh; // 16/9 = 1.778
margin: auto;
}
.cp-app-slide-container {
display: inline-flex;
height: 100%; width: 100vw;
text-align: center;
vertical-align: top;
}
&.cp-app-slide-transition {
.cp-app-slide-container {
transition: margin-left 1s;
}
}
media-tag button {
max-height: none;
}
}
box-sizing: border-box;
z-index: 9001;
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100vh;
display: none;
background-color: @slide-default-bg;
}
/* Slide content */
div#cp-app-slide-modal #cp-app-slide-modal-content, #cp-app-slide-print {
.cp-app-slide-frame {
* {
.size(2.75);
* {
font-size: 1em;
line-height: 1em;
}
}
ul, ol {
ul, ol {
margin: 0;
}
}
h1 { .size(5); }
h2 { .size(4.2); }
h3 { .size(3.6); }
h4 { .size (3); }
h5 { .size(2.2); }
h6 { .size(1.6); }
h1, h2, h3, h4, h5, h6 {
color: inherit;
text-align: center;
padding-top: 0;
margin-bottom: 0.5em;
}
.markdown_preformatted-code;
ul, ol {
min-width: 50%;
max-width: 100%;
display: table;
margin: 0 auto;
padding-left: 0.3em;
}
// fixes image overflowing
media-tag {
height: 100%;
& + * {
margin-top: 1rem;
}
}
img {
position: relative;
min-width: 1%;
margin: auto;
}
.cp-app-slide-number {
position: absolute;
right: 5vh;
bottom: 5vh;
.size(1);
}
.cp-app-slide-date {
position: absolute;
left: 5vh;
bottom: 5vh;
.size(1);
}
.cp-app-slide-title {
position: absolute;
bottom: 5vh;
left: 0px; right: 0px;
text-align: center;
.size(1);
}
text-align: left;
position: relative;
}
}
.cp-app-slide-frame * {
max-width: 100%;
max-height: 100%;
}
p {
padding: 0;
margin: 0;
min-height:0;
min-width:0;
}

View File

@ -1,40 +1,38 @@
<!DOCTYPE html>
<html class="cp slide">
<html>
<head>
<title>CryptPad</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer" />
<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>
<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 {
overflow-y: hidden;
}
#iframe-container {
position: fixed;
top: 0px;
bottom: 0px;
right: 0px;
left: 0px;
margin: 0px;
padding: 0px;
}
#pad-iframe {
#sbox-iframe {
position:fixed;
top:0px;
left:0px;
bottom:0px;
right:0px;
width:100%;
height:100%;
border:none;
margin:0;
padding:0;
overflow:hidden;
box-sizing: border-box;
}
body #pad-iframe.fullscreen {
top: 0px;
#sbox-filePicker-iframe {
position: fixed;
top:0; left:0;
bottom:0; right:0;
width:100%;
height: 100%;
border: 0;
}
</style>
</style>
</head>
<body>
<div id="iframe-container">
<iframe id="pad-iframe", name="pad-iframe"></iframe><script src="/common/noscriptfix.js"></script>
</div>
<iframe id="sbox-iframe">

View File

@ -1,33 +1,34 @@
<!DOCTYPE html>
<html>
<html class="cp-app-noscroll cp-app-print">
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="/bower_components/components-font-awesome/css/font-awesome.min.css">
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script async data-bootload="inner.js" data-main="/common/boot.js?ver=1.0" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
<style>.loading-hidden { display: none; } </style>
<script async data-bootload="/slide/inner.js" data-main="/common/sframe-boot.js?ver=1.1" src="/bower_components/requirejs/require.js?ver=2.3.5"></script>
<style>
.loading-hidden { display: none; }
#editor1 { display: none; }
</style>
</head>
<body class="loading-hidden">
<div id="bar"></div>
<!-- <textarea></textarea>-->
<div id="cme_toolbox" class="toolbar-container"></div>
<div id="editorContainer">
<body class="cp-app-slide">
<div id="cme_toolbox" class="cp-toolbar-container"></div>
<div id="cp-app-slide-editor">
<textarea id="editor1" name="editor1"></textarea>
<div class="cp slide" tabindex="2">
<div id="modal">
<div id="button_exit" class="button"><span class="fa fa-times"></span></div>
<div id="button_left" class="button"><span class="fa fa-chevron-left"></span></div>
<div id="button_right" class="button"><span class="fa fa-chevron-right"></span></div>
<div id="content"></div>
<div class="cp-app-slide-viewer" tabindex="2">
<div id="cp-app-slide-modal">
<div id="cp-app-slide-modal-exit" class="cp-app-slide-modal-button">
<span class="fa fa-times"></span>
</div>
<div id="cp-app-slide-modal-left" class="cp-app-slide-modal-button">
<span class="fa fa-chevron-left"></span>
</div>
<div id="cp-app-slide-modal-right" class="cp-app-slide-modal-button">
<span class="fa fa-chevron-right"></span>
</div>
<div id="cp-app-slide-modal-content"></div>
</div>
<div id="print"></div>
<div id="cp-app-slide-print"></div>
</div>
</div>
<div id="nope"></div>
<div id="colorPicker_check"></div>
<div id="cp-app-slide-colorpicker"></div>
</body>
</html>

View File

@ -1,13 +1,24 @@
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',
'/common/diffMarked.js',
'/bower_components/nthen/index.js',
'/common/sframe-common.js',
'/api/config',
'/common/common-realtime.js',
'/slide/slide.js',
'cm/lib/codemirror',
'css!/bower_components/bootstrap/dist/css/bootstrap.min.css',
'less!/customize/src/less/toolbar.less',
'less!/customize/src/less/cryptpad.less',
'less!/slide/slide.less',
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less2/main.less',
'css!cm/lib/codemirror.css',
'css!cm/addon/dialog/dialog.css',
@ -35,7 +46,701 @@ define([
'cm/addon/fold/comment-fold',
'cm/addon/display/placeholder',
], function ($, CMeditor) {
], function (
$,
Crypto,
TextPatcher,
Toolbar,
JSONSortify,
JsonOT,
Cryptpad,
Cryptget,
DiffMd,
nThen,
SFCommon,
ApiConfig,
CommonRealtime,
Slide,
CMeditor)
{
window.CodeMirror = CMeditor;
$('.loading-hidden').removeClass('loading-hidden');
var Messages = Cryptpad.Messages;
var APP = window.APP = {
Cryptpad: Cryptpad,
};
var SLIDE_BACKCOLOR_ID = "cp-app-slide-toolbar-backcolor";
var SLIDE_COLOR_ID = "cp-app-slide-toolbar-color";
var stringify = function (obj) {
return JSONSortify(obj);
};
var toolbar;
var isPresentMode;
var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError);
};
var andThen = function (editor, CodeMirror, common) {
var readOnly = false;
var cpNfInner;
var metadataMgr;
var $bar = $('#cme_toolbox');
var isHistoryMode = false;
var setEditable = APP.setEditable = function (bool) {
if (readOnly && bool) { return; }
editor.setOption('readOnly', !bool);
};
var Title;
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 canonicalize = function (t) { return t.replace(/\r\n/g, '\n'); };
var setHistory = function (bool, update) {
isHistoryMode = bool;
setEditable(!bool);
if (!bool && update) {
config.onRemote();
}
};
var setTabTitle = function (title) {
console.error('TODO'); // TODO iframe
return;
var slideNumber = '';
if (Slide.shown) { //Slide.index && Slide.content.length) {
slideNumber = ' (' + Slide.index + '/' + Slide.content.length + ')';
}
document.title = title + slideNumber;
};
var $contentContainer = $('#cp-app-slide-editor');
var $modal = $('#cp-app-slide-modal');
var $content = $('#cp-app-slide-modal-content');
var $print = $('#cp-app-slide-print');
var slideOptions = {};
var initialState = Messages.slideInitialState;
var textColor;
var backColor;
$content.click(function (e) {
if (!e.target) { return; }
var $t = $(e.target);
if ($t.is('a') || $t.parents('a').length) {
e.preventDefault();
var $a = $t.is('a') ? $t : $t.parents('a').first();
var href = $a.attr('href');
window.open(href);
}
});
Slide.setModal(common, $modal, $content, slideOptions, initialState);
var enterPresentationMode = function (shouldLog) {
Slide.show(true, editor.getValue());
if (shouldLog) {
Cryptpad.log(Messages.presentSuccess);
}
};
if (isPresentMode) {
enterPresentationMode(true);
}
CommonRealtime.onInfiniteSpinner(function () { setEditable(false); });
setEditable(false);
var initializing = true;
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 (isHistoryMode) { return; }
if (readOnly) { return; }
editor.save();
var textValue = canonicalize(CodeMirror.$textarea.val());
var shjson = stringifyInner(textValue);
APP.patchText(shjson);
Slide.update(textValue);
if (APP.realtime.getUserDoc() !== shjson) {
console.error("realtime.getUserDoc() !== shjson");
}
};
var updateSlideOptions = function (newOpt) {
if (stringify(newOpt) !== stringify(slideOptions)) {
$.extend(slideOptions, newOpt);
// TODO: manage realtime + cursor in the "options" modal ??
Slide.updateOptions();
}
};
var updateLocalOptions = function (newOpt) {
updateSlideOptions(newOpt);
var metadata = JSON.parse(JSON.stringify(metadataMgr.getMetadata()));
metadata.slideOptions = slideOptions;
metadataMgr.updateMetadata(metadata);
onLocal();
};
var updateColors = function (text, back) {
if (text) {
textColor = text;
$modal.css('color', text);
$modal.css('border-color', text);
$('#' + SLIDE_COLOR_ID).css('color', text);
}
if (back) {
backColor = back;
$modal.css('background-color', back);
$('#' + SLIDE_BACKCOLOR_ID).css('color', back);
}
};
var updateLocalColors = function (text, back) {
updateColors(text, back);
var metadata = JSON.parse(JSON.stringify(metadataMgr.getMetadata()));
if (backColor) { metadata.backColor = backColor; }
if (textColor) { metadata.color = textColor; }
metadataMgr.updateMetadata(metadata);
onLocal();
console.log(metadataMgr.getMetadata());
};
var createPrintDialog = function () {
var slideOptionsTmp = {
title: false,
slide: false,
date: false,
transition: true,
style: ''
};
$.extend(slideOptionsTmp, slideOptions);
var $container = $('<div class="alertify">');
var $container2 = $('<div class="dialog">').appendTo($container);
var $div = $('<div id="printOptions">').appendTo($container2);
var $p = $('<p>', {'class': 'msg'}).appendTo($div);
$('<b>').text(Messages.printOptions).appendTo($p);
$p.append($('<br>'));
// Slide number
$('<input>', {
type: 'checkbox',
id: 'cp-app-slide-options-number',
checked: slideOptionsTmp.slide
}).on('change', function () {
var c = this.checked;
slideOptionsTmp.slide = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'cp-app-slide-options-number'}).text(Messages.printSlideNumber)
.appendTo($p);
$p.append($('<br>'));
// Date
$('<input>', {
type: 'checkbox',
id: 'cp-app-slide-options-date',
checked: slideOptionsTmp.date
}).on('change', function () {
var c = this.checked;
slideOptionsTmp.date = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'cp-app-slide-options-date'}).text(Messages.printDate)
.appendTo($p);
$p.append($('<br>'));
// Title
$('<input>', {
type: 'checkbox',
id: 'cp-app-slide-options-title',
checked: slideOptionsTmp.title
}).on('change', function () {
var c = this.checked;
slideOptionsTmp.title = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'cp-app-slide-options-title'}).text(Messages.printTitle)
.appendTo($p);
$p.append($('<br>'));
// Transition
$('<input>', {
type: 'checkbox',
id: 'cp-app-slide-options-transition',
checked: slideOptionsTmp.transition
}).on('change', function () {
var c = this.checked;
slideOptionsTmp.transition = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'cp-app-slide-options-transition'}).text(Messages.printTransition)
.appendTo($p);
$p.append($('<br>'));
// CSS
$('<label>', {'for': 'cp-app-slide-options-css'}).text(Messages.printCSS).appendTo($p);
$p.append($('<br>'));
var $textarea = $('<textarea>', {'id':'cp-app-slide-options-css'})
.css({'width':'100%', 'height':'100px'}).appendTo($p)
.on('keydown keyup', function (e) {
e.stopPropagation();
});
$textarea.val(slideOptionsTmp.style);
window.setTimeout(function () { $textarea.focus(); }, 0);
var h;
var todo = function () {
slideOptionsTmp.style = $textarea.val();
updateLocalOptions(slideOptionsTmp);
$container.remove();
Cryptpad.stopListening(h);
};
var todoCancel = function () {
$container.remove();
Cryptpad.stopListening(h);
};
h = Cryptpad.listenForKeys(todo, todoCancel);
var $nav = $('<nav>').appendTo($div);
$('<button>', {'class': 'cancel'}).text(Messages.cancelButton).appendTo($nav).click(todoCancel);
$('<button>', {'class': 'ok'}).text(Messages.settings_save).appendTo($nav).click(todo);
return $container;
};
config.onInit = function (info) {
readOnly = metadataMgr.getPrivateData().readOnly;
var titleCfg = { getHeadingText: CodeMirror.getHeadingText };
Title = common.createTitle(titleCfg, config.onLocal);
Slide.setTitle(Title);
var configTb = {
displayed: ['title', 'useradmin', 'spinner', 'share', 'userlist', 'newpad', 'limit'],
title: Title.getTitleConfig(),
metadataMgr: metadataMgr,
readOnly: readOnly,
ifrw: window,
realtime: info.realtime,
common: Cryptpad,
sfCommon: common,
$container: $bar,
$contentContainer: $contentContainer
};
toolbar = APP.toolbar = Toolbar.create(configTb);
Title.setToolbar(toolbar);
CodeMirror.init(config.onLocal, Title, toolbar);
var $rightside = toolbar.$rightside;
var $drawer = toolbar.$drawer;
/* add a history button */
var histConfig = {
onLocal: config.onLocal,
onRemote: config.onRemote,
setHistory: setHistory,
applyVal: function (val) {
var remoteDoc = JSON.parse(val || '{}').content;
editor.setValue(remoteDoc || '');
editor.save();
},
$toolbar: $bar
};
var $hist = common.createButton('history', true, {histConfig: histConfig});
$drawer.append($hist);
/* 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, {}, CodeMirror.exportText);
$drawer.append($export);
if (!readOnly) {
/* add an import button */
var $import = common.createButton('import', true, {}, CodeMirror.importText);
$drawer.append($import);
}
/* add a forget button */
var forgetCb = function (err) {
if (err) { return; }
setEditable(false);
};
var $forgetPad = common.createButton('forget', true, {}, forgetCb);
$rightside.append($forgetPad);
var $previewButton = APP.$previewButton = common.createButton(null, true);
$previewButton.removeClass('fa-question').addClass('fa-eye');
$previewButton.attr('title', Messages.previewButtonTitle);
$previewButton.click(function () {
var $c = $contentContainer;
if ($c.hasClass('cp-app-slide-preview')) {
common.setPadAttribute('previewMode', false, function (e) {
if (e) { return console.log(e); }
});
$previewButton.removeClass('cp-toolbar-button-active');
return void $c.removeClass('cp-app-slide-preview');
}
common.setPadAttribute('previewMode', true, function (e) {
if (e) { return console.log(e); }
});
$c.addClass('cp-app-slide-preview');
$previewButton.addClass('cp-toolbar-button-active');
Slide.updateFontSize();
});
$rightside.append($previewButton);
var $printButton = $('<button>', {
title: Messages.printButtonTitle,
'class': 'cp-toolbar-rightside-button fa fa-print',
style: 'font-size: 17px'
}).click(function () {
Slide.update(editor.getValue(), true);
$print.html($content.html());
// TODO use translation key
Cryptpad.confirm("Are you sure you want to print?", function (yes) {
if (yes) {
window.focus();
window.print();
}
}, {ok: Messages.printButton});
common.feedback('PRINT_SLIDES');
}).append($('<span>', {'class': 'cp-toolbar-drawer-element'}).text(Messages.printText));
$drawer.append($printButton);
var $slideOptions = $('<button>', {
title: Messages.slideOptionsTitle,
'class': 'cp-toolbar-rightside-button fa fa-cog',
style: 'font-size: 17px'
}).click(function () {
$('body').append(createPrintDialog());
}).append($('<span>', {'class': 'cp-toolbar-drawer-element'}).text(Messages.slideOptionsText));
$drawer.append($slideOptions);
var $present = common.createButton('present', true)
.click(function () {
enterPresentationMode(true);
});
$rightside.append($present);
var configureColors = function () {
var $back = $('<button>', {
id: SLIDE_BACKCOLOR_ID,
'class': 'fa fa-square cp-toolbar-rightside-button',
'style': 'font-family: FontAwesome; color: #000;',
title: Messages.backgroundButtonTitle
});
var $text = $('<button>', {
id: SLIDE_COLOR_ID,
'class': 'fa fa-i-cursor cp-toolbar-rightside-button',
'style': 'font-family: FontAwesome; font-weight: bold; color: #fff;',
title: Messages.colorButtonTitle
});
var $testColor = $('<input>', { type: 'color', value: '!' });
var $check = $("#cp-app-slide-colorpicker");
if ($testColor.attr('type') !== "color" || $testColor.val() === '!') { return; }
$back.on('click', function() {
var $picker = $('<input>', { type: 'color', value: backColor })
.css({ display: 'none', })
.on('change', function() {
updateLocalColors(undefined, this.value);
$check.html('');
});
$check.append($picker);
setTimeout(function() {
$picker.click();
}, 0);
});
$text.on('click', function() {
var $picker = $('<input>', { type: 'color', value: textColor })
.css({ display: 'none', })
.on('change', function() {
updateLocalColors(this.value, undefined);
$check.html('');
});
$check.append($picker);
setTimeout(function() {
$picker.click();
}, 0);
});
$rightside.append($back).append($text);
};
configureColors();
CodeMirror.configureTheme();
var fileDialogCfg = {
onSelect: function (data) {
if (data.type === 'file') {
var mt = '<media-tag src="' + data.src + '" data-crypto-key="cryptpad:' + data.key + '"></media-tag>';
editor.replaceSelection(mt);
return;
}
}
};
common.initFilePicker(fileDialogCfg);
APP.$mediaTagButton = $('<button>', {
title: Messages.filePickerButton,
'class': 'cp-toolbar-rightside-button fa fa-picture-o',
style: 'font-size: 17px'
}).click(function () {
var pickerCfg = {
types: ['file'],
where: ['root']
};
common.openFilePicker(pickerCfg);
}).appendTo($rightside);
metadataMgr.onChange(function () {
var md = metadataMgr.getMetadata();
if (md.color || md.backColor) {
updateLocalColors(md.color, md.backColor);
}
if (md.slideOptions) {
updateLocalOptions(md.slideOptions);
}
});
};
config.onReady = function (info) {
console.log('onready');
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) ||
(typeof(hjson.type) !== 'undefined' && hjson.type !== 'code')) {
var errorText = Messages.typeError;
Cryptpad.errorLoadingScreen(errorText);
throw new Error(errorText);
}
newDoc = hjson.content;
if (hjson.highlightMode) {
CodeMirror.setMode(hjson.highlightMode);
}
} else {
Title.updateTitle(Cryptpad.initialName || Title.defaultTitle);
}
if (!CodeMirror.highlightMode) {
CodeMirror.setMode('markdown');
}
editor.setValue(newDoc || initialState);
if (Cryptpad.initialName && Title.isDefaultTitle()) {
Title.updateTitle(Cryptpad.initialName);
}
common.getPadAttribute('previewMode', function (e, data) {
if (e) { return void console.error(e); }
if (data !== false && APP.$previewButton) {
APP.$previewButton.click();
}
});
Slide.onChange(function (o, n, l) {
console.log('TODO: remove that part?');
var slideNumber = '';
if (n !== null) {
if (Slide.shown) {
slideNumber = ' (' + (++n) + '/' + l + ')';
}
}
// TODO iframe
document.title = Title.title + slideNumber;
});
setEditable(!readOnly);
initializing = false;
onLocal(); // push local state to avoid parse errors later.
console.log(editor.getValue());
Slide.update(editor.getValue());
Cryptpad.removeLoadingScreen();
if (readOnly) {
config.onRemote();
return;
}
if (isNew) {
common.openTemplatePicker();
}
var fmConfig = {
dropArea: $('.CodeMirror'),
body: $('body'),
onUploaded: function (ev, data) {
var parsed = Cryptpad.parsePadUrl(data.url);
var hexFileName = Cryptpad.base64ToHex(parsed.hashData.channel);
var src = '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName;
var mt = '<media-tag src="' + src + '" data-crypto-key="cryptpad:' + parsed.hashData.key + '"></media-tag>';
editor.replaceSelection(mt);
}
};
APP.FM = common.createFileManager(fmConfig);
};
config.onRemote = function () {
if (initializing) { return; }
if (isHistoryMode) { return; }
var oldDoc = canonicalize(CodeMirror.$textarea.val());
var shjson = APP.realtime.getUserDoc();
var hjson = JSON.parse(shjson);
var remoteDoc = hjson.content;
if (hjson.metadata) {
metadataMgr.updateMetadata(hjson.metadata);
}
var highlightMode = hjson.highlightMode;
if (highlightMode && highlightMode !== APP.highlightMode) {
CodeMirror.setMode(highlightMode);
}
CodeMirror.setValueAndCursor(oldDoc, remoteDoc, TextPatcher);
if (!readOnly) {
var textValue = canonicalize(CodeMirror.$textarea.val());
var shjson2 = stringifyInner(textValue);
if (shjson2 !== shjson) {
console.error("shjson2 !== shjson");
TextPatcher.log(shjson, TextPatcher.diff(shjson, shjson2));
APP.patchText(shjson2);
}
}
Slide.update(remoteDoc);
if (oldDoc !== remoteDoc) { Cryptpad.notify(); }
};
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);
//toolbar.failed();
if (info.state) {
initializing = true;
//toolbar.reconnecting(info.myId);
Cryptpad.findOKButton().click();
} else {
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}
};
config.onError = onConnectError;
cpNfInner = common.startRealtime(config);
metadataMgr = cpNfInner.metadataMgr;
editor.on('change', onLocal);
Cryptpad.onLogout(function () { setEditable(false); });
};
var CMEDITOR_CHECK_INTERVAL = 100;
var cmEditorAvailable = function (cb) {
var intr;
var check = function () {
if (window.CodeMirror) {
clearTimeout(intr);
cb(window.CodeMirror);
}
};
intr = setInterval(function () {
console.log("CodeMirror was not defined. Trying again in %sms", CMEDITOR_CHECK_INTERVAL);
check();
}, CMEDITOR_CHECK_INTERVAL);
check();
};
var main = function () {
var CM;
var CodeMirror;
var editor;
var common;
nThen(function (waitFor) {
cmEditorAvailable(waitFor(function (cm) {
CM = cm;
}));
$(waitFor(function () {
Cryptpad.addLoadingScreen();
}));
SFCommon.create(waitFor(function (c) { APP.common = common = c; }));
}).nThen(function (/*waitFor*/) {
CodeMirror = common.initCodeMirrorApp(null, CM);
$('.CodeMirror').addClass('fullPage');
editor = CodeMirror.editor;
Cryptpad.onError(function (info) {
if (info && info.type === "store") {
onConnectError();
}
});
common.isPresentUrl(function (err, val) {
isPresentMode = val;
andThen(editor, CodeMirror, common);
});
});
};
main();
});

View File

@ -1,680 +1,41 @@
// Load #1, load as little as possible because we are in a race to get the loading screen up.
define([
'/bower_components/nthen/index.js',
'/api/config',
'jquery',
'/bower_components/chainpad-crypto/crypto.js',
'/bower_components/chainpad-netflux/chainpad-netflux.js',
'/bower_components/textpatcher/TextPatcher.js',
'/common/toolbar2.js',
'json.sortify',
'/bower_components/chainpad-json-validator/json-ot.js',
'/common/cryptpad-common.js',
'/common/cryptget.js',
'/slide/slide.js',
'/common/requireconfig.js',
'/common/sframe-common-outer.js'
], function (nThen, ApiConfig, $, RequireConfig, SFCommonO) {
var requireConfig = RequireConfig();
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less/cryptpad.less',
], function ($, Crypto, Realtime, TextPatcher, Toolbar, JSONSortify, JsonOT, Cryptpad, Cryptget, Slide) {
var Messages = Cryptpad.Messages;
var module = window.APP = {
Cryptpad: Cryptpad,
TextPatcher: TextPatcher,
Slide: Slide,
};
var APP = window.APP;
var SLIDE_BACKCOLOR_ID = "cryptpad-backcolor";
var SLIDE_COLOR_ID = "cryptpad-color";
$(function () {
Cryptpad.addLoadingScreen();
var stringify = function (obj) {
return JSONSortify(obj);
// Loaded in load #2
nThen(function (waitFor) {
$(waitFor());
}).nThen(function (waitFor) {
var req = {
cfg: requireConfig,
req: [ '/common/loading.js' ],
pfx: window.location.origin
};
var ifrw = module.ifrw = $('#pad-iframe')[0].contentWindow;
var toolbar;
var editor;
window.rc = requireConfig;
window.apiconf = ApiConfig;
$('#sbox-iframe').attr('src',
ApiConfig.httpSafeOrigin + '/slide/inner.html?' + requireConfig.urlArgs +
'#' + encodeURIComponent(JSON.stringify(req)));
var secret = Cryptpad.getSecrets();
var readOnly = secret.keys && !secret.keys.editKeyStr;
Slide.readOnly = readOnly;
if (!secret.keys) {
secret.keys = secret.key;
}
var presentMode = Slide.isPresentURL();
var onConnectError = function () {
Cryptpad.errorLoadingScreen(Messages.websocketError);
// This is a cheap trick to avoid loading sframe-channel in parallel with the
// loading screen setup.
var done = waitFor();
var onMsg = function (msg) {
var data = JSON.parse(msg.data);
if (data.q !== 'READY') { return; }
window.removeEventListener('message', onMsg);
var _done = done;
done = function () { };
_done();
};
var andThen = function (CMeditor) {
var $iframe = $('#pad-iframe').contents();
var $contentContainer = $iframe.find('#editorContainer');
var CodeMirror = Cryptpad.createCodemirror(ifrw, Cryptpad, null, CMeditor);
editor = CodeMirror.editor;
var $bar = $('#pad-iframe')[0].contentWindow.$('#cme_toolbox');
var $pad = $('#pad-iframe');
var isHistoryMode = false;
var setEditable = module.setEditable = function (bool) {
if (readOnly && bool) { return; }
editor.setOption('readOnly', !bool);
};
var Title;
var UserList;
var Metadata;
var setTabTitle = function (title) {
var slideNumber = '';
if (Slide.shown) { //Slide.index && Slide.content.length) {
slideNumber = ' (' + Slide.index + '/' + Slide.content.length + ')';
}
document.title = title + slideNumber;
};
var initialState = Messages.slideInitialState;
var $modal = $pad.contents().find('#modal');
var $content = $pad.contents().find('#content');
var $print = $pad.contents().find('#print');
var slideOptions = {};
$content.click(function (e) {
if (!e.target) { return; }
var $t = $(e.target);
if ($t.is('a') || $t.parents('a').length) {
e.preventDefault();
var $a = $t.is('a') ? $t : $t.parents('a').first();
var href = $a.attr('href');
window.open(href);
}
});
Slide.setModal($modal, $content, $pad, ifrw, slideOptions, initialState);
var enterPresentationMode = function (shouldLog) {
Slide.show(true, editor.getValue());
if (shouldLog) {
Cryptpad.log(Messages.presentSuccess);
}
};
if (presentMode) {
enterPresentationMode(true);
}
var textColor;
var backColor;
var config = {
initialState: '{}',
websocketURL: Cryptpad.getWebsocketURL(),
channel: secret.channel,
// our public key
validateKey: secret.keys.validateKey || undefined,
readOnly: readOnly,
crypto: Crypto.createEncryptor(secret.keys),
transformFunction: JsonOT.validate,
network: Cryptpad.getNetwork()
};
var canonicalize = function (t) { return t.replace(/\r\n/g, '\n'); };
var setHistory = function (bool, update) {
isHistoryMode = bool;
setEditable(!bool);
if (!bool && update) {
config.onRemote();
}
};
var initializing = true;
var stringifyInner = function (textValue) {
var obj = {
content: textValue,
metadata: {
users: UserList.userData,
defaultTitle: Title.defaultTitle,
slideOptions: slideOptions
}
};
if (!initializing) {
obj.metadata.title = Title.title;
}
if (textColor) {
obj.metadata.color = textColor;
}
if (backColor) {
obj.metadata.backColor = backColor;
}
// stringify the json and send it into chainpad
return stringify(obj);
};
var onLocal = config.onLocal = function () {
if (initializing) { return; }
if (isHistoryMode) { return; }
if (readOnly) { return; }
editor.save();
var textValue = canonicalize(CodeMirror.$textarea.val());
var shjson = stringifyInner(textValue);
module.patchText(shjson);
Slide.update(textValue);
if (module.realtime.getUserDoc() !== shjson) {
console.error("realtime.getUserDoc() !== shjson");
}
};
var metadataCfg = {
slideOptions: function (newOpt) {
if (stringify(newOpt) !== stringify(slideOptions)) {
$.extend(slideOptions, newOpt);
// TODO: manage realtime + cursor in the "options" modal ??
Slide.updateOptions();
}
}
};
var updateColors = metadataCfg.slideColors = function (text, back) {
if (text) {
textColor = text;
$modal.css('color', text);
$modal.css('border-color', text);
$pad.contents().find('#' + SLIDE_COLOR_ID).css('color', text);
}
if (back) {
backColor = back;
$modal.css('background-color', back);
//$pad.contents().find('#' + SLIDE_COLOR_ID).css('background', back);
$pad.contents().find('#' + SLIDE_BACKCOLOR_ID).css('color', back);
}
};
var createPrintDialog = function () {
var slideOptionsTmp = {
title: false,
slide: false,
date: false,
transition: true,
style: ''
};
$.extend(slideOptionsTmp, slideOptions);
var $container = $('<div class="alertify">');
var $container2 = $('<div class="dialog">').appendTo($container);
var $div = $('<div id="printOptions">').appendTo($container2);
var $p = $('<p>', {'class': 'msg'}).appendTo($div);
$('<b>').text(Messages.printOptions).appendTo($p);
$p.append($('<br>'));
// Slide number
$('<input>', {type: 'checkbox', id: 'checkNumber', checked: slideOptionsTmp.slide}).on('change', function () {
var c = this.checked;
slideOptionsTmp.slide = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'checkNumber'}).text(Messages.printSlideNumber).appendTo($p);
$p.append($('<br>'));
// Date
$('<input>', {type: 'checkbox', id: 'checkDate', checked: slideOptionsTmp.date}).on('change', function () {
var c = this.checked;
slideOptionsTmp.date = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'checkDate'}).text(Messages.printDate).appendTo($p);
$p.append($('<br>'));
// Title
$('<input>', {type: 'checkbox', id: 'checkTitle', checked: slideOptionsTmp.title}).on('change', function () {
var c = this.checked;
slideOptionsTmp.title = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'checkTitle'}).text(Messages.printTitle).appendTo($p);
$p.append($('<br>'));
// Transition
$('<input>', {type: 'checkbox', id: 'checkTransition', checked: slideOptionsTmp.transition}).on('change', function () {
var c = this.checked;
slideOptionsTmp.transition = c;
}).appendTo($p).css('width', 'auto');
$('<label>', {'for': 'checkTransition'}).text(Messages.printTransition).appendTo($p);
$p.append($('<br>'));
// CSS
$('<label>', {'for': 'cssPrint'}).text(Messages.printCSS).appendTo($p);
$p.append($('<br>'));
var $textarea = $('<textarea>', {'id':'cssPrint'}).css({'width':'100%', 'height':'100px'}).appendTo($p)
.on('keydown keyup', function (e) {
e.stopPropagation();
});
$textarea.val(slideOptionsTmp.style);
window.setTimeout(function () { $textarea.focus(); }, 0);
var h;
var todo = function () {
$.extend(slideOptions, slideOptionsTmp);
slideOptions.style = $textarea.val();
onLocal();
$container.remove();
Cryptpad.stopListening(h);
};
var todoCancel = function () {
$container.remove();
Cryptpad.stopListening(h);
};
h = Cryptpad.listenForKeys(todo, todoCancel);
var $nav = $('<nav>').appendTo($div);
$('<button>', {'class': 'cancel'}).text(Messages.cancelButton).appendTo($nav).click(todoCancel);
$('<button>', {'class': 'ok'}).text(Messages.settings_save).appendTo($nav).click(todo);
return $container;
};
config.onInit = function (info) {
UserList = Cryptpad.createUserList(info, config.onLocal, Cryptget, Cryptpad);
var titleCfg = {
updateLocalTitle: setTabTitle,
getHeadingText: CodeMirror.getHeadingText
};
Title = Cryptpad.createTitle(titleCfg, config.onLocal, Cryptpad);
Slide.setTitle(Title);
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: ifrw,
realtime: info.realtime,
network: info.network,
$container: $bar,
$contentContainer: $contentContainer
};
toolbar = module.toolbar = Toolbar.create(configTb);
Title.setToolbar(toolbar);
CodeMirror.init(config.onLocal, Title, toolbar);
var $rightside = toolbar.$rightside;
var $drawer = toolbar.$drawer;
var editHash;
if (!readOnly) {
editHash = Cryptpad.getEditHashFromKeys(info.channel, secret.keys);
}
/* add a history button */
var histConfig = {
onLocal: config.onLocal,
onRemote: config.onRemote,
setHistory: setHistory,
applyVal: function (val) {
var remoteDoc = JSON.parse(val || '{}').content;
editor.setValue(remoteDoc || '');
editor.save();
},
$toolbar: $bar
};
var $hist = Cryptpad.createButton('history', true, {histConfig: histConfig});
$drawer.append($hist);
/* 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);
}
/* add an export button */
var $export = Cryptpad.createButton('export', true, {}, CodeMirror.exportText);
$drawer.append($export);
if (!readOnly) {
/* add an import button */
var $import = Cryptpad.createButton('import', true, {}, CodeMirror.importText);
$drawer.append($import);
}
/* add a forget button */
var forgetCb = function (err) {
if (err) { return; }
setEditable(false);
};
var $forgetPad = Cryptpad.createButton('forget', true, {}, forgetCb);
$rightside.append($forgetPad);
var fileDialogCfg = {
$body: $iframe.find('body'),
onSelect: function (href) {
var parsed = Cryptpad.parsePadUrl(href);
var hexFileName = Cryptpad.base64ToHex(parsed.hashData.channel);
var src = '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName;
var mt = '<media-tag src="' + src + '" data-crypto-key="cryptpad:' + parsed.hashData.key + '"></media-tag>';
editor.replaceSelection(mt);
},
data: APP
};
$('<button>', {
title: Messages.filePickerButton,
'class': 'rightside-button fa fa-picture-o',
style: 'font-size: 17px'
}).click(function () {
Cryptpad.createFileDialog(fileDialogCfg);
}).appendTo($rightside);
var $previewButton = APP.$previewButton = Cryptpad.createButton(null, true);
$previewButton.removeClass('fa-question').addClass('fa-eye');
$previewButton.attr('title', Messages.previewButtonTitle);
$previewButton.click(function () {
var $c = $iframe.find('#editorContainer');
if ($c.hasClass('preview')) {
Cryptpad.setPadAttribute('previewMode', false, function (e) {
if (e) { return console.log(e); }
});
$previewButton.removeClass('active');
return void $c.removeClass('preview');
}
Cryptpad.setPadAttribute('previewMode', true, function (e) {
if (e) { return console.log(e); }
});
$c.addClass('preview');
$previewButton.addClass('active');
Slide.updateFontSize();
});
$rightside.append($previewButton);
var $printButton = $('<button>', {
title: Messages.printButtonTitle,
'class': 'rightside-button fa fa-print',
style: 'font-size: 17px'
}).click(function () {
Slide.update(editor.getValue(), true);
$print.html($content.html());
Cryptpad.confirm("Are you sure you want to print?", function (yes) {
if (yes) {
window.frames["pad-iframe"].focus();
window.frames["pad-iframe"].print();
}
}, {ok: Messages.printButton});
Cryptpad.feedback('PRINT_SLIDES');
//$('body').append(createPrintDialog());
}).append($('<span>', {'class': 'drawer'}).text(Messages.printText));
$drawer.append($printButton);
var $slideOptions = $('<button>', {
title: Messages.slideOptionsTitle,
'class': 'rightside-button fa fa-cog',
style: 'font-size: 17px'
}).click(function () {
$('body').append(createPrintDialog());
}).append($('<span>', {'class': 'drawer'}).text(Messages.slideOptionsText));
$drawer.append($slideOptions);
var $present = Cryptpad.createButton('present', true)
.click(function () {
enterPresentationMode(true);
});
if (presentMode) {
$present.hide();
}
$rightside.append($present);
var configureColors = function () {
var $back = $('<button>', {
id: SLIDE_BACKCOLOR_ID,
'class': 'fa fa-square rightside-button',
'style': 'font-family: FontAwesome; color: #000;',
title: Messages.backgroundButtonTitle
});
var $text = $('<button>', {
id: SLIDE_COLOR_ID,
'class': 'fa fa-i-cursor rightside-button',
'style': 'font-family: FontAwesome; font-weight: bold; color: #fff;',
title: Messages.colorButtonTitle
});
var $testColor = $('<input>', { type: 'color', value: '!' });
var $check = $pad.contents().find("#colorPicker_check");
if ($testColor.attr('type') !== "color" || $testColor.val() === '!') { return; }
$back.on('click', function() {
var $picker = $('<input>', { type: 'color', value: backColor })
.css({ display: 'none', })
.on('change', function() {
updateColors(undefined, this.value);
onLocal();
});
$check.append($picker);
setTimeout(function() {
$picker.click();
}, 0);
});
$text.on('click', function() {
var $picker = $('<input>', { type: 'color', value: textColor })
.css({ display: 'none', })
.on('change', function() {
updateColors(this.value, undefined);
onLocal();
$check.html('');
});
$check.append($picker);
setTimeout(function() {
$picker.click();
}, 0);
});
$rightside.append($back).append($text);
};
configureColors();
CodeMirror.configureTheme();
if (presentMode) {
$('#top-bar').hide();
}
// set the hash
if (!window.location.hash || window.location.hash === '#') {
Cryptpad.replaceHash(editHash);
}
};
config.onReady = function (info) {
if (module.realtime !== info.realtime) {
var realtime = module.realtime = info.realtime;
module.patchText = TextPatcher.create({
realtime: realtime,
//logging: true
});
}
var userDoc = module.realtime.getUserDoc();
var isNew = false;
if (userDoc === "" || userDoc === "{}") { isNew = true; }
var newDoc = "";
if(userDoc !== "") {
var hjson = JSON.parse(userDoc);
newDoc = hjson.content;
if (typeof (hjson) !== 'object' || Array.isArray(hjson) ||
(typeof(hjson.type) !== 'undefined' && hjson.type !== 'slide')) {
var errorText = Messages.typeError;
Cryptpad.errorLoadingScreen(errorText);
throw new Error(errorText);
}
if (hjson.highlightMode) {
CodeMirror.setMode(hjson.highlightMode);
}
}
if (!CodeMirror.highlightMode) {
CodeMirror.setMode('markdown');
}
// Update the user list (metadata) from the hyperjson
Metadata.update(userDoc);
editor.setValue(newDoc || initialState);
if (Cryptpad.initialName && Title.isDefaultTitle()) {
Title.updateTitle(Cryptpad.initialName);
}
Cryptpad.getPadAttribute('previewMode', function (e, data) {
if (e) { return void console.error(e); }
if ([true, undefined].indexOf(data) !== -1 && APP.$previewButton) {
APP.$previewButton.click();
}
});
Slide.onChange(function (o, n, l) {
var slideNumber = '';
if (n !== null) {
if (Slide.shown) { //Slide.index && Slide.content.length) {
slideNumber = ' (' + (++n) + '/' + l + ')';
}
}
document.title = Title.title + slideNumber;
});
Cryptpad.removeLoadingScreen();
setEditable(true);
initializing = false;
onLocal(); // push local state to avoid parse errors later.
Slide.update(editor.getValue());
if (readOnly) { return; }
UserList.getLastName(toolbar.$userNameButton, isNew);
var fmConfig = {
dropArea: $iframe.find('.CodeMirror'),
body: $iframe.find('body'),
onUploaded: function (ev, data) {
//var cursor = editor.getCursor();
//var cleanName = data.name.replace(/[\[\]]/g, '');
//var text = '!['+cleanName+']('+data.url+')';
var parsed = Cryptpad.parsePadUrl(data.url);
var hexFileName = Cryptpad.base64ToHex(parsed.hashData.channel);
var src = '/blob/' + hexFileName.slice(0,2) + '/' + hexFileName;
var mt = '<media-tag src="' + src + '" data-crypto-key="cryptpad:' + parsed.hashData.key + '"></media-tag>';
editor.replaceSelection(mt);
}
};
APP.FM = Cryptpad.createFileManager(fmConfig);
};
config.onRemote = function () {
if (initializing) { return; }
if (isHistoryMode) { return; }
var oldDoc = canonicalize(CodeMirror.$textarea.val());
var shjson = module.realtime.getUserDoc();
// Update the user list (metadata) from the hyperjson
Metadata.update(shjson);
var hjson = JSON.parse(shjson);
var remoteDoc = hjson.content;
var highlightMode = hjson.highlightMode;
if (highlightMode && highlightMode !== CodeMirror.highlightMode) {
CodeMirror.setMode(highlightMode);
}
CodeMirror.setValueAndCursor(oldDoc, remoteDoc, TextPatcher);
if (!readOnly) {
var textValue = canonicalize(CodeMirror.$textarea.val());
var shjson2 = stringifyInner(textValue);
if (shjson2 !== shjson) {
console.error("shjson2 !== shjson");
TextPatcher.log(shjson, TextPatcher.diff(shjson, shjson2));
module.patchText(shjson2);
}
}
Slide.update(remoteDoc);
if (oldDoc !== remoteDoc) {
Cryptpad.notify();
}
};
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);
toolbar.failed();
if (info.state) {
initializing = true;
toolbar.reconnecting(info.myId);
Cryptpad.findOKButton().click();
} else {
if (!Slide.isPresentURL()) {
Cryptpad.alert(Messages.common_connectionLost, undefined, true);
}
}
};
config.onError = onConnectError;
module.realtime = Realtime.start(config);
editor.on('change', onLocal);
Cryptpad.onLogout(function () { setEditable(false); });
};
var interval = 100;
var second = function (CM) {
Cryptpad.ready(function () {
andThen(CM);
Cryptpad.reportAppUsage();
});
Cryptpad.onError(function (info) {
if (info && info.type === "store") {
onConnectError();
}
});
};
var first = function () {
if (ifrw.CodeMirror) {
// it exists, call your continuation
second(ifrw.CodeMirror);
} else {
console.log("CodeMirror was not defined. Trying again in %sms", interval);
// try again in 'interval' ms
setTimeout(first, interval);
}
};
first();
window.addEventListener('message', onMsg);
}).nThen(function (/*waitFor*/) {
SFCommonO.start();
});
});

View File

@ -1,8 +1,7 @@
define([
'jquery',
'/common/diffMarked.js',
'/common/cryptpad-common.js',
],function ($, DiffMd, Cryptpad) {
],function ($, DiffMd) {
var Slide = {
index: 0,
@ -13,13 +12,13 @@ define([
var ifrw;
var $modal;
var $content;
var $pad;
var placeholder;
var options;
var separator = '<hr data-pewpew="pezpez">';
var separatorReg = /<hr data\-pewpew="pezpez">/g;
var slideClass = 'slide-frame';
var slideClass = 'cp-app-slide-frame';
var Title;
var Common;
Slide.onChange = function (f) {
if (typeof(f) === 'function') {
@ -60,21 +59,21 @@ define([
};
var fixCSS = function (css) {
var append = '.cp #print .slide-frame ';
var append2 = '.cp div#modal #content .slide-frame ';
var append = '.cp #cp-app-slide-print .cp-app-slide-frame ';
var append2 = '.cp div#cp-app-slide-modal #cp-app-slide-modal-content .cp-app-slide-frame ';
return css.replace(/(\n*)([^\n}]+)\s*\{/g, '$1' + append + '$2,' + append2 + '$2 {');
};
var goTo = Slide.goTo = function (i) {
i = i || 0;
Slide.index = i;
$content.find('.slide-container').first().css('margin-left', -(i*100)+'%');
$content.find('.cp-app-slide-container').first().css('margin-left', -(i*100)+'%');
updateFontSize();
change(Slide.lastIndex, Slide.index);
$modal.find('#button_left > span').css({
$modal.find('#cp-app-slide-modal-left > span').css({
opacity: Slide.index === 0? 0: 1
});
$modal.find('#button_right > span').css({
$modal.find('#cp-app-slide-modal-right > span').css({
opacity: Slide.index === (getNumberOfSlides() -1)? 0: 1
});
};
@ -82,29 +81,29 @@ define([
if (typeof(Slide.content) !== 'string') { return; }
var c = Slide.content;
var m = '<span class="slide-container"><span class="'+slideClass+'">'+DiffMd.render(c).replace(separatorReg, '</span></span><span class="slide-container"><span class="'+slideClass+'">')+'</span></span>';
var m = '<span class="cp-app-slide-container"><span class="'+slideClass+'">'+DiffMd.render(c).replace(separatorReg, '</span></span><span class="cp-app-slide-container"><span class="'+slideClass+'">')+'</span></span>';
DiffMd.apply(m, $content);
var length = getNumberOfSlides();
$modal.find('style.slideStyle').remove();
$modal.find('style.cp-app-slide-style').remove();
if (options.style && Slide.shown) {
$modal.prepend($('<style>', {'class': 'slideStyle'}).text(fixCSS(options.style)));
$modal.prepend($('<style>', {'class': 'cp-app-slide-style'}).text(fixCSS(options.style)));
}
$content.find('.slide-frame').each(function (i, el) {
$content.find('.cp-app-slide-frame').each(function (i, el) {
if (options.slide) {
$('<div>', {'class': 'slideNumber'}).text((i+1)+'/'+length).appendTo($(el));
$('<div>', {'class': 'cp-app-slide-number'}).text((i+1)+'/'+length).appendTo($(el));
}
if (options.date) {
$('<div>', {'class': 'slideDate'}).text(new Date().toLocaleDateString()).appendTo($(el));
$('<div>', {'class': 'cp-app-slide-date'}).text(new Date().toLocaleDateString()).appendTo($(el));
}
if (options.title) {
$('<div>', {'class': 'slideTitle'}).text(Title.title).appendTo($(el));
$('<div>', {'class': 'cp-app-slide-title'}).text(Title.title).appendTo($(el));
}
});
$content.removeClass('transition');
$content.removeClass('cp-app-slide-transition');
if (options.transition || typeof(options.transition) === "undefined") {
$content.addClass('transition');
$content.addClass('cp-app-slide-transition');
}
//$content.find('.' + slideClass).hide();
//$content.find('.' + slideClass + ':eq( ' + i + ' )').show();
@ -116,46 +115,29 @@ define([
draw(Slide.index);
};
var isPresentURL = Slide.isPresentURL = function () {
var parsed = Cryptpad.parsePadUrl(window.location.href);
return parsed && parsed.hashData && parsed.hashData.present;
};
var show = Slide.show = function (bool, content) {
var parsed = Cryptpad.parsePadUrl(window.location.href);
var hashData = parsed.hashData || {};
Slide.shown = bool;
if (bool) {
Slide.update(content);
Slide.draw(Slide.index);
$modal.addClass('shown');
$modal.addClass('cp-app-slide-shown');
$(ifrw).focus();
change(null, Slide.index);
if (!isPresentURL()) {
window.location += parsed.getUrl({present: true, embed: hashData.embed});
}
$pad.contents().find('.cryptpad-present-button').hide();
$pad.contents().find('.cryptpad-source-button').show();
$pad.addClass('fullscreen');
$('#iframe-container').addClass('fullscreen');
$('.top-bar').hide();
Common.setPresentUrl(true);
$('.cp-app-slide-present-button').hide();
updateFontSize();
return;
}
window.location = parsed.getUrl({embed: hashData.embed});
Common.setPresentUrl(false);
change(Slide.index, null);
$pad.contents().find('.cryptpad-present-button').show();
$pad.contents().find('.cryptpad-source-button').hide();
$pad.removeClass('fullscreen');
$('#iframe-container').removeClass('fullscreen');
$('.top-bar').show();
$modal.removeClass('shown');
$('.cp-app-slide-present-button').show();
$('.cp-app-slide-source-button').hide();
$modal.removeClass('cp-app-slide-shown');
updateFontSize();
};
Slide.update = function (content) {
updateFontSize();
//if (!init) { return; }
if (!content) { content = ''; }
var old = Slide.content;
Slide.content = content.replace(/\n\s*\-\-\-\s*\n/g, '\n\n'+separator+'\n\n');
@ -199,33 +181,34 @@ define([
};
var addEvent = function () {
console.log($modal);
var icon_to;
$modal.mousemove(function () {
var $buttons = $modal.find('.button');
var $buttons = $modal.find('.cp-app-slide-modal-button');
$buttons.show();
if (icon_to) { window.clearTimeout(icon_to); }
icon_to = window.setTimeout(function() {
$buttons.fadeOut();
}, 1000);
});
$modal.find('#button_exit').click(function () {
$modal.find('#cp-app-slide-modal-exit').click(function () {
var ev = $.Event("keyup");
ev.which = 27;
$modal.trigger(ev);
});
$modal.find('#button_left').click(function () {
$modal.find('#cp-app-slide-modal-left').click(function () {
var ev = $.Event("keyup");
ev.which = 37;
$modal.trigger(ev);
});
$modal.find('#button_right').click(function () {
$modal.find('#cp-app-slide-modal-right').click(function () {
console.log('right');
var ev = $.Event("keyup");
ev.which = 39;
$modal.trigger(ev);
});
$pad.contents().find('.CodeMirror').keyup(function (e) { e.stopPropagation(); });
$('.CodeMirror').keyup(function (e) { e.stopPropagation(); });
$(ifrw).on('keyup', function (e) {
//if (!Slide.shown) { return; }
if (e.ctrlKey) { return; }
@ -302,11 +285,11 @@ define([
};
Slide.setModal = function ($m, $c, $p, iframe, opt, ph) {
Slide.setModal = function (common, $m, $c, opt, ph) {
Common = common;
$modal = Slide.$modal = $m;
$content = Slide.$content = $c;
$pad = Slide.$pad = $p;
ifrw = Slide.ifrw = iframe;
ifrw = Slide.ifrw = window;
placeholder = Slide.placeholder = ph;
options = Slide.options = opt;
addEvent();