Stackedit/js/core.js

514 lines
19 KiB
JavaScript
Raw Normal View History

2013-05-26 22:59:03 +00:00
define([
"jquery",
2013-05-29 19:55:23 +00:00
"underscore",
2013-05-26 22:59:03 +00:00
"utils",
2013-05-27 19:45:33 +00:00
"settings",
2013-06-10 21:22:32 +00:00
"extensionMgr",
"mousetrap",
"text!html/settingsTemplateTooltip.html",
2013-05-26 22:59:03 +00:00
"storage",
"config",
2013-06-02 00:38:23 +00:00
"libs/bootstrap",
"libs/layout",
"libs/Markdown.Editor"
2013-06-10 21:22:32 +00:00
], function($, _, utils, settings, extensionMgr, mousetrap, settingsTemplateTooltipHTML) {
2013-04-02 18:42:47 +00:00
2013-05-29 19:55:23 +00:00
var core = {};
// Used for periodic tasks
var intervalId = undefined;
2013-06-10 22:32:34 +00:00
var periodicCallbacks = [extensionMgr.onPeriodicRun];
2013-05-29 19:55:23 +00:00
core.addPeriodicCallback = function(callback) {
periodicCallbacks.push(callback);
};
// Used to detect user activity
var userReal = false;
var userActive = false;
var windowUnique = true;
var userLastActivity = 0;
function setUserActive() {
userReal = true;
userActive = true;
userLastActivity = utils.currentTime;
}
function isUserActive() {
if(userActive === true && utils.currentTime - userLastActivity > USER_IDLE_THRESHOLD) {
userActive = false;
}
return userActive && windowUnique;
}
// Used to only have 1 window of the application in the same browser
var windowId = undefined;
function checkWindowUnique() {
if(userReal === false || windowUnique === false) {
return;
}
if(windowId === undefined) {
windowId = utils.randomString();
localStorage["frontWindowId"] = windowId;
}
var frontWindowId = localStorage["frontWindowId"];
if(frontWindowId != windowId) {
windowUnique = false;
if(intervalId !== undefined) {
clearInterval(intervalId);
}
$(".modal").modal("hide");
$('#modal-non-unique').modal({
backdrop: "static",
keyboard: false
});
}
}
// Offline management
core.isOffline = false;
var offlineTime = utils.currentTime;
core.setOffline = function() {
offlineTime = utils.currentTime;
if(core.isOffline === false) {
core.isOffline = true;
extensionMgr.onOfflineChanged(true);
}
};
function setOnline() {
if(core.isOffline === true) {
core.isOffline = false;
extensionMgr.onOfflineChanged(false);
}
}
function checkOnline() {
// Try to reconnect if we are offline but we have some network
if(core.isOffline === true && navigator.onLine === true && offlineTime + CHECK_ONLINE_PERIOD < utils.currentTime) {
offlineTime = utils.currentTime;
// Try to download anything to test the connection
$.ajax({
url: "//www.google.com/jsapi",
timeout: AJAX_TIMEOUT,
dataType: "script"
}).done(function() {
setOnline();
});
}
}
// Load settings in settings dialog
function loadSettings() {
// Layout orientation
utils.setInputRadio("radio-layout-orientation", settings.layoutOrientation);
// Theme
utils.setInputValue("#input-settings-theme", localStorage.theme);
// Lazy rendering
utils.setInputChecked("#input-settings-lazy-rendering", settings.lazyRendering);
// Editor font size
utils.setInputValue("#input-settings-editor-font-size", settings.editorFontSize);
// Default content
utils.setInputValue("#textarea-settings-default-content", settings.defaultContent);
// Commit message
utils.setInputValue("#input-settings-publish-commit-msg", settings.commitMsg);
// Template
utils.setInputValue("#textarea-settings-publish-template", settings.template);
// SSH proxy
utils.setInputValue("#input-settings-ssh-proxy", settings.sshProxy);
// Load extension settings
extensionMgr.onLoadSettings();
}
// Save settings from settings dialog
function saveSettings(event) {
var newSettings = {};
// Layout orientation
newSettings.layoutOrientation = utils.getInputRadio("radio-layout-orientation");
// Theme
var theme = utils.getInputValue("#input-settings-theme");
// Lazy Rendering
newSettings.lazyRendering = utils.getInputChecked("#input-settings-lazy-rendering");
// Editor font size
newSettings.editorFontSize = utils.getInputIntValue("#input-settings-editor-font-size", event, 1, 99);
// Default content
newSettings.defaultContent = utils.getInputValue("#textarea-settings-default-content");
// Commit message
newSettings.commitMsg = utils.getInputTextValue("#input-settings-publish-commit-msg", event);
// Template
newSettings.template = utils.getInputTextValue("#textarea-settings-publish-template", event);
// SSH proxy
newSettings.sshProxy = utils.checkUrl(utils.getInputTextValue("#input-settings-ssh-proxy", event), true);
// Save extension settings
newSettings.extensionSettings = {};
extensionMgr.onSaveSettings(newSettings.extensionSettings, event);
if(!event.isPropagationStopped()) {
$.extend(settings, newSettings);
localStorage.settings = JSON.stringify(settings);
localStorage.theme = theme;
}
}
// Create the layout
var layout = undefined;
core.createLayout = function() {
if(viewerMode === true) {
return;
}
var layoutGlobalConfig = {
closable: true,
resizable: false,
slidable: false,
livePaneResizing: true,
enableCursorHotkey: false,
spacing_open: 15,
spacing_closed: 15,
togglerLength_open: 90,
togglerLength_closed: 90,
stateManagement__enabled: false,
center__minWidth: 200,
center__minHeight: 200
};
extensionMgr.onLayoutConfigure(layoutGlobalConfig);
if(settings.layoutOrientation == "horizontal") {
$(".ui-layout-south").remove();
2013-06-12 20:37:43 +00:00
$(".preview-container").html('<div id="wmd-preview"></div>');
2013-05-29 19:55:23 +00:00
layout = $('body').layout($.extend(layoutGlobalConfig, {
east__resizable: true,
east__size: .5,
east__minSize: 200
}));
}
else if(settings.layoutOrientation == "vertical") {
$(".ui-layout-east").remove();
2013-06-12 20:37:43 +00:00
$(".preview-container").html('<div id="wmd-preview"></div>');
2013-05-29 19:55:23 +00:00
layout = $('body').layout($.extend(layoutGlobalConfig, {
south__resizable: true,
south__size: .5,
south__minSize: 200
}));
}
$(".ui-layout-toggler-north").addClass("btn").append($("<b>").addClass("caret"));
$(".ui-layout-toggler-south").addClass("btn").append($("<b>").addClass("caret"));
$(".ui-layout-toggler-east").addClass("btn").append($("<b>").addClass("caret"));
$("#navbar").click(function() {
layout.allowOverflow('north');
});
extensionMgr.onLayoutCreated(layout);
};
// Create the PageDown editor
2013-06-02 00:38:23 +00:00
var editor = undefined;
2013-06-03 22:19:52 +00:00
var fileDesc = undefined;
2013-06-02 00:38:23 +00:00
var documentContent = undefined;
2013-06-03 22:19:52 +00:00
var undoManager = undefined;
core.createEditor = function(fileDescParam) {
fileDesc = fileDescParam;
2013-06-02 00:38:23 +00:00
documentContent = undefined;
2013-06-03 22:19:52 +00:00
var initDocumentContent = fileDesc.content;
2013-06-05 22:29:32 +00:00
var editorElt = $("#wmd-input");
editorElt.val(initDocumentContent);
2013-06-02 00:38:23 +00:00
if(editor !== undefined) {
2013-06-03 22:19:52 +00:00
// If the editor is already created
undoManager.reinit(initDocumentContent, fileDesc.editorStart, fileDesc.editorEnd, fileDesc.editorScrollTop);
editor.refreshPreview();
2013-06-02 00:38:23 +00:00
return;
}
2013-06-05 22:29:32 +00:00
var previewContainerElt = $(".preview-container");
2013-06-10 21:22:32 +00:00
2013-06-05 22:29:32 +00:00
// Store editor scrollTop on scroll event
editorElt.scroll(function() {
2013-06-03 22:19:52 +00:00
if(documentContent !== undefined) {
fileDesc.editorScrollTop = $(this).scrollTop();
}
});
2013-06-05 22:29:32 +00:00
// Store editor selection on change
editorElt.bind("keyup mouseup", function() {
if(documentContent !== undefined) {
fileDesc.editorStart = this.selectionStart;
fileDesc.editorEnd = this.selectionEnd;
}
});
// Store preview scrollTop on scroll event
previewContainerElt.scroll(function() {
2013-06-03 22:19:52 +00:00
if(documentContent !== undefined) {
fileDesc.previewScrollTop = $(this).scrollTop();
}
});
2013-06-10 21:22:32 +00:00
// Create the converter and the editor
2013-05-29 19:55:23 +00:00
var converter = new Markdown.Converter();
2013-06-02 00:38:23 +00:00
editor = new Markdown.Editor(converter);
2013-05-29 19:55:23 +00:00
// Custom insert link dialog
editor.hooks.set("insertLinkDialog", function(callback) {
2013-06-02 00:38:23 +00:00
core.insertLinkCallback = callback;
2013-05-29 19:55:23 +00:00
utils.resetModalInputs();
$("#modal-insert-link").modal();
return true;
});
// Custom insert image dialog
editor.hooks.set("insertImageDialog", function(callback) {
2013-06-02 00:38:23 +00:00
core.insertLinkCallback = callback;
2013-05-29 19:55:23 +00:00
utils.resetModalInputs();
$("#modal-insert-image").modal();
return true;
});
function checkDocumentChanges() {
2013-06-05 22:29:32 +00:00
var newDocumentContent = editorElt.val();
2013-05-29 19:55:23 +00:00
if(documentContent !== undefined && documentContent != newDocumentContent) {
2013-06-03 22:19:52 +00:00
fileDesc.content = newDocumentContent;
2013-06-16 10:47:35 +00:00
extensionMgr.onContentChanged(fileDesc);
2013-05-29 19:55:23 +00:00
}
documentContent = newDocumentContent;
}
2013-06-02 00:38:23 +00:00
var previewWrapper;
2013-05-29 19:55:23 +00:00
if(settings.lazyRendering === true) {
previewWrapper = function(makePreview) {
var debouncedMakePreview = _.debounce(makePreview, 500);
return function() {
if(documentContent === undefined) {
makePreview();
2013-06-05 22:29:32 +00:00
editorElt.scrollTop(fileDesc.editorScrollTop);
previewContainerElt.scrollTop(fileDesc.previewScrollTop);
2013-05-29 19:55:23 +00:00
}
else {
debouncedMakePreview();
}
checkDocumentChanges();
};
};
}
else {
previewWrapper = function(makePreview) {
return function() {
makePreview();
2013-06-03 22:19:52 +00:00
if(documentContent === undefined) {
2013-06-05 22:29:32 +00:00
previewContainerElt.scrollTop(fileDesc.previewScrollTop);
2013-06-03 22:19:52 +00:00
}
checkDocumentChanges();
2013-05-29 19:55:23 +00:00
};
};
}
extensionMgr.onEditorConfigure(editor);
2013-06-02 00:38:23 +00:00
editor.hooks.chain("onPreviewRefresh", extensionMgr.onAsyncPreview);
2013-06-03 22:19:52 +00:00
undoManager = editor.run(previewWrapper);
undoManager.reinit(initDocumentContent, fileDesc.editorStart, fileDesc.editorEnd, fileDesc.editorScrollTop);
2013-05-29 19:55:23 +00:00
// Hide default buttons
$(".wmd-button-row").addClass("btn-group").find("li:not(.wmd-spacer)").addClass("btn").css("left", 0).find("span").hide();
// Add customized buttons
$("#wmd-bold-button").append($("<i>").addClass("icon-bold"));
$("#wmd-italic-button").append($("<i>").addClass("icon-italic"));
$("#wmd-link-button").append($("<i>").addClass("icon-globe"));
$("#wmd-quote-button").append($("<i>").addClass("icon-indent-left"));
$("#wmd-code-button").append($("<i>").addClass("icon-code"));
$("#wmd-image-button").append($("<i>").addClass("icon-picture"));
$("#wmd-olist-button").append($("<i>").addClass("icon-numbered-list"));
$("#wmd-ulist-button").append($("<i>").addClass("icon-list"));
$("#wmd-heading-button").append($("<i>").addClass("icon-text-height"));
$("#wmd-hr-button").append($("<i>").addClass("icon-hr"));
$("#wmd-undo-button").append($("<i>").addClass("icon-undo"));
$("#wmd-redo-button").append($("<i>").addClass("icon-share-alt"));
};
// onReady event callbacks
var readyCallbacks = [];
core.onReady = function(callback) {
readyCallbacks.push(callback);
runReadyCallbacks();
};
var ready = false;
core.setReady = function() {
ready = true;
runReadyCallbacks();
};
function runReadyCallbacks() {
if(ready === true) {
_.each(readyCallbacks, function(callback) {
callback();
});
readyCallbacks = [];
}
}
core.onReady(extensionMgr.onReady);
core.onReady(function() {
// Load theme list
_.each(THEME_LIST, function(name, value) {
$("#input-settings-theme").append($('<option value="' + value + '">' + name + '</option>'));
});
// listen to online/offline events
$(window).on('offline', core.setOffline);
$(window).on('online', setOnline);
if(navigator.onLine === false) {
core.setOffline();
}
// Detect user activity
$(document).mousemove(setUserActive).keypress(setUserActive);
// Avoid dropdown to close when clicking on submenu
$(".dropdown-submenu > a").click(function(e) {
e.stopPropagation();
});
2013-06-02 19:35:44 +00:00
var shownModalId = undefined;
$(".modal").on('shown', function(e) {
2013-06-02 00:38:23 +00:00
// Focus on the first input when modal opens
2013-06-02 19:35:44 +00:00
var modalId = $(this).attr("id");
if(shownModalId != modalId) {
// Hack to avoid conflict with tabs, collapse, tooltips events
shownModalId = modalId;
_.defer(function(elt) {
elt.find("input:enabled:visible:first").focus();
}, $(this));
}
2013-06-02 00:38:23 +00:00
}).on('hidden', function() {
// Focus on the editor when modal is gone
2013-06-02 19:35:44 +00:00
var modalId = $(this).attr("id");
if(shownModalId == modalId && $(this).is(":hidden")) {
shownModalId = undefined;
2013-06-10 21:22:32 +00:00
$("#wmd-input").focus();
2013-06-02 00:38:23 +00:00
}
}).keyup(function(e) {
// Handle enter key in modals
if(e.which == 13 && !$(e.target).is("textarea")) {
$(this).find(".modal-footer a:last").click();
}
});
2013-06-10 21:22:32 +00:00
// Configure Mousetrap
mousetrap.stopCallback = function(e, element, combo) {
return shownModalId || $(element).is("input, select, textarea:not(#wmd-input)");
};
2013-05-29 19:55:23 +00:00
// Click events on "insert link" and "insert image" dialog buttons
$(".action-insert-link").click(function(e) {
var value = utils.getInputTextValue($("#input-insert-link"), e);
if(value !== undefined) {
2013-06-02 00:38:23 +00:00
core.insertLinkCallback(value);
2013-06-02 19:35:44 +00:00
core.insertLinkCallback = undefined;
2013-05-29 19:55:23 +00:00
}
});
$(".action-insert-image").click(function(e) {
var value = utils.getInputTextValue($("#input-insert-image"), e);
if(value !== undefined) {
2013-06-02 00:38:23 +00:00
core.insertLinkCallback(value);
2013-06-02 19:35:44 +00:00
core.insertLinkCallback = undefined;
2013-05-29 19:55:23 +00:00
}
});
2013-06-10 21:22:32 +00:00
2013-06-02 00:38:23 +00:00
// Hide events on "insert link" and "insert image" dialogs
$("#modal-insert-link, #modal-insert-image").on('hidden', function() {
if(core.insertLinkCallback !== undefined) {
core.insertLinkCallback(null);
2013-06-02 19:35:44 +00:00
core.insertLinkCallback = undefined;
2013-06-02 00:38:23 +00:00
}
2013-05-29 19:55:23 +00:00
});
// Settings loading/saving
$(".action-load-settings").click(function() {
loadSettings();
});
$(".action-apply-settings").click(function(e) {
saveSettings(e);
if(!e.isPropagationStopped()) {
window.location.reload();
}
});
$(".action-default-settings").click(function() {
localStorage.removeItem("settings");
localStorage.removeItem("theme");
window.location.reload();
});
$(".action-app-reset").click(function() {
localStorage.clear();
window.location.reload();
});
// UI layout
$("#menu-bar, .ui-layout-center, .ui-layout-east, .ui-layout-south").removeClass("hide");
core.createLayout();
// Editor's textarea
$("#wmd-input, #md-section-helper").css({
// Apply editor font size
"font-size": settings.editorFontSize + "px",
"line-height": Math.round(settings.editorFontSize * (20 / 14)) + "px"
});
2013-06-02 00:38:23 +00:00
// Handle tab key
2013-05-29 19:55:23 +00:00
$("#wmd-input").keydown(function(e) {
if(e.keyCode === 9) {
var value = $(this).val();
var start = this.selectionStart;
var end = this.selectionEnd;
// IE8 does not support selection attributes
if(start === undefined || end === undefined) {
return;
}
$(this).val(value.substring(0, start) + "\t" + value.substring(end));
this.selectionStart = this.selectionEnd = start + 1;
e.preventDefault();
}
});
// Tooltips
$(".tooltip-lazy-rendering").tooltip({
container: '#modal-settings',
placement: 'right',
2013-06-02 00:38:23 +00:00
trigger: 'hover',
2013-05-29 19:55:23 +00:00
title: 'Disable preview rendering while typing in order to offload CPU. Refresh preview after 500 ms of inactivity.'
});
$(".tooltip-default-content").tooltip({
html: true,
container: '#modal-settings',
placement: 'right',
2013-06-02 00:38:23 +00:00
trigger: 'hover',
2013-05-29 19:55:23 +00:00
title: 'Thanks for supporting StackEdit by adding a backlink in your documents!'
});
$(".tooltip-template").tooltip({
html: true,
container: '#modal-settings',
placement: 'right',
trigger: 'manual',
2013-06-10 21:22:32 +00:00
title: settingsTemplateTooltipHTML
2013-05-29 19:55:23 +00:00
}).click(function(e) {
$(this).tooltip('show');
2013-06-02 00:38:23 +00:00
$(document).on("click.tooltip-template", function(e) {
$(".tooltip-template").tooltip('hide');
$(document).off("click.tooltip-template");
});
2013-05-29 19:55:23 +00:00
e.stopPropagation();
});
// Reset inputs
$(".action-reset-input").click(function() {
utils.resetModalInputs();
});
// Do periodic tasks
intervalId = window.setInterval(function() {
utils.updateCurrentTime();
checkWindowUnique();
if(isUserActive() === true || viewerMode === true) {
_.each(periodicCallbacks, function(callback) {
callback();
});
checkOnline();
}
}, 1000);
});
return core;
});