realms-wiki/realms/static/js/dillinger.js

698 lines
18 KiB
JavaScript
Raw Normal View History

2013-10-01 07:10:10 +03:00
$(function(){
2013-10-10 00:35:06 +03:00
// Cache some shit
var $theme = $('#theme-list')
, $preview = $('#preview')
, $autosave = $('#autosave')
, $wordcount = $('#wordcount')
, $wordcounter = $('#wordcounter')
, $pagename = $("#page-name");
var editor
, autoInterval
, profile =
2013-10-01 07:10:10 +03:00
{
2013-10-10 00:35:06 +03:00
theme: 'ace/theme/idle_fingers'
, currentMd: ''
, autosave:
2013-10-01 07:10:10 +03:00
{
2013-10-10 00:35:06 +03:00
enabled: true
, interval: 3000 // might be too aggressive; don't want to block UI for large saves.
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
, current_filename : $pagename.val()
};
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
// Feature detect ish
var dillinger = 'dillinger'
, dillingerElem = document.createElement(dillinger)
, dillingerStyle = dillingerElem.style
, domPrefixes = 'Webkit Moz O ms Khtml'.split(' ');
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/// UTILS =================
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/**
* Utility method to async load a JavaScript file.
*
* @param {String} The name of the file to load
* @param {Function} Optional callback to be executed after the script loads.
* @return {void}
*/
function asyncLoad(filename,cb){
(function(d,t){
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
var leScript = d.createElement(t)
, scripts = d.getElementsByTagName(t)[0];
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
leScript.async = 1;
leScript.src = filename;
scripts.parentNode.insertBefore(leScript,scripts);
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
leScript.onload = function(){
cb && cb();
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
}(document,'script'));
}
/**
* Utility method to determin if localStorage is supported or not.
*
* @return {Boolean}
*/
function hasLocalStorage(){
// http://mathiasbynens.be/notes/localstorage-pattern
var storage;
try{ if(localStorage.getItem) {storage = localStorage} }catch(e){}
return storage;
}
/**
* Grab the user's profile from localStorage and stash in "profile" variable.
*
* @return {Void}
*/
function getUserProfile(){
var p;
try{
p = JSON.parse( localStorage.profile );
// Need to merge in any undefined/new properties from last release
// Meaning, if we add new features they may not have them in profile
p = $.extend(true, profile, p);
}catch(e){
p = profile
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
if (p.filename != $pagename.val()) {
updateUserProfile({ filename: $pagename.val(), currentMd: "" });
}
profile = p;
}
/**
* Update user's profile in localStorage by merging in current profile with passed in param.
*
* @param {Object} An object containg proper keys and values to be JSON.stringify'd
* @return {Void}
*/
function updateUserProfile(obj){
localStorage.clear();
localStorage.profile = JSON.stringify( $.extend(true, profile, obj) );
}
/**
* Utility method to test if particular property is supported by the browser or not.
* Completely ripped from Modernizr with some mods.
* Thx, Modernizr team!
*
* @param {String} The property to test
* @return {Boolean}
*/
function prefixed(prop){ return testPropsAll(prop, 'pfx') }
/**
* A generic CSS / DOM property test; if a browser supports
* a certain property, it won't return undefined for it.
* A supported CSS property returns empty string when its not yet set.
*
* @param {Object} A hash of properties to test
* @param {String} A prefix
* @return {Boolean}
*/
function testProps( props, prefixed ) {
for ( var i in props ) {
if( dillingerStyle[ props[i] ] !== undefined ) {
return prefixed === 'pfx' ? props[i] : true;
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
}
return false
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Tests a list of DOM properties we want to check against.
* We specify literally ALL possible (known and/or likely) properties on
* the element including the non-vendor prefixed one, for forward-
* compatibility.
*
* @param {String} The name of the property
* @param {String} The prefix string
* @return {Boolean}
*/
function testPropsAll( prop, prefixed ) {
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1)
, props = (prop + ' ' + domPrefixes.join(ucProp + ' ') + ucProp).split(' ');
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
return testProps(props, prefixed);
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/**
* Normalize the transitionEnd event across browsers.
*
* @return {String}
*/
function normalizeTransitionEnd()
{
2013-10-03 21:13:10 +03:00
2013-10-10 00:35:06 +03:00
var transEndEventNames =
{
'WebkitTransition' : 'webkitTransitionEnd'
, 'MozTransition' : 'transitionend'
, 'OTransition' : 'oTransitionEnd'
, 'msTransition' : 'msTransitionEnd' // maybe?
, 'transition' : 'transitionend'
2013-10-01 07:10:10 +03:00
};
2013-10-10 00:35:06 +03:00
return transEndEventNames[ prefixed('transition') ];
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/**
* Get current filename from contenteditable field.
*
* @return {String}
*/
function getCurrentFilenameFromField(){
return $('#filename > span[contenteditable="true"]').text()
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Set current filename from profile.
*
* @param {String} Optional string to force set the value.
* @return {String}
*/
function setCurrentFilenameField(str){
$('#filename > span[contenteditable="true"]').text( str || profile.current_filename || "Untitled Document")
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Returns the full text of an element and all its children.
* The script recursively traverses all text nodes, and returns a
* concatenated string of all texts.
*
* Taken from
* http://stackoverflow.com/questions/2653670/innertext-textcontent-vs-retrieving-each-text-node
*
* @param node
* @return {int}
*/
function getTextInElement(node) {
if (node.nodeType === 3) {
return node.data;
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
var txt = '';
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
if (node = node.firstChild) do {
txt += getTextInElement(node);
} while (node = node.nextSibling);
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
return txt;
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Counts the words in a string
*
* @param string
* @return int
*/
function countWords(string) {
var words = string.replace(/W+/g, ' ').match(/\S+/g);
return words && words.length || 0;
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Initialize application.
*
* @return {Void}
*/
function init(){
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
if( !hasLocalStorage() ) { sadPanda() }
else{
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
// Attach to jQuery support object for later use.
$.support.transitionEnd = normalizeTransitionEnd();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
getUserProfile();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
initAce();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
initUi();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
bindPreview();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
bindNav();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
bindKeyboard();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
autoSave();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
}
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Initialize theme and other options of Ace editor.
*
* @return {Void}
*/
function initAce(){
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
editor = ace.edit("editor");
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/**
* Initialize various UI elements based on userprofile data.
*
* @return {Void}
*/
function initUi(){
// Set proper theme value in theme dropdown
fetchTheme(profile.theme, function(){
$theme.find('li > a[data-value="'+profile.theme+'"]').addClass('selected');
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
editor.getSession().setUseWrapMode(true);
editor.setShowPrintMargin(false);
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
editor.getSession().setMode('ace/mode/markdown');
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
editor.getSession().setValue( profile.currentMd || editor.getSession().getValue());
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
// Immediately populate the preview <div>
previewMd();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
});
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
// Set text for dis/enable autosave / word counter
$autosave.html( profile.autosave.enabled ? '<i class="icon-remove"></i>&nbsp;Disable Autosave' : '<i class="icon-ok"></i>&nbsp;Enable Autosave' );
$wordcount.html( !profile.wordcount ? '<i class="icon-remove"></i>&nbsp;Disabled Word Count' : '<i class="icon-ok"></i>&nbsp;Enabled Word Count' );
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
setCurrentFilenameField();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/* BEGIN RE-ARCH STUFF */
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
$('.dropdown-toggle').dropdown();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/* END RE-ARCH STUFF */
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/// HANDLERS =================
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/**
* Clear the markdown and text and the subsequent HTML preview.
*
* @return {Void}
*/
function clearSelection(){
editor.getSession().setValue("");
previewMd();
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
// TODO: WEBSOCKET MESSAGE?
/**
* Save the markdown via localStorage - isManual is from a click or key event.
*
* @param {Boolean}
* @return {Void}
*/
function saveFile(isManual){
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
updateUserProfile({currentMd: editor.getSession().getValue()})
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
if (isManual) {
updateUserProfile({ currentMd: "" });
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
var data = {
name: $pagename.val(),
message: $("#page-message").val(),
content: editor.getSession().getValue()
};
$.post(window.location, data, function(){
location.href = "/" + data['name'];
});
}
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Enable autosave for a specific interval.
*
* @return {Void}
*/
function autoSave(){
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
if(profile.autosave.enabled){
autoInterval = setInterval( function(){
// firefox barfs if I don't pass in anon func to setTimeout.
saveFile();
}, profile.autosave.interval);
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
}
else{
clearInterval( autoInterval )
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
}
2013-10-01 07:10:10 +03:00
$("#save-native").on('click', function() {
saveFile(true);
});
2013-10-10 00:35:06 +03:00
/**
* Clear out user profile data in localStorage.
*
* @return {Void}
*/
function resetProfile(){
// For some reason, clear() is not working in Chrome.
localStorage.clear();
// Let's turn off autosave
profile.autosave.enabled = false
// Delete the property altogether --> need ; for JSHint bug.
; delete localStorage.profile;
// Now reload the page to start fresh
window.location.reload();
}
/**
* Dropbown nav handler to update the current theme.
*
* @return {Void}
*/
function changeTheme(e){
// check for same theme
var $target = $(e.target);
if( $target.attr('data-value') === profile.theme) { return; }
else{
// add/remove class
$theme.find('li > a.selected').removeClass('selected');
$target.addClass('selected');
// grabnew theme
var newTheme = $target.attr('data-value');
$(e.target).blur();
fetchTheme(newTheme, function(){
});
2013-10-01 07:10:10 +03:00
}
}
2013-10-10 00:35:06 +03:00
// TODO: Maybe we just load them all once and stash in appcache?
/**
* Dynamically appends a script tag with the proper theme and then applies that theme.
*
* @param {String} The theme name
* @param {Function} Optional callback
* @return {Void}
*/
function fetchTheme(th, cb){
var name = th.split('/').pop();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
asyncLoad("/static/js/ace/theme-"+ name +".js", function(){
editor.setTheme(th);
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
cb && cb();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
updateBg(name);
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
updateUserProfile({theme: th});
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
}); // end asyncLoad
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
} // end fetchTheme(t)
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/**
* Change the body background color based on theme.
*
* @param {String} The theme name
* @return {Void}
*/
function updateBg(name){
// document.body.style.backgroundColor = bgColors[name]
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Clientside update showing rendered HTML of Markdown.
*
* @return {Void}
*/
function previewMd(){
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
var unmd = editor.getSession().getValue()
, md = MDR.convert(unmd, true);
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
$preview
.html('') // unnecessary?
.html(md);
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
refreshWordCount();
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
function refreshWordCount(selectionCount){
var msg = "Words: ";
if (selectionCount !== undefined) {
msg += selectionCount + " of ";
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
if(profile.wordcount){
$wordcounter.text(msg + countWords(getTextInElement($preview[0])));
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/**
* Stash current file name in the user's profile.
*
* @param {String} Optional string to force the value
* @return {Void}
*/
function updateFilename(str){
// Check for string because it may be keyup event object
var f
if(typeof str === 'string'){
f = str
}else
{
f = getCurrentFilenameFromField()
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
updateUserProfile( {current_filename: f })
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
function showHtml(){
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
// TODO: UPDATE TO SUPPORT FILENAME NOT JUST A RANDOM FILENAME
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
var unmd = editor.getSession().getValue();
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
function _doneHandler(jqXHR, data, response){
// console.dir(resp)
var resp = JSON.parse(response.responseText);
$('#myModalBody').text(resp.data);
$('#myModal').modal();
2013-10-01 07:10:10 +03:00
}
function _failHandler(){
2013-10-10 00:35:06 +03:00
alert("Roh-roh. Something went wrong. :(");
2013-10-01 07:10:10 +03:00
}
var config = {
2013-10-10 00:35:06 +03:00
type: 'POST',
data: "unmd=" + encodeURIComponent(unmd),
dataType: 'json',
url: '/factory/fetch_html_direct',
error: _failHandler,
success: _doneHandler
};
2013-10-01 07:10:10 +03:00
$.ajax(config)
}
2013-10-10 00:35:06 +03:00
/**
* Show a sad panda because they are using a shitty browser.
*
* @return {Void}
*/
function sadPanda(){
// TODO: ACTUALLY SHOW A SAD PANDA.
alert('Sad Panda - No localStorage for you!')
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Toggles the autosave feature.
*
* @return {Void}
*/
function toggleAutoSave(){
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
$autosave.html( profile.autosave.enabled ? '<i class="icon-remove"></i>&nbsp;Disable Autosave' : '<i class="icon-ok"></i>&nbsp;Enable Autosave' );
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
updateUserProfile({autosave: {enabled: !profile.autosave.enabled }});
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
autoSave();
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Bind keyup handler to the editor.
*
* @return {Void}
*/
function bindPreview(){
$('#editor').bind('keyup', previewMd);
2013-10-01 07:10:10 +03:00
}
2013-10-10 00:35:06 +03:00
/**
* Bind navigation elements.
*
* @return {Void}
*/
function bindNav(){
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
$theme
.find('li > a')
.bind('click', function(e){
changeTheme(e);
return false;
});
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
$('#clear')
.on('click', function(){
clearSelection();
return false;
});
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
$("#autosave")
.on('click', function(){
toggleAutoSave();
return false;
});
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
$('#reset')
.on('click', function(){
resetProfile();
return false;
});
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
$('#cheat').
on('click', function(){
window.open("https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet", "_blank");
return false;
});
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
} // end bindNav()
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
/**
* Bind special keyboard handlers.
*
* @return {Void}
*/
function bindKeyboard(){
// CMD+s TO SAVE DOC
key('command+s, ctrl+s', function(e){
saveFile(true);
e.preventDefault(); // so we don't save the webpage - native browser functionality
});
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
var saveCommand = {
name: "save",
bindKey: {
mac: "Command-S",
win: "Ctrl-S"
},
exec: function(){
saveFile(true);
}
};
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
editor.commands.addCommand(saveCommand);
}
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
init();
});
2013-10-01 07:10:10 +03:00
/**
* Get scrollHeight of preview div
* (code adapted from https://github.com/anru/rsted/blob/master/static/scripts/editor.js)
*
* @param {Object} The jQuery object for the preview div
* @return {Int} The scrollHeight of the preview area (in pixels)
*/
function getScrollHeight($prevFrame) {
// Different browsers attach the scrollHeight of a document to different
// elements, so handle that here.
if ($prevFrame[0].scrollHeight !== undefined) {
return $prevFrame[0].scrollHeight;
} else if ($prevFrame.find('html')[0].scrollHeight !== undefined &&
2013-10-10 00:35:06 +03:00
$prevFrame.find('html')[0].scrollHeight !== 0) {
2013-10-01 07:10:10 +03:00
return $prevFrame.find('html')[0].scrollHeight;
} else {
return $prevFrame.find('body')[0].scrollHeight;
}
}
/**
* Scroll preview to match cursor position in editor session
* (code adapted from https://github.com/anru/rsted/blob/master/static/scripts/editor.js)
*
* @return {Void}
*/
function syncPreview() {
2013-10-10 00:35:06 +03:00
var $ed = window.ace.edit('editor');
var $prev = $('#preview');
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
var editorScrollRange = ($ed.getSession().getLength());
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
var previewScrollRange = (getScrollHeight($prev));
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
// Find how far along the editor is (0 means it is scrolled to the top, 1
// means it is at the bottom).
var scrollFactor = $ed.getFirstVisibleRow() / editorScrollRange;
2013-10-01 07:10:10 +03:00
2013-10-10 00:35:06 +03:00
// Set the scroll position of the preview pane to match. jQuery will
// gracefully handle out-of-bounds values.
$prev.scrollTop(scrollFactor * previewScrollRange);
2013-10-01 07:10:10 +03:00
}
window.onload = function(){
2013-10-10 00:35:06 +03:00
var $loading = $('#loading');
if ($.support.transition){
$loading
.bind( $.support.transitionEnd, function(){
$('#main').removeClass('bye');
$loading.remove();
})
.addClass('fade_slow');
} else {
$('#main').removeClass('bye');
$loading.remove();
}
/**
* Bind synchronization of preview div to editor scroll and change
* of editor cursor position.
*/
window.ace.edit('editor').session.on('changeScrollTop', syncPreview);
window.ace.edit('editor').session.selection.on('changeCursor', syncPreview);
};