hedgedoc/public/js/index.js

1986 lines
59 KiB
JavaScript
Raw Normal View History

2015-05-04 03:53:29 -04:00
//constant vars
//settings
2015-06-01 06:04:25 -04:00
var debug = false;
2015-07-11 00:52:04 -04:00
var version = '0.3.2';
2015-06-01 06:04:25 -04:00
var defaultTextHeight = 18;
var viewportMargin = 20;
var defaultExtraKeys = {
2015-07-01 12:10:20 -04:00
"Cmd-S": function () {
return CodeMirror.PASS
},
"Ctrl-S": function () {
return CodeMirror.PASS
},
2015-06-01 06:04:25 -04:00
"Enter": "newlineAndIndentContinueMarkdownList"
};
var idleTime = 300000; //5 mins
var finishChangeDelay = 200;
2015-05-04 03:53:29 -04:00
var cursorActivityDelay = 50;
var cursorAnimatePeriod = 100;
2015-06-01 06:04:25 -04:00
var supportCodeModes = ['javascript', 'htmlmixed', 'htmlembedded', 'css', 'xml', 'clike', 'clojure', 'ruby', 'python', 'shell', 'php', 'sql', 'coffeescript', 'yaml', 'jade', 'lua', 'cmake', 'nginx', 'perl', 'sass', 'r', 'dockerfile'];
var supportHeaders = [
{
text: '# h1',
search: '#'
},
{
text: '## h2',
search: '##'
},
{
text: '### h3',
search: '###'
},
{
text: '#### h4',
search: '####'
},
{
text: '##### h5',
search: '#####'
},
{
text: '###### h6',
search: '######'
},
{
text: '###### tags: `example`',
search: '###### tags:'
}
];
var supportReferrals = [
{
text: '[reference link]',
search: '[]'
},
{
text: '[reference]: url "title"',
search: '[]:'
},
{
text: '[^footnote link]',
search: '[^]'
},
{
text: '[^footnote reference]: url "title"',
search: '[^]:'
},
{
text: '^[inline footnote]',
search: '^[]'
},
{
text: '[link text][reference]',
search: '[][]'
},
{
text: '[link text](url "title")',
search: '[]()'
},
{
text: '![image text][reference]',
search: '![][]'
},
{
text: '![image text](url "title")',
search: '![]()'
}
];
var supportExternals = [
{
text: '{%youtube youtubeid %}',
search: 'youtube'
},
{
text: '{%vimeo vimeoid %}',
search: 'vimeo'
},
{
text: '{%gist gistid %}',
search: 'gist'
}
];
2015-07-01 12:10:20 -04:00
var supportBlockquoteTags = [
{
text: '[name tag]',
search: '[]',
command: function () {
return '[name=' + personalInfo.name + ']';
},
},
2015-06-01 06:04:25 -04:00
{
2015-07-01 12:10:20 -04:00
text: '[time tag]',
search: '[]',
2015-06-01 06:04:25 -04:00
command: function () {
2015-07-01 12:10:20 -04:00
return '[time=' + moment().format('llll') + ']';
2015-06-01 06:04:25 -04:00
},
2015-07-01 12:10:20 -04:00
},
{
text: '[my color tag]',
2015-07-01 12:10:20 -04:00
search: '[]',
command: function () {
return '[color=' + personalInfo.color + ']';
}
},
{
text: '[random color tag]',
search: '[]',
command: function () {
var color = randomColor({
luminosity: 'light'
});
return '[color=' + color + ']';
}
2015-06-01 06:04:25 -04:00
}
];
2015-05-04 03:53:29 -04:00
var modeType = {
edit: {},
view: {},
both: {}
}
var statusType = {
connected: {
msg: "CONNECTED",
label: "label-warning",
fa: "fa-wifi"
},
online: {
2015-06-01 06:04:25 -04:00
msg: "ONLINE",
2015-05-04 03:53:29 -04:00
label: "label-primary",
fa: "fa-users"
},
offline: {
msg: "OFFLINE",
label: "label-danger",
fa: "fa-plug"
}
}
var defaultMode = modeType.both;
//global vars
var loaded = false;
2015-07-01 12:10:20 -04:00
var needRefresh = false;
2015-05-04 03:53:29 -04:00
var isDirty = false;
var editShown = false;
var visibleXS = false;
var visibleSM = false;
var visibleMD = false;
var visibleLG = false;
var isTouchDevice = 'ontouchstart' in document.documentElement;
var currentMode = defaultMode;
var currentStatus = statusType.offline;
var lastInfo = {
needRestore: false,
cursor: null,
scroll: null,
edit: {
scroll: {
left: null,
top: null
},
cursor: {
line: null,
ch: null
}
},
view: {
scroll: {
left: null,
top: null
}
},
history: null
};
2015-06-01 06:04:25 -04:00
var personalInfo = {};
var onlineUsers = [];
2015-05-04 03:53:29 -04:00
//editor settings
2015-05-15 00:58:13 -04:00
var textit = document.getElementById("textit");
if (!textit) throw new Error("There was no textit area!");
var editor = CodeMirror.fromTextArea(textit, {
2015-05-04 03:53:29 -04:00
mode: 'gfm',
2015-05-15 00:58:13 -04:00
keyMap: "sublime",
2015-06-01 06:04:25 -04:00
viewportMargin: viewportMargin,
2015-05-04 03:53:29 -04:00
styleActiveLine: true,
lineNumbers: true,
lineWrapping: true,
2015-05-15 00:58:13 -04:00
showCursorWhenSelecting: true,
2015-06-01 06:04:25 -04:00
indentUnit: 4,
indentWithTabs: true,
continueComments: "Enter",
2015-05-04 03:53:29 -04:00
theme: "monokai",
inputStyle: "textarea",
matchBrackets: true,
autoCloseBrackets: true,
matchTags: {
bothTags: true
},
autoCloseTags: true,
foldGutter: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
2015-06-01 06:04:25 -04:00
extraKeys: defaultExtraKeys,
2015-05-04 03:53:29 -04:00
readOnly: true
});
2015-07-01 12:10:20 -04:00
var inlineAttach = inlineAttachment.editors.codemirror4.attach(editor);
2015-06-01 06:04:25 -04:00
defaultTextHeight = parseInt($(".CodeMirror").css('line-height'));
2015-05-04 03:53:29 -04:00
//ui vars
var ui = {
spinner: $(".ui-spinner"),
content: $(".ui-content"),
toolbar: {
shortStatus: $(".ui-short-status"),
status: $(".ui-status"),
new: $(".ui-new"),
publish: $(".ui-publish"),
2015-05-04 03:53:29 -04:00
download: {
markdown: $(".ui-download-markdown")
},
save: {
dropbox: $(".ui-save-dropbox")
},
import: {
dropbox: $(".ui-import-dropbox"),
clipboard: $(".ui-import-clipboard")
},
mode: $(".ui-mode"),
edit: $(".ui-edit"),
view: $(".ui-view"),
2015-07-01 12:10:20 -04:00
both: $(".ui-both"),
uploadImage: $(".ui-upload-image")
},
infobar: {
lastchange: $(".ui-lastchange"),
permission: {
permission: $(".ui-permission"),
label: $(".ui-permission-label"),
freely: $(".ui-permission-freely"),
editable: $(".ui-permission-editable"),
locked: $(".ui-permission-locked")
}
},
toc: {
toc: $('.ui-toc'),
affix: $('.ui-affix-toc'),
label: $('.ui-toc-label'),
dropdown: $('.ui-toc-dropdown')
2015-05-04 03:53:29 -04:00
},
area: {
edit: $(".ui-edit-area"),
view: $(".ui-view-area"),
codemirror: $(".ui-edit-area .CodeMirror"),
markdown: $(".ui-view-area .markdown-body")
}
};
//page actions
var opts = {
lines: 11, // The number of lines to draw
length: 20, // The length of each line
width: 2, // The line thickness
radius: 30, // The radius of the inner circle
corners: 0, // Corner roundness (0..1)
rotate: 0, // The rotation offset
direction: 1, // 1: clockwise, -1: counterclockwise
color: '#000', // #rgb or #rrggbb or array of colors
speed: 1.1, // Rounds per second
trail: 60, // Afterglow percentage
shadow: false, // Whether to render a shadow
hwaccel: true, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: '50%', // Top position relative to parent
left: '50%' // Left position relative to parent
};
var spinner = new Spinner(opts).spin(ui.spinner[0]);
2015-06-01 06:04:25 -04:00
//idle
var idle = new Idle({
onAway: idleStateChange,
onAwayBack: idleStateChange,
awayTimeout: idleTime
});
ui.area.codemirror.on('touchstart', function () {
idle.onActive();
});
function idleStateChange() {
emitUserStatus();
updateOnlineStatus();
}
2015-07-01 12:10:20 -04:00
function setNeedRefresh() {
$('#refreshModal').modal('show');
needRefresh = true;
editor.setOption('readOnly', true);
socket.disconnect();
showStatus(statusType.offline);
2015-06-01 06:04:25 -04:00
}
2015-07-01 12:10:20 -04:00
loginStateChangeEvent = setNeedRefresh;
2015-06-01 06:04:25 -04:00
//visibility
var wasFocus = false;
Visibility.change(function (e, state) {
var hidden = Visibility.hidden();
if (hidden) {
if (editorHasFocus()) {
wasFocus = true;
editor.getInputField().blur();
}
} else {
if (wasFocus) {
editor.focus();
wasFocus = false;
}
}
});
2015-05-04 03:53:29 -04:00
//when page ready
$(document).ready(function () {
2015-06-01 06:04:25 -04:00
idle.checkAway();
2015-05-04 03:53:29 -04:00
checkResponsive();
2015-06-01 06:04:25 -04:00
//if in smaller screen, we don't need advanced scrollbar
var scrollbarStyle;
if (visibleXS) {
scrollbarStyle = 'native';
} else {
scrollbarStyle = 'overlay';
}
if (scrollbarStyle != editor.getOption('scrollbarStyle')) {
editor.setOption('scrollbarStyle', scrollbarStyle);
clearMap();
}
checkEditorStyle();
2015-05-04 03:53:29 -04:00
changeMode(currentMode);
/* we need this only on touch devices */
if (isTouchDevice) {
2015-05-15 00:58:13 -04:00
/* cache dom references */
var $body = jQuery('body');
2015-05-04 03:53:29 -04:00
/* bind events */
$(document)
2015-05-15 00:58:13 -04:00
.on('focus', 'textarea, input', function () {
$body.addClass('fixfixed');
})
.on('blur', 'textarea, input', function () {
$body.removeClass('fixfixed');
});
2015-05-04 03:53:29 -04:00
}
2015-07-01 12:10:20 -04:00
//showup
$().showUp('.navbar', {
upClass: 'navbar-hide',
downClass: 'navbar-show'
});
2015-05-04 03:53:29 -04:00
});
//when page resize
2015-05-15 00:58:13 -04:00
var windowResizeDelay = 200;
var windowResizeTimer = null;
2015-05-04 03:53:29 -04:00
$(window).resize(function () {
2015-05-15 00:58:13 -04:00
clearTimeout(windowResizeTimer);
windowResizeTimer = setTimeout(function () {
windowResize();
}, windowResizeDelay);
2015-05-04 03:53:29 -04:00
});
2015-06-01 06:04:25 -04:00
//when page unload
$(window).unload(function () {
writeHistory(ui.area.markdown);
});
$(window).error(function () {
setNeedRefresh();
2015-06-01 06:04:25 -04:00
});
2015-07-01 12:10:20 -04:00
//when page hash change
window.onhashchange = locationHashChanged;
function locationHashChanged(e) {
e.stopPropagation();
e.preventDefault();
if (currentMode != modeType.both) {
return;
}
var hashtarget = $("[id$='" + location.hash.substr(1) + "']");
if (hashtarget.length > 0) {
var linenumber = hashtarget.attr('data-startline');
if (linenumber) {
editor.setOption('viewportMargin', Infinity);
editor.setOption('viewportMargin', viewportMargin);
var t = editor.charCoords({
line: linenumber,
ch: 0
}, "local").top;
editor.scrollTo(null, t - defaultTextHeight * 1.2);
}
}
}
2015-05-15 00:58:13 -04:00
function windowResize() {
checkResponsive();
2015-06-01 06:04:25 -04:00
checkEditorStyle();
2015-07-01 12:10:20 -04:00
checkTocStyle();
//refresh editor
2015-06-01 06:04:25 -04:00
if (loaded) {
editor.setOption('viewportMargin', Infinity);
setTimeout(function () {
clearMap();
syncScrollToView();
editor.setOption('viewportMargin', viewportMargin);
}, windowResizeDelay);
}
}
function editorHasFocus() {
return $(editor.getInputField()).is(":focus");
2015-05-15 00:58:13 -04:00
}
2015-06-01 06:04:25 -04:00
2015-05-04 03:53:29 -04:00
//768-792px have a gap
function checkResponsive() {
visibleXS = $(".visible-xs").is(":visible");
visibleSM = $(".visible-sm").is(":visible");
visibleMD = $(".visible-md").is(":visible");
visibleLG = $(".visible-lg").is(":visible");
2015-06-01 06:04:25 -04:00
2015-05-04 03:53:29 -04:00
if (visibleXS && currentMode == modeType.both)
2015-06-01 06:04:25 -04:00
if (editorHasFocus())
2015-05-04 03:53:29 -04:00
changeMode(modeType.edit);
else
changeMode(modeType.view);
2015-06-01 06:04:25 -04:00
emitUserStatus();
}
function checkEditorStyle() {
var scrollbarStyle = editor.getOption('scrollbarStyle');
if (scrollbarStyle == 'overlay' || currentMode == modeType.both) {
ui.area.codemirror.css('height', '');
} else if (scrollbarStyle == 'native') {
ui.area.codemirror.css('height', 'auto');
$('.CodeMirror-gutters').css('height', $('.CodeMirror-sizer').height());
}
2015-05-04 03:53:29 -04:00
}
2015-07-01 12:10:20 -04:00
function checkTocStyle() {
//toc right
var paddingRight = parseFloat(ui.area.markdown.css('padding-right'));
var right = ($(window).width() - (ui.area.markdown.offset().left + ui.area.markdown.outerWidth() - paddingRight));
ui.toc.toc.css('right', right + 'px');
//affix toc left
var newbool;
var rightMargin = (ui.area.markdown.parent().outerWidth() - ui.area.markdown.outerWidth()) / 2;
//for ipad or wider device
if (rightMargin >= 133) {
newbool = true;
var affixLeftMargin = (ui.toc.affix.outerWidth() - ui.toc.affix.width()) / 2;
var left = ui.area.markdown.offset().left + ui.area.markdown.outerWidth() - affixLeftMargin;
ui.toc.affix.css('left', left + 'px');
} else {
newbool = false;
}
//toc scrollspy
ui.toc.toc.removeClass('scrollspy-body, scrollspy-view');
ui.toc.affix.removeClass('scrollspy-body, scrollspy-view');
if (currentMode != modeType.both && !newbool) {
ui.toc.toc.addClass('scrollspy-body');
ui.toc.affix.addClass('scrollspy-body');
} else {
ui.toc.toc.addClass('scrollspy-view');
ui.toc.affix.addClass('scrollspy-body');
}
if (newbool != enoughForAffixToc) {
enoughForAffixToc = newbool;
generateScrollspy();
}
}
2015-05-04 03:53:29 -04:00
function showStatus(type, num) {
currentStatus = type;
var shortStatus = ui.toolbar.shortStatus;
var status = ui.toolbar.status;
var label = $('<span class="label"></span>');
var fa = $('<i class="fa"></i>');
var msg = "";
var shortMsg = "";
shortStatus.html("");
status.html("");
switch (currentStatus) {
case statusType.connected:
label.addClass(statusType.connected.label);
fa.addClass(statusType.connected.fa);
msg = statusType.connected.msg;
break;
case statusType.online:
label.addClass(statusType.online.label);
fa.addClass(statusType.online.fa);
2015-06-01 06:04:25 -04:00
shortMsg = num;
msg = num + " " + statusType.online.msg;
2015-05-04 03:53:29 -04:00
break;
case statusType.offline:
label.addClass(statusType.offline.label);
fa.addClass(statusType.offline.fa);
msg = statusType.offline.msg;
break;
}
label.append(fa);
var shortLabel = label.clone();
shortLabel.append(" " + shortMsg);
shortStatus.append(shortLabel);
label.append(" " + msg);
status.append(label);
}
function toggleMode() {
2015-05-15 00:58:13 -04:00
switch (currentMode) {
2015-05-04 03:53:29 -04:00
case modeType.edit:
changeMode(modeType.view);
break;
case modeType.view:
changeMode(modeType.edit);
break;
case modeType.both:
changeMode(modeType.view);
break;
}
}
function changeMode(type) {
saveInfo();
if (type)
currentMode = type;
2015-06-01 06:04:25 -04:00
checkEditorStyle();
2015-05-04 03:53:29 -04:00
var responsiveClass = "col-lg-6 col-md-6 col-sm-6";
var scrollClass = "ui-scrollable";
ui.area.codemirror.removeClass(scrollClass);
ui.area.edit.removeClass(responsiveClass);
ui.area.view.removeClass(scrollClass);
ui.area.view.removeClass(responsiveClass);
switch (currentMode) {
case modeType.edit:
ui.area.edit.show();
ui.area.view.hide();
if (!editShown) {
editor.refresh();
editShown = true;
}
break;
case modeType.view:
ui.area.edit.hide();
ui.area.view.show();
break;
case modeType.both:
ui.area.codemirror.addClass(scrollClass);
ui.area.edit.addClass(responsiveClass).show();
ui.area.view.addClass(scrollClass);
ui.area.view.addClass(responsiveClass).show();
break;
}
if (currentMode != modeType.view && visibleLG) {
2015-06-01 06:04:25 -04:00
//editor.focus();
2015-07-01 12:10:20 -04:00
//editor.refresh();
2015-05-04 03:53:29 -04:00
} else {
editor.getInputField().blur();
}
2015-07-01 12:10:20 -04:00
if (currentMode == modeType.edit || currentMode == modeType.both) {
ui.toolbar.uploadImage.fadeIn();
} else {
ui.toolbar.uploadImage.fadeOut();
}
if (currentMode != modeType.edit) {
$(document.body).css('background-color', 'white');
2015-05-04 03:53:29 -04:00
updateView();
2015-07-01 12:10:20 -04:00
} else {
$(document.body).css('background-color', ui.area.codemirror.css('background-color'));
}
2015-05-04 03:53:29 -04:00
restoreInfo();
2015-06-01 06:04:25 -04:00
windowResize();
2015-05-04 03:53:29 -04:00
ui.toolbar.both.removeClass("active");
ui.toolbar.edit.removeClass("active");
ui.toolbar.view.removeClass("active");
var modeIcon = ui.toolbar.mode.find('i');
modeIcon.removeClass('fa-toggle-on').removeClass('fa-toggle-off');
if (ui.area.edit.is(":visible") && ui.area.view.is(":visible")) { //both
ui.toolbar.both.addClass("active");
modeIcon.addClass('fa-eye');
} else if (ui.area.edit.is(":visible")) { //edit
ui.toolbar.edit.addClass("active");
modeIcon.addClass('fa-toggle-off');
} else if (ui.area.view.is(":visible")) { //view
ui.toolbar.view.addClass("active");
modeIcon.addClass('fa-toggle-on');
}
}
//button actions
2015-07-01 12:10:20 -04:00
var url = window.location.pathname;
//share
ui.toolbar.publish.attr("href", url + "/publish");
2015-05-04 03:53:29 -04:00
//download
//markdown
2015-05-15 00:58:13 -04:00
ui.toolbar.download.markdown.click(function () {
2015-05-04 03:53:29 -04:00
var filename = renderFilename(ui.area.markdown) + '.md';
var markdown = editor.getValue();
2015-05-15 00:58:13 -04:00
var blob = new Blob([markdown], {
type: "text/markdown;charset=utf-8"
});
2015-05-04 03:53:29 -04:00
saveAs(blob, filename);
});
//save to dropbox
2015-05-15 00:58:13 -04:00
ui.toolbar.save.dropbox.click(function () {
2015-05-04 03:53:29 -04:00
var filename = renderFilename(ui.area.markdown) + '.md';
var options = {
files: [
2015-05-15 00:58:13 -04:00
{
'url': url + "/download",
'filename': filename
}
2015-05-04 03:53:29 -04:00
]
};
Dropbox.save(options);
});
//import from dropbox
2015-05-15 00:58:13 -04:00
ui.toolbar.import.dropbox.click(function () {
2015-05-04 03:53:29 -04:00
var options = {
2015-05-15 00:58:13 -04:00
success: function (files) {
2015-05-04 03:53:29 -04:00
ui.spinner.show();
var url = files[0].link;
importFromUrl(url);
},
linkType: "direct",
multiselect: false,
extensions: ['.md', '.html']
};
Dropbox.choose(options);
});
//import from clipboard
2015-05-15 00:58:13 -04:00
ui.toolbar.import.clipboard.click(function () {
2015-05-04 03:53:29 -04:00
//na
});
2015-07-01 12:10:20 -04:00
//upload image
ui.toolbar.uploadImage.bind('change', function (e) {
var files = e.target.files || e.dataTransfer.files;
e.dataTransfer = {};
e.dataTransfer.files = files;
inlineAttach.onDrop(e);
});
//toc
ui.toc.dropdown.click(function (e) {
e.stopPropagation();
});
function scrollToTop() {
if (currentMode == modeType.both) {
if (editor.getScrollInfo().top != 0)
editor.scrollTo(0, 0);
else
ui.area.view.animate({
scrollTop: 0
}, 100, "linear");
} else {
$(document.body).animate({
scrollTop: 0
}, 100, "linear");
}
}
function scrollToBottom() {
if (currentMode == modeType.both) {
var scrollInfo = editor.getScrollInfo();
var scrollHeight = scrollInfo.height;
if (scrollInfo.top != scrollHeight)
editor.scrollTo(0, scrollHeight * 2);
else
ui.area.view.animate({
scrollTop: ui.area.view[0].scrollHeight
}, 100, "linear");
} else {
$(document.body).animate({
scrollTop: $(document.body)[0].scrollHeight
}, 100, "linear");
}
}
var enoughForAffixToc = true;
//scrollspy
function generateScrollspy() {
$(document.body).scrollspy({
target: '.scrollspy-body'
});
ui.area.view.scrollspy({
target: '.scrollspy-view'
});
$(document.body).scrollspy('refresh');
ui.area.view.scrollspy('refresh');
if (enoughForAffixToc) {
ui.toc.toc.hide();
ui.toc.affix.show();
} else {
ui.toc.affix.hide();
ui.toc.toc.show();
}
$(document.body).scroll();
ui.area.view.scroll();
}
2015-05-04 03:53:29 -04:00
//fix for wrong autofocus
2015-05-15 00:58:13 -04:00
$('#clipboardModal').on('shown.bs.modal', function () {
2015-05-04 03:53:29 -04:00
$('#clipboardModal').blur();
});
2015-05-15 00:58:13 -04:00
$("#clipboardModalClear").click(function () {
2015-05-04 03:53:29 -04:00
$("#clipboardModalContent").html('');
});
2015-05-15 00:58:13 -04:00
$("#clipboardModalConfirm").click(function () {
2015-05-04 03:53:29 -04:00
var data = $("#clipboardModalContent").html();
2015-05-15 00:58:13 -04:00
if (data) {
2015-05-04 03:53:29 -04:00
parseToEditor(data);
$('#clipboardModal').modal('hide');
$("#clipboardModalContent").html('');
}
});
2015-07-01 12:10:20 -04:00
$('#refreshModalRefresh').click(function () {
location.reload(true);
});
2015-05-15 00:58:13 -04:00
2015-05-04 03:53:29 -04:00
function parseToEditor(data) {
var parsed = toMarkdown(data);
2015-05-15 00:58:13 -04:00
if (parsed)
editor.replaceRange(parsed, {
line: 0,
ch: 0
}, {
line: editor.lastLine(),
ch: editor.lastLine().length
}, '+input');
2015-05-04 03:53:29 -04:00
}
2015-05-15 00:58:13 -04:00
2015-05-04 03:53:29 -04:00
function importFromUrl(url) {
//console.log(url);
2015-05-15 00:58:13 -04:00
if (url == null) return;
if (!isValidURL(url)) {
2015-05-04 03:53:29 -04:00
alert('Not valid URL :(');
return;
}
$.ajax({
method: "GET",
url: url,
2015-05-15 00:58:13 -04:00
success: function (data) {
2015-05-04 03:53:29 -04:00
parseToEditor(data);
},
2015-05-15 00:58:13 -04:00
error: function () {
2015-05-04 03:53:29 -04:00
alert('Import failed :(');
},
2015-05-15 00:58:13 -04:00
complete: function () {
2015-05-04 03:53:29 -04:00
ui.spinner.hide();
}
});
}
2015-05-15 00:58:13 -04:00
2015-05-04 03:53:29 -04:00
function isValidURL(str) {
2015-07-01 12:10:20 -04:00
var pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
if (!pattern.test(str)) {
return false;
} else {
return true;
2015-05-04 03:53:29 -04:00
}
2015-07-01 12:10:20 -04:00
}
//mode
2015-05-04 03:53:29 -04:00
ui.toolbar.mode.click(function () {
toggleMode();
});
//edit
ui.toolbar.edit.click(function () {
changeMode(modeType.edit);
});
//view
ui.toolbar.view.click(function () {
changeMode(modeType.view);
});
//both
ui.toolbar.both.click(function () {
changeMode(modeType.both);
});
2015-07-01 12:10:20 -04:00
//permission
//freely
ui.infobar.permission.freely.click(function () {
updatePermission("freely");
});
//editable
ui.infobar.permission.editable.click(function () {
updatePermission("editable");
});
//locked
ui.infobar.permission.locked.click(function () {
updatePermission("locked");
});
function updatePermission(_permission) {
if (_permission != permission) {
socket.emit('permission', _permission);
}
}
function checkPermission() {
var label = null;
var title = null;
switch (permission) {
case "freely":
label = '<i class="fa fa-leaf"></i> Freely';
title = "Anyone can edit";
break;
case "editable":
label = '<i class="fa fa-pencil"></i> Editable';
title = "Signed people can edit";
break;
case "locked":
label = '<i class="fa fa-lock"></i> Locked';
title = "Only owner can edit";
break;
}
if (personalInfo.userid == owner) {
label += ' <i class="fa fa-caret-down"></i>';
ui.infobar.permission.label.removeClass('disabled');
} else {
ui.infobar.permission.label.addClass('disabled');
}
ui.infobar.permission.label.html(label).attr('title', title);
}
2015-05-04 03:53:29 -04:00
//socket.io actions
var socket = io.connect();
2015-06-01 06:04:25 -04:00
//overwrite original event for checking login state
var on = socket.on;
socket.on = function () {
2015-07-01 12:10:20 -04:00
if (!checkLoginStateChanged() && !needRefresh)
2015-06-01 06:04:25 -04:00
on.apply(socket, arguments);
};
var emit = socket.emit;
socket.emit = function () {
2015-07-01 12:10:20 -04:00
if (!checkLoginStateChanged() && !needRefresh)
2015-06-01 06:04:25 -04:00
emit.apply(socket, arguments);
};
2015-05-04 03:53:29 -04:00
socket.on('info', function (data) {
console.error(data);
location.href = "./404.html";
});
socket.on('disconnect', function (data) {
showStatus(statusType.offline);
if (loaded) {
saveInfo();
lastInfo.history = editor.getHistory();
}
if (!editor.getOption('readOnly'))
editor.setOption('readOnly', true);
});
2015-06-01 06:04:25 -04:00
socket.on('reconnect', function (data) {
//sync back any change in offline
emitUserStatus(true);
cursorActivity();
socket.emit('online users');
});
2015-05-04 03:53:29 -04:00
socket.on('connect', function (data) {
2015-06-01 06:04:25 -04:00
personalInfo['id'] = socket.id;
2015-05-04 03:53:29 -04:00
showStatus(statusType.connected);
socket.emit('version');
});
socket.on('version', function (data) {
if (data != version)
2015-07-01 12:10:20 -04:00
setNeedRefresh();
});
socket.on('check', function (data) {
lastchangetime = data.updatetime;
lastchangeui = ui.infobar.lastchange;
updateLastChange();
2015-05-04 03:53:29 -04:00
});
2015-07-01 12:10:20 -04:00
socket.on('permission', function (data) {
permission = data.permission;
checkPermission();
});
var docmaxlength = null;
2015-07-01 12:10:20 -04:00
var otk = null;
var owner = null;
var permission = null;
2015-05-04 03:53:29 -04:00
socket.on('refresh', function (data) {
docmaxlength = data.docmaxlength;
editor.setOption("maxLength", docmaxlength);
2015-07-01 12:10:20 -04:00
otk = data.otk;
owner = data.owner;
permission = data.permission;
lastchangetime = data.updatetime;
lastchangeui = ui.infobar.lastchange;
updateLastChange();
checkPermission();
});
var EditorClient = ot.EditorClient;
var SocketIOAdapter = ot.SocketIOAdapter;
var CodeMirrorAdapter = ot.CodeMirrorAdapter;
var cmClient = null;
2015-07-01 12:10:20 -04:00
socket.on('doc', function (obj) {
obj = LZString.decompressFromUTF16(obj);
obj = JSON.parse(obj);
var body = obj.str;
var bodyMismatch = (editor.getValue() != body);
saveInfo();
if (bodyMismatch) {
2015-07-01 12:10:20 -04:00
if (body)
editor.setValue(body);
else
editor.setValue("");
}
if (!cmClient) {
cmClient = window.cmClient = new EditorClient(
obj.revision, obj.clients,
new SocketIOAdapter(socket), new CodeMirrorAdapter(editor)
);
} else {
cmClient.revision = obj.revision;
cmClient.initializeClients(obj.clients);
if (bodyMismatch) {
cmClient.undoManager.undoStack.length = 0;
cmClient.undoManager.redoStack.length = 0;
}
}
2015-05-04 03:53:29 -04:00
if (!loaded) {
editor.clearHistory();
ui.spinner.hide();
ui.content.fadeIn();
changeMode();
loaded = true;
2015-06-01 06:04:25 -04:00
emitUserStatus(); //send first user status
updateOnlineStatus(); //update first online status
2015-07-01 12:10:20 -04:00
setTimeout(function () {
//work around editor not refresh
editor.refresh();
//work around cursor not refresh
for (var i = 0; i < onlineUsers.length; i++) {
buildCursor(onlineUsers[i]);
}
//work around might not scroll to hash
scrollToHash();
}, 1);
2015-05-04 03:53:29 -04:00
} else {
2015-06-01 06:04:25 -04:00
//if current doc is equal to the doc before disconnect
if (bodyMismatch)
2015-05-04 03:53:29 -04:00
editor.clearHistory();
else {
if (lastInfo.history)
editor.setHistory(lastInfo.history);
}
lastInfo.history = null;
}
if (bodyMismatch) {
isDirty = true;
2015-07-01 12:10:20 -04:00
updateView();
}
2015-05-04 03:53:29 -04:00
if (editor.getOption('readOnly'))
editor.setOption('readOnly', false);
2015-05-15 00:58:13 -04:00
2015-05-04 03:53:29 -04:00
restoreInfo();
});
2015-07-01 12:10:20 -04:00
socket.on('ack', _.debounce(function () {
isDirty = true;
updateView();
}, finishChangeDelay));
2015-07-01 12:10:20 -04:00
socket.on('operation', _.debounce(function () {
isDirty = true;
updateView();
}, finishChangeDelay));
2015-07-01 12:10:20 -04:00
2015-05-04 03:53:29 -04:00
socket.on('online users', function (data) {
2015-06-01 06:04:25 -04:00
data = LZString.decompressFromUTF16(data);
data = JSON.parse(data);
2015-05-04 03:53:29 -04:00
if (debug)
console.debug(data);
2015-06-01 06:04:25 -04:00
onlineUsers = data.users;
updateOnlineStatus();
2015-05-15 00:58:13 -04:00
$('.other-cursors').children().each(function (key, value) {
var found = false;
for (var i = 0; i < data.users.length; i++) {
var user = data.users[i];
if ($(this).attr('id') == user.id)
found = true;
}
if (!found)
2015-06-01 06:04:25 -04:00
$(this).stop(true).fadeOut("normal", function () {
$(this).remove();
});
2015-05-15 00:58:13 -04:00
});
for (var i = 0; i < data.users.length; i++) {
2015-05-04 03:53:29 -04:00
var user = data.users[i];
2015-05-15 00:58:13 -04:00
if (user.id != socket.id)
2015-06-01 06:04:25 -04:00
buildCursor(user);
else
personalInfo = user;
}
});
socket.on('user status', function (data) {
if (debug)
console.debug(data);
for (var i = 0; i < onlineUsers.length; i++) {
if (onlineUsers[i].id == data.id) {
onlineUsers[i] = data;
}
2015-05-04 03:53:29 -04:00
}
2015-06-01 06:04:25 -04:00
updateOnlineStatus();
if (data.id != socket.id)
buildCursor(data);
2015-05-04 03:53:29 -04:00
});
socket.on('cursor focus', function (data) {
2015-05-15 00:58:13 -04:00
if (debug)
2015-05-04 03:53:29 -04:00
console.debug(data);
2015-06-01 06:04:25 -04:00
for (var i = 0; i < onlineUsers.length; i++) {
if (onlineUsers[i].id == data.id) {
onlineUsers[i].cursor = data;
}
}
if (data.id != socket.id)
buildCursor(data);
//force show
2015-05-04 03:53:29 -04:00
var cursor = $('#' + data.id);
2015-05-15 00:58:13 -04:00
if (cursor.length > 0) {
2015-06-01 06:04:25 -04:00
cursor.stop(true).fadeIn();
2015-05-04 03:53:29 -04:00
}
});
socket.on('cursor activity', function (data) {
2015-05-15 00:58:13 -04:00
if (debug)
2015-05-04 03:53:29 -04:00
console.debug(data);
2015-06-01 06:04:25 -04:00
for (var i = 0; i < onlineUsers.length; i++) {
if (onlineUsers[i].id == data.id) {
onlineUsers[i].cursor = data;
}
}
2015-05-15 00:58:13 -04:00
if (data.id != socket.id)
2015-06-01 06:04:25 -04:00
buildCursor(data);
2015-05-04 03:53:29 -04:00
});
socket.on('cursor blur', function (data) {
2015-05-15 00:58:13 -04:00
if (debug)
2015-05-04 03:53:29 -04:00
console.debug(data);
2015-06-01 06:04:25 -04:00
for (var i = 0; i < onlineUsers.length; i++) {
if (onlineUsers[i].id == data.id) {
onlineUsers[i].cursor = null;
}
}
if (data.id != socket.id)
buildCursor(data);
//force hide
2015-05-04 03:53:29 -04:00
var cursor = $('#' + data.id);
2015-05-15 00:58:13 -04:00
if (cursor.length > 0) {
2015-06-01 06:04:25 -04:00
cursor.stop(true).fadeOut();
2015-05-04 03:53:29 -04:00
}
});
2015-05-15 00:58:13 -04:00
2015-06-01 06:04:25 -04:00
var options = {
valueNames: ['id', 'name'],
item: '<li class="ui-user-item">\
<span class="id" style="display:none;"></span>\
<a href="#">\
2015-07-04 10:19:09 -04:00
<span class="pull-left"><i class="ui-user-icon"></i></span><span class="ui-user-name name"></span><span class="pull-right"><i class="fa fa-circle ui-user-status"></i></span>\
2015-06-01 06:04:25 -04:00
</a>\
</li>'
};
var onlineUserList = new List('online-user-list', options);
var shortOnlineUserList = new List('short-online-user-list', options);
function updateOnlineStatus() {
2015-07-01 12:10:20 -04:00
if (!loaded || !socket.connected) return;
2015-06-01 06:04:25 -04:00
var _onlineUsers = deduplicateOnlineUsers(onlineUsers);
showStatus(statusType.online, _onlineUsers.length);
var items = onlineUserList.items;
//update or remove current list items
for (var i = 0; i < items.length; i++) {
var found = false;
var foundindex = null;
for (var j = 0; j < _onlineUsers.length; j++) {
if (items[i].values().id == _onlineUsers[j].id) {
foundindex = j;
found = true;
break;
}
}
var id = items[i].values().id;
if (found) {
onlineUserList.get('id', id)[0].values(_onlineUsers[foundindex]);
shortOnlineUserList.get('id', id)[0].values(_onlineUsers[foundindex]);
} else {
onlineUserList.remove('id', id);
shortOnlineUserList.remove('id', id);
}
}
//add not in list items
for (var i = 0; i < _onlineUsers.length; i++) {
var found = false;
for (var j = 0; j < items.length; j++) {
if (items[j].values().id == _onlineUsers[i].id) {
found = true;
break;
}
2015-05-04 03:53:29 -04:00
}
2015-06-01 06:04:25 -04:00
if (!found) {
onlineUserList.add(_onlineUsers[i]);
shortOnlineUserList.add(_onlineUsers[i]);
}
}
//sorting
sortOnlineUserList(onlineUserList);
sortOnlineUserList(shortOnlineUserList);
//render list items
renderUserStatusList(onlineUserList);
renderUserStatusList(shortOnlineUserList);
}
function sortOnlineUserList(list) {
//sort order by isSelf, login state, idle state, alphabet name, color brightness
list.sort('', {
sortFunction: function (a, b) {
var usera = a.values();
var userb = b.values();
var useraIsSelf = (usera.id == personalInfo.id || (usera.login && usera.userid == personalInfo.userid));
var userbIsSelf = (userb.id == personalInfo.id || (userb.login && userb.userid == personalInfo.userid));
if (useraIsSelf && !userbIsSelf) {
return -1;
2015-07-01 12:10:20 -04:00
} else if (!useraIsSelf && userbIsSelf) {
2015-06-01 06:04:25 -04:00
return 1;
} else {
if (usera.login && !userb.login)
return -1;
else if (!usera.login && userb.login)
return 1;
else {
if (!usera.idle && userb.idle)
return -1;
else if (usera.idle && !userb.idle)
return 1;
else {
if (usera.name.toLowerCase() < userb.name.toLowerCase()) {
return -1;
} else if (usera.name.toLowerCase() > userb.name.toLowerCase()) {
return 1;
} else {
if (usera.color.toLowerCase() < userb.color.toLowerCase())
return -1;
else if (usera.color.toLowerCase() > userb.color.toLowerCase())
return 1;
else
return 0;
}
}
}
}
}
});
2015-05-04 03:53:29 -04:00
}
2015-06-01 06:04:25 -04:00
function renderUserStatusList(list) {
var items = list.items;
for (var j = 0; j < items.length; j++) {
var item = items[j];
var userstatus = $(item.elm).find('.ui-user-status');
var usericon = $(item.elm).find('.ui-user-icon');
if (item.values().login && item.values().photo) {
2015-07-04 10:19:09 -04:00
usericon.css('background-image', 'url(' + item.values().photo + ')');
usericon.css('box-shadow', '0px 0px 2px ' + item.values().color);
//add 1px more to right, make it feel aligned
usericon.css('margin-right', '6px');
} else {
usericon.css('background-color', item.values().color);
}
2015-06-01 06:04:25 -04:00
userstatus.removeClass('ui-user-status-offline ui-user-status-online ui-user-status-idle');
if (item.values().idle)
userstatus.addClass('ui-user-status-idle');
else
userstatus.addClass('ui-user-status-online');
}
}
function deduplicateOnlineUsers(list) {
var _onlineUsers = [];
for (var i = 0; i < list.length; i++) {
var user = $.extend({}, list[i]);
if (!user.userid)
_onlineUsers.push(user);
else {
var found = false;
for (var j = 0; j < _onlineUsers.length; j++) {
if (_onlineUsers[j].userid == user.userid) {
//keep self color when login
if (user.id == personalInfo.id) {
_onlineUsers[j].color = user.color;
}
//keep idle state if any of self client not idle
if (!user.idle) {
_onlineUsers[j].idle = user.idle;
2015-07-04 10:19:09 -04:00
_onlineUsers[j].color = user.color;
2015-06-01 06:04:25 -04:00
}
found = true;
break;
}
}
if (!found)
_onlineUsers.push(user);
}
}
return _onlineUsers;
}
var userStatusCache = null;
function emitUserStatus(force) {
if (!loaded) return;
var type = null;
if (visibleXS)
type = 'xs';
else if (visibleSM)
type = 'sm';
else if (visibleMD)
type = 'md';
else if (visibleLG)
type = 'lg';
personalInfo['idle'] = idle.isAway;
personalInfo['type'] = type;
for (var i = 0; i < onlineUsers.length; i++) {
if (onlineUsers[i].id == personalInfo.id) {
onlineUsers[i] = personalInfo;
}
}
var userStatus = {
idle: idle.isAway,
type: type
};
if (force || JSON.stringify(userStatus) != JSON.stringify(userStatusCache)) {
socket.emit('user status', userStatus);
userStatusCache = userStatus;
}
}
function checkCursorTag(coord, ele) {
var curosrtagMargin = 60;
var viewport = editor.getViewport();
var viewportHeight = (viewport.to - viewport.from) * editor.defaultTextHeight();
var editorWidth = ui.area.codemirror.width();
var editorHeight = ui.area.codemirror.height();
var width = ele.width();
var height = ele.height();
var left = coord.left;
var top = coord.top;
var offsetLeft = -3;
var offsetTop = defaultTextHeight;
if (width > 0 && height > 0) {
if (left + width + offsetLeft > editorWidth - curosrtagMargin) {
2015-07-01 12:10:20 -04:00
offsetLeft = -(width + 10);
2015-06-01 06:04:25 -04:00
}
if (top + height + offsetTop > Math.max(viewportHeight, editorHeight) + curosrtagMargin && top - height > curosrtagMargin) {
offsetTop = -(height);
}
}
ele[0].style.left = offsetLeft + 'px';
ele[0].style.top = offsetTop + 'px';
}
function buildCursor(user) {
if (!user.cursor) return;
var coord = editor.charCoords(user.cursor, 'windows');
coord.left = coord.left < 4 ? 4 : coord.left;
coord.top = coord.top < 0 ? 0 : coord.top;
var iconClass = 'fa-user';
switch (user.type) {
case 'xs':
iconClass = 'fa-mobile';
break;
case 'sm':
iconClass = 'fa-tablet';
break;
case 'md':
iconClass = 'fa-desktop';
break;
case 'lg':
iconClass = 'fa-desktop';
break;
}
2015-05-04 03:53:29 -04:00
if ($('.other-cursors').length <= 0) {
$("<div class='other-cursors'>").insertAfter('.CodeMirror-cursors');
}
2015-06-01 06:04:25 -04:00
if ($('#' + user.id).length <= 0) {
var cursor = $('<div id="' + user.id + '" class="other-cursor" style="display:none;"></div>');
cursor.attr('data-line', user.cursor.line);
cursor.attr('data-ch', user.cursor.ch);
cursor.attr('data-offset-left', 0);
cursor.attr('data-offset-top', 0);
var cursorbar = $('<div class="cursorbar">&nbsp;</div>');
cursorbar[0].style.height = defaultTextHeight + 'px';
cursorbar[0].style.borderLeft = '2px solid ' + user.color;
var icon = '<i class="fa ' + iconClass + '"></i>';
var cursortag = $('<div class="cursortag">' + icon + '&nbsp;<span class="name">' + user.name + '</span></div>');
//cursortag[0].style.background = color;
cursortag[0].style.color = user.color;
cursor.attr('data-mode', 'state');
cursor.hover(
function () {
if (cursor.attr('data-mode') == 'hover')
cursortag.stop(true).fadeIn("fast");
},
function () {
if (cursor.attr('data-mode') == 'hover')
cursortag.stop(true).fadeOut("fast");
});
function switchMode(ele) {
if (ele.attr('data-mode') == 'state')
ele.attr('data-mode', 'hover');
else if (ele.attr('data-mode') == 'hover')
ele.attr('data-mode', 'state');
}
function switchTag(ele) {
if (ele.css('display') === 'none')
ele.stop(true).fadeIn("fast");
else
ele.stop(true).fadeOut("fast");
}
var hideCursorTagDelay = 2000;
var hideCursorTagTimer = null;
function hideCursorTag() {
if (cursor.attr('data-mode') == 'hover')
cursortag.fadeOut("fast");
}
cursor.on('touchstart', function (e) {
var display = cursortag.css('display');
cursortag.stop(true).fadeIn("fast");
clearTimeout(hideCursorTagTimer);
hideCursorTagTimer = setTimeout(hideCursorTag, hideCursorTagDelay);
if (display === 'none') {
e.preventDefault();
e.stopPropagation();
}
});
cursortag.on('mousedown touchstart', function (e) {
if (cursor.attr('data-mode') == 'state')
switchTag(cursortag);
switchMode(cursor);
e.preventDefault();
e.stopPropagation();
});
cursor.append(cursorbar);
cursor.append(cursortag);
2015-05-04 03:53:29 -04:00
cursor[0].style.left = coord.left + 'px';
cursor[0].style.top = coord.top + 'px';
$('.other-cursors').append(cursor);
2015-06-01 06:04:25 -04:00
if (!user.idle)
cursor.stop(true).fadeIn();
checkCursorTag(coord, cursortag);
2015-05-04 03:53:29 -04:00
} else {
2015-06-01 06:04:25 -04:00
var cursor = $('#' + user.id);
var lineDiff = Math.abs(cursor.attr('data-line') - user.cursor.line);
2015-06-01 06:04:25 -04:00
cursor.attr('data-line', user.cursor.line);
cursor.attr('data-ch', user.cursor.ch);
var cursorbar = cursor.find('.cursorbar');
cursorbar[0].style.height = defaultTextHeight + 'px';
cursorbar[0].style.borderLeft = '2px solid ' + user.color;
var cursortag = cursor.find('.cursortag');
cursortag.find('i').removeClass().addClass('fa').addClass(iconClass);
cursortag.find(".name").text(user.name);
if (cursor.css('display') === 'none') {
cursor[0].style.left = coord.left + 'px';
cursor[0].style.top = coord.top + 'px';
} else {
cursor.animate({
"left": coord.left,
"top": coord.top
}, {
duration: cursorAnimatePeriod,
queue: false
});
}
if (user.idle && cursor.css('display') !== 'none')
cursor.stop(true).fadeOut();
else if (!user.idle && cursor.css('display') === 'none')
cursor.stop(true).fadeIn();
checkCursorTag(coord, cursortag);
2015-05-04 03:53:29 -04:00
}
}
//editor actions
function enforceMaxLength(cm, change) {
var maxLength = cm.getOption("maxLength");
if (maxLength && change.update) {
var str = change.text.join("\n");
var delta = str.length - (cm.indexFromPos(change.to) - cm.indexFromPos(change.from));
if (delta <= 0) {
return false;
}
delta = cm.getValue().length + delta - maxLength;
if (delta > 0) {
str = str.substr(0, str.length - delta);
change.update(change.from, change.to, str.split("\n"));
return true;
}
}
return false;
}
var ignoreEmitEvents = ['setValue', 'ignoreHistory'];
2015-05-04 03:53:29 -04:00
editor.on('beforeChange', function (cm, change) {
if (debug)
console.debug(change);
if (enforceMaxLength(cm, change)) {
$('.limit-modal').modal('show');
}
var isIgnoreEmitEvent = (ignoreEmitEvents.indexOf(change.origin) != -1);
if (!isIgnoreEmitEvent) {
switch (permission) {
case "freely":
//na
break;
case "editable":
if (!personalInfo.login) {
change.canceled = true;
$('.signin-modal').modal('show');
}
break;
case "locked":
if (personalInfo.userid != owner) {
change.canceled = true;
$('.locked-modal').modal('show');
2015-07-01 12:10:20 -04:00
}
break;
2015-07-01 12:10:20 -04:00
}
}
2015-05-04 03:53:29 -04:00
});
editor.on('focus', function (cm) {
2015-06-01 06:04:25 -04:00
for (var i = 0; i < onlineUsers.length; i++) {
if (onlineUsers[i].id == personalInfo.id) {
onlineUsers[i].cursor = editor.getCursor();
}
}
personalInfo['cursor'] = editor.getCursor();
2015-05-04 03:53:29 -04:00
socket.emit('cursor focus', editor.getCursor());
});
var cursorActivityTimer = null;
editor.on('cursorActivity', function (cm) {
clearTimeout(cursorActivityTimer);
cursorActivityTimer = setTimeout(cursorActivity, cursorActivityDelay);
});
2015-05-15 00:58:13 -04:00
2015-05-04 03:53:29 -04:00
function cursorActivity() {
2015-06-01 06:04:25 -04:00
if (editorHasFocus() && !Visibility.hidden()) {
for (var i = 0; i < onlineUsers.length; i++) {
if (onlineUsers[i].id == personalInfo.id) {
onlineUsers[i].cursor = editor.getCursor();
}
}
personalInfo['cursor'] = editor.getCursor();
socket.emit('cursor activity', editor.getCursor());
}
2015-05-04 03:53:29 -04:00
}
editor.on('blur', function (cm) {
2015-06-01 06:04:25 -04:00
for (var i = 0; i < onlineUsers.length; i++) {
if (onlineUsers[i].id == personalInfo.id) {
onlineUsers[i].cursor = null;
}
}
personalInfo['cursor'] = null;
2015-05-04 03:53:29 -04:00
socket.emit('cursor blur');
});
function saveInfo() {
2015-06-01 06:04:25 -04:00
var scrollbarStyle = editor.getOption('scrollbarStyle');
2015-05-04 03:53:29 -04:00
var left = $(document.body).scrollLeft();
var top = $(document.body).scrollTop();
switch (currentMode) {
case modeType.edit:
2015-06-01 06:04:25 -04:00
if (scrollbarStyle == 'native') {
lastInfo.edit.scroll.left = left;
lastInfo.edit.scroll.top = top;
} else {
lastInfo.edit.scroll = editor.getScrollInfo();
}
2015-05-04 03:53:29 -04:00
break;
case modeType.view:
lastInfo.view.scroll.left = left;
lastInfo.view.scroll.top = top;
break;
case modeType.both:
lastInfo.edit.scroll = editor.getScrollInfo();
lastInfo.view.scroll.left = ui.area.view.scrollLeft();
lastInfo.view.scroll.top = ui.area.view.scrollTop();
break;
}
lastInfo.edit.cursor = editor.getCursor();
lastInfo.needRestore = true;
}
function restoreInfo() {
2015-06-01 06:04:25 -04:00
var scrollbarStyle = editor.getOption('scrollbarStyle');
2015-05-04 03:53:29 -04:00
if (lastInfo.needRestore) {
var line = lastInfo.edit.cursor.line;
var ch = lastInfo.edit.cursor.ch;
editor.setCursor(line, ch);
switch (currentMode) {
case modeType.edit:
2015-06-01 06:04:25 -04:00
if (scrollbarStyle == 'native') {
$(document.body).scrollLeft(lastInfo.edit.scroll.left);
$(document.body).scrollTop(lastInfo.edit.scroll.top);
} else {
var left = lastInfo.edit.scroll.left;
var top = lastInfo.edit.scroll.top;
editor.scrollIntoView();
editor.scrollTo(left, top);
}
2015-05-04 03:53:29 -04:00
break;
case modeType.view:
$(document.body).scrollLeft(lastInfo.view.scroll.left);
$(document.body).scrollTop(lastInfo.view.scroll.top);
break;
case modeType.both:
var left = lastInfo.edit.scroll.left;
var top = lastInfo.edit.scroll.top;
editor.scrollIntoView();
editor.scrollTo(left, top);
ui.area.view.scrollLeft(lastInfo.view.scroll.left);
ui.area.view.scrollTop(lastInfo.view.scroll.top);
break;
}
lastInfo.needRestore = false;
}
}
//view actions
var finishChangeTimer = null;
2015-07-01 12:10:20 -04:00
function finishChange(emit) {
2015-05-04 03:53:29 -04:00
updateView();
}
var lastResult = null;
function updateView() {
if (currentMode == modeType.edit || !isDirty) return;
var value = editor.getValue();
var result = postProcess(md.render(value)).children().toArray();
partialUpdate(result, lastResult, ui.area.markdown.children().toArray());
2015-06-01 06:04:25 -04:00
if (result && lastResult && result.length != lastResult.length)
updateDataAttrs(result, ui.area.markdown.children().toArray());
lastResult = $(result).clone();
2015-05-04 03:53:29 -04:00
finishView(ui.area.view);
2015-07-01 12:10:20 -04:00
autoLinkify(ui.area.view);
generateToc('toc');
generateToc('toc-affix');
generateScrollspy();
smoothHashScroll();
2015-05-04 03:53:29 -04:00
writeHistory(ui.area.markdown);
isDirty = false;
2015-05-15 00:58:13 -04:00
clearMap();
2015-06-01 06:04:25 -04:00
buildMap();
}
function updateDataAttrs(src, des) {
//sync data attr startline and endline
for (var i = 0; i < src.length; i++) {
copyAttribute(src[i], des[i], 'data-startline');
copyAttribute(src[i], des[i], 'data-endline');
}
2015-05-04 03:53:29 -04:00
}
function partialUpdate(src, tar, des) {
if (!src || src.length == 0 || !tar || tar.length == 0 || !des || des.length == 0) {
ui.area.markdown.html(src);
return;
}
if (src.length == tar.length) { //same length
for (var i = 0; i < src.length; i++) {
copyAttribute(src[i], des[i], 'data-startline');
copyAttribute(src[i], des[i], 'data-endline');
var rawSrc = cloneAndRemoveDataAttr(src[i]);
var rawTar = cloneAndRemoveDataAttr(tar[i]);
if (rawSrc.outerHTML != rawTar.outerHTML) {
//console.log(rawSrc);
//console.log(rawTar);
$(des[i]).replaceWith(src[i]);
}
}
} else { //diff length
var start = 0;
var end = 0;
//find diff start position
for (var i = 0; i < tar.length; i++) {
2015-06-01 06:04:25 -04:00
//copyAttribute(src[i], des[i], 'data-startline');
//copyAttribute(src[i], des[i], 'data-endline');
2015-05-04 03:53:29 -04:00
var rawSrc = cloneAndRemoveDataAttr(src[i]);
var rawTar = cloneAndRemoveDataAttr(tar[i]);
if (!rawSrc || !rawTar || rawSrc.outerHTML != rawTar.outerHTML) {
start = i;
break;
}
}
//find diff end position
var srcEnd = 0;
var tarEnd = 0;
for (var i = 0; i < src.length; i++) {
2015-06-01 06:04:25 -04:00
//copyAttribute(src[i], des[i], 'data-startline');
//copyAttribute(src[i], des[i], 'data-endline');
2015-05-04 03:53:29 -04:00
var rawSrc = cloneAndRemoveDataAttr(src[i]);
var rawTar = cloneAndRemoveDataAttr(tar[i]);
if (!rawSrc || !rawTar || rawSrc.outerHTML != rawTar.outerHTML) {
start = i;
break;
}
}
//tar end
2015-05-15 00:58:13 -04:00
for (var i = 1; i <= tar.length + 1; i++) {
2015-05-04 03:53:29 -04:00
var srcLength = src.length;
var tarLength = tar.length;
2015-06-01 06:04:25 -04:00
//copyAttribute(src[srcLength - i], des[srcLength - i], 'data-startline');
//copyAttribute(src[srcLength - i], des[srcLength - i], 'data-endline');
2015-05-04 03:53:29 -04:00
var rawSrc = cloneAndRemoveDataAttr(src[srcLength - i]);
var rawTar = cloneAndRemoveDataAttr(tar[tarLength - i]);
if (!rawSrc || !rawTar || rawSrc.outerHTML != rawTar.outerHTML) {
tarEnd = tar.length - i;
break;
}
}
//src end
2015-05-15 00:58:13 -04:00
for (var i = 1; i <= src.length + 1; i++) {
2015-05-04 03:53:29 -04:00
var srcLength = src.length;
var tarLength = tar.length;
2015-06-01 06:04:25 -04:00
//copyAttribute(src[srcLength - i], des[srcLength - i], 'data-startline');
//copyAttribute(src[srcLength - i], des[srcLength - i], 'data-endline');
2015-05-04 03:53:29 -04:00
var rawSrc = cloneAndRemoveDataAttr(src[srcLength - i]);
var rawTar = cloneAndRemoveDataAttr(tar[tarLength - i]);
if (!rawSrc || !rawTar || rawSrc.outerHTML != rawTar.outerHTML) {
srcEnd = src.length - i;
break;
}
}
//check if tar end overlap tar start
var overlap = 0;
for (var i = start; i >= 0; i--) {
2015-05-15 00:58:13 -04:00
var rawTarStart = cloneAndRemoveDataAttr(tar[i - 1]);
var rawTarEnd = cloneAndRemoveDataAttr(tar[tarEnd + 1 + start - i]);
if (rawTarStart && rawTarEnd && rawTarStart.outerHTML == rawTarEnd.outerHTML)
2015-05-04 03:53:29 -04:00
overlap++;
else
break;
}
2015-05-15 00:58:13 -04:00
if (debug)
2015-05-04 03:53:29 -04:00
console.log('overlap:' + overlap);
//show diff content
2015-05-15 00:58:13 -04:00
if (debug) {
2015-05-04 03:53:29 -04:00
console.log('start:' + start);
console.log('tarEnd:' + tarEnd);
console.log('srcEnd:' + srcEnd);
}
tarEnd += overlap;
srcEnd += overlap;
2015-05-15 00:58:13 -04:00
var repeatAdd = (start - srcEnd) < (start - tarEnd);
var repeatDiff = Math.abs(srcEnd - tarEnd) - 1;
//push new elements
var newElements = [];
2015-06-01 06:04:25 -04:00
if (srcEnd >= start) {
2015-05-15 00:58:13 -04:00
for (var j = start; j <= srcEnd; j++) {
if (!src[j]) continue;
newElements.push(src[j].outerHTML);
}
2015-06-01 06:04:25 -04:00
} else if (repeatAdd) {
2015-05-15 00:58:13 -04:00
for (var j = srcEnd - repeatDiff; j <= srcEnd; j++) {
if (!des[j]) continue;
newElements.push(des[j].outerHTML);
}
2015-05-04 03:53:29 -04:00
}
2015-05-15 00:58:13 -04:00
//push remove elements
var removeElements = [];
2015-06-01 06:04:25 -04:00
if (tarEnd >= start) {
2015-05-15 00:58:13 -04:00
for (var j = start; j <= tarEnd; j++) {
if (!des[j]) continue;
removeElements.push(des[j]);
}
2015-06-01 06:04:25 -04:00
} else if (!repeatAdd) {
2015-05-15 00:58:13 -04:00
for (var j = start; j <= start + repeatDiff; j++) {
if (!des[j]) continue;
removeElements.push(des[j]);
}
2015-05-04 03:53:29 -04:00
}
2015-05-15 00:58:13 -04:00
//add elements
if (debug) {
console.log('ADD ELEMENTS');
console.log(newElements.join('\n'));
2015-05-04 03:53:29 -04:00
}
2015-05-15 00:58:13 -04:00
if (des[start])
$(newElements.join('')).insertBefore(des[start]);
else
$(newElements.join('')).insertAfter(des[start - 1]);
//remove elements
if (debug)
console.log('REMOVE ELEMENTS');
for (var j = 0; j < removeElements.length; j++) {
if (debug) {
console.log(removeElements[j].outerHTML);
}
if (removeElements[j])
removeElements[j].remove();
2015-05-04 03:53:29 -04:00
}
}
}
function cloneAndRemoveDataAttr(el) {
2015-05-15 00:58:13 -04:00
if (!el) return;
2015-06-01 06:04:25 -04:00
var rawEl = $(el).clone()[0];
2015-05-04 03:53:29 -04:00
rawEl.removeAttribute('data-startline');
rawEl.removeAttribute('data-endline');
return rawEl;
}
function copyAttribute(src, des, attr) {
if (src && src.getAttribute(attr) && des)
des.setAttribute(attr, src.getAttribute(attr));
2015-06-01 06:04:25 -04:00
}
if ($('.cursor-menu').length <= 0) {
$("<div class='cursor-menu'>").insertAfter('.CodeMirror-cursors');
}
var upSideDown = false;
var menuMargin = 60;
function checkCursorMenu() {
var dropdown = $('.cursor-menu .dropdown-menu');
var cursor = editor.getCursor();
var scrollInfo = editor.getScrollInfo();
if (!dropdown.hasClass('other-cursor'))
dropdown.addClass('other-cursor');
dropdown.attr('data-line', cursor.line);
dropdown.attr('data-ch', cursor.ch);
var coord = editor.charCoords({
line: cursor.line,
ch: cursor.ch
}, 'windows');
var viewport = editor.getViewport();
var viewportHeight = (viewport.to - viewport.from) * editor.defaultTextHeight();
var editorWidth = ui.area.codemirror.width();
var editorHeight = ui.area.codemirror.height();
var width = dropdown.width();
var height = dropdown.height();
var left = coord.left;
var top = coord.top;
var offsetLeft = 0;
var offsetTop = defaultTextHeight;
if (left + width + offsetLeft > editorWidth - menuMargin)
offsetLeft = -(left + width - editorWidth + menuMargin);
if (top + height + offsetTop > Math.max(viewportHeight, editorHeight) + menuMargin && top - height > menuMargin) {
offsetTop = -(height + defaultTextHeight);
upSideDown = true;
} else {
upSideDown = false;
}
dropdown.attr('data-offset-left', offsetLeft);
dropdown.attr('data-offset-top', offsetTop);
dropdown[0].style.left = left + offsetLeft + 'px';
dropdown[0].style.top = top + offsetTop + 'px';
}
var isInCode = false;
function check(text) {
var cursor = editor.getCursor();
text = [];
for (var i = 0; i < cursor.line; i++)
text.push(editor.getLine(i));
text = text.join('\n') + '\n' + editor.getLine(cursor.line).slice(0, cursor.ch);
//console.log(text);
var match;
match = text.match(/`{3,}/g);
if (match && match.length % 2) {
isInCode = true;
} else {
match = text.match(/`/g);
if (match && match.length % 2) {
isInCode = true;
} else {
isInCode = false;
}
}
}
$(editor.getInputField())
.textcomplete([
{ // emoji strategy
match: /(?:^|\n|)\B:([\-+\w]*)$/,
search: function (term, callback) {
callback($.map(emojify.emojiNames, function (emoji) {
return emoji.indexOf(term) === 0 ? emoji : null;
}));
checkCursorMenu();
},
template: function (value) {
return '<img class="emoji" src="/vendor/emojify/images/' + value + '.png"></img> ' + value;
},
replace: function (value) {
return ':' + value + ':';
},
index: 1,
context: function (text) {
check(text);
return !isInCode;
}
},
{ // Code block language strategy
langs: supportCodeModes,
match: /(^|\n)```(\w+)$/,
2015-06-01 06:04:25 -04:00
search: function (term, callback) {
callback($.map(this.langs, function (lang) {
return lang.indexOf(term) === 0 ? lang : null;
}));
checkCursorMenu();
},
replace: function (lang) {
return '$1```' + lang + '=\n\n```';
},
done: function () {
2015-07-01 12:10:20 -04:00
editor.doc.cm.execCommand("goLineUp");
2015-06-01 06:04:25 -04:00
},
context: function () {
return isInCode;
}
},
{ //header
match: /(?:^|\n)(\s{0,3})(#{1,6}\w*)$/,
search: function (term, callback) {
callback($.map(supportHeaders, function (header) {
return header.search.indexOf(term) === 0 ? header.text : null;
}));
checkCursorMenu();
},
replace: function (value) {
return '$1' + value;
},
context: function (text) {
return !isInCode;
}
},
2015-07-01 12:10:20 -04:00
{ //blockquote personal info & general info
match: /(?:^|\n|\s)(\>.*)(\[\])(\w*)$/,
2015-06-01 06:04:25 -04:00
search: function (term, callback) {
2015-07-01 12:10:20 -04:00
var list = [];
$.map(supportBlockquoteTags, function (blockquotetag) {
if (blockquotetag.search.indexOf(term) === 0)
list.push(blockquotetag.command());
});
$.map(supportReferrals, function (referral) {
if (referral.search.indexOf(term) === 0)
list.push(referral.text);
})
callback(list);
2015-06-01 06:04:25 -04:00
checkCursorMenu();
},
replace: function (value) {
return '$1' + value;
},
context: function (text) {
return !isInCode;
}
},
2015-07-01 12:10:20 -04:00
{ //referral
match: /(^|\n|\s)(\!|\!|\[\])(\w*)$/,
2015-06-01 06:04:25 -04:00
search: function (term, callback) {
2015-07-01 12:10:20 -04:00
callback($.map(supportReferrals, function (referral) {
return referral.search.indexOf(term) === 0 ? referral.text : null;
2015-06-01 06:04:25 -04:00
}));
checkCursorMenu();
},
replace: function (value) {
return '$1' + value;
},
context: function (text) {
return !isInCode;
}
},
2015-07-01 12:10:20 -04:00
{ //externals
match: /(^|\n|\s)\{\}(\w*)$/,
2015-06-01 06:04:25 -04:00
search: function (term, callback) {
2015-07-01 12:10:20 -04:00
callback($.map(supportExternals, function (external) {
return external.search.indexOf(term) === 0 ? external.text : null;
}));
2015-06-01 06:04:25 -04:00
checkCursorMenu();
},
replace: function (value) {
2015-07-01 12:10:20 -04:00
return '$1' + value;
2015-06-01 06:04:25 -04:00
},
context: function (text) {
return !isInCode;
}
}
], {
appendTo: $('.cursor-menu')
})
.on({
'textComplete:select': function (e, value, strategy) {
//NA
},
'textComplete:show': function (e) {
checkCursorMenu();
$(this).data('autocompleting', true);
editor.setOption("extraKeys", {
"Up": function () {
return CodeMirror.PASS;
},
"Right": function () {
editor.doc.cm.execCommand("goCharRight");
},
"Down": function () {
return CodeMirror.PASS;
},
"Left": function () {
editor.doc.cm.execCommand("goCharLeft");
},
"Enter": function () {
return CodeMirror.PASS;
},
"Backspace": function () {
editor.doc.cm.execCommand("delCharBefore");
checkCursorMenu();
}
});
},
'textComplete:hide': function (e) {
$(this).data('autocompleting', false);
editor.setOption("extraKeys", defaultExtraKeys);
}
});