Use JavaScript Standard Style (part 2)

Fixed all fail on frontend code.
This commit is contained in:
BoHong Li 2017-03-09 02:41:05 +08:00
parent 4889e9732d
commit 5bc642d02e
19 changed files with 6790 additions and 7032 deletions

View File

@ -1,7 +1,10 @@
require('./locale');
/* eslint-env browser, jquery */
/* global moment, serverurl */
require('../css/cover.css');
require('../css/site.css');
require('./locale')
require('../css/cover.css')
require('../css/site.css')
import {
checkIfAuth,
@ -9,7 +12,7 @@ import {
getLoginState,
resetCheckAuth,
setloginStateChangeEvent
} from './lib/common/login';
} from './lib/common/login'
import {
clearDuplicatedHistory,
@ -23,411 +26,403 @@ import {
removeHistory,
saveHistory,
saveStorageHistoryToServer
} from './history';
} from './history'
import { saveAs } from 'file-saver';
import List from 'list.js';
import S from 'string';
import { saveAs } from 'file-saver'
import List from 'list.js'
import S from 'string'
const options = {
valueNames: ['id', 'text', 'timestamp', 'fromNow', 'time', 'tags', 'pinned'],
item: '<li class="col-xs-12 col-sm-6 col-md-6 col-lg-4">\
<span class="id" style="display:none;"></span>\
<a href="#">\
<div class="item">\
<div class="ui-history-pin fa fa-thumb-tack fa-fw"></div>\
<div class="ui-history-close fa fa-close fa-fw" data-toggle="modal" data-target=".delete-modal"></div>\
<div class="content">\
<h4 class="text"></h4>\
<p>\
<i><i class="fa fa-clock-o"></i> visited </i><i class="fromNow"></i>\
<br>\
<i class="timestamp" style="display:none;"></i>\
<i class="time"></i>\
</p>\
<p class="tags"></p>\
</div>\
</div>\
</a>\
</li>',
page: 18,
plugins: [
ListPagination({
outerWindow: 1
})
]
};
const historyList = new List('history', options);
valueNames: ['id', 'text', 'timestamp', 'fromNow', 'time', 'tags', 'pinned'],
item: '<li class="col-xs-12 col-sm-6 col-md-6 col-lg-4">' +
'<span class="id" style="display:none;"></span>' +
'<a href="#">' +
'<div class="item">' +
'<div class="ui-history-pin fa fa-thumb-tack fa-fw"></div>' +
'<div class="ui-history-close fa fa-close fa-fw" data-toggle="modal" data-target=".delete-modal"></div>' +
'<div class="content">' +
'<h4 class="text"></h4>' +
'<p>' +
'<i><i class="fa fa-clock-o"></i> visited </i><i class="fromNow"></i>' +
'<br>' +
'<i class="timestamp" style="display:none;"></i>' +
'<i class="time"></i>' +
'</p>' +
'<p class="tags"></p>' +
'</div>' +
'</div>' +
'</a>' +
'</li>',
page: 18,
plugins: [
window.ListPagination({
outerWindow: 1
})
]
}
const historyList = new List('history', options)
migrateHistoryFromTempCallback = pageInit;
setloginStateChangeEvent(pageInit);
window.migrateHistoryFromTempCallback = pageInit
setloginStateChangeEvent(pageInit)
pageInit();
pageInit()
function pageInit() {
checkIfAuth(
function pageInit () {
checkIfAuth(
data => {
$('.ui-signin').hide();
$('.ui-or').hide();
$('.ui-welcome').show();
if (data.photo) $('.ui-avatar').prop('src', data.photo).show();
else $('.ui-avatar').prop('src', '').hide();
$('.ui-name').html(data.name);
$('.ui-signout').show();
$(".ui-history").click();
parseServerToHistory(historyList, parseHistoryCallback);
$('.ui-signin').hide()
$('.ui-or').hide()
$('.ui-welcome').show()
if (data.photo) $('.ui-avatar').prop('src', data.photo).show()
else $('.ui-avatar').prop('src', '').hide()
$('.ui-name').html(data.name)
$('.ui-signout').show()
$('.ui-history').click()
parseServerToHistory(historyList, parseHistoryCallback)
},
() => {
$('.ui-signin').show();
$('.ui-or').show();
$('.ui-welcome').hide();
$('.ui-avatar').prop('src', '').hide();
$('.ui-name').html('');
$('.ui-signout').hide();
parseStorageToHistory(historyList, parseHistoryCallback);
$('.ui-signin').show()
$('.ui-or').show()
$('.ui-welcome').hide()
$('.ui-avatar').prop('src', '').hide()
$('.ui-name').html('')
$('.ui-signout').hide()
parseStorageToHistory(historyList, parseHistoryCallback)
}
);
)
}
$(".masthead-nav li").click(function () {
$(this).siblings().removeClass("active");
$(this).addClass("active");
});
$('.masthead-nav li').click(function () {
$(this).siblings().removeClass('active')
$(this).addClass('active')
})
// prevent empty link change hash
$('a[href="#"]').click(function (e) {
e.preventDefault();
});
e.preventDefault()
})
$(".ui-home").click(function (e) {
if (!$("#home").is(':visible')) {
$(".section:visible").hide();
$("#home").fadeIn();
}
});
$('.ui-home').click(function (e) {
if (!$('#home').is(':visible')) {
$('.section:visible').hide()
$('#home').fadeIn()
}
})
$(".ui-history").click(() => {
if (!$("#history").is(':visible')) {
$(".section:visible").hide();
$("#history").fadeIn();
}
});
$('.ui-history').click(() => {
if (!$('#history').is(':visible')) {
$('.section:visible').hide()
$('#history').fadeIn()
}
})
function checkHistoryList() {
if ($("#history-list").children().length > 0) {
$('.pagination').show();
$(".ui-nohistory").hide();
$(".ui-import-from-browser").hide();
} else if ($("#history-list").children().length == 0) {
$('.pagination').hide();
$(".ui-nohistory").slideDown();
getStorageHistory(data => {
if (data && data.length > 0 && getLoginState() && historyList.items.length == 0) {
$(".ui-import-from-browser").slideDown();
}
});
}
function checkHistoryList () {
if ($('#history-list').children().length > 0) {
$('.pagination').show()
$('.ui-nohistory').hide()
$('.ui-import-from-browser').hide()
} else if ($('#history-list').children().length === 0) {
$('.pagination').hide()
$('.ui-nohistory').slideDown()
getStorageHistory(data => {
if (data && data.length > 0 && getLoginState() && historyList.items.length === 0) {
$('.ui-import-from-browser').slideDown()
}
})
}
}
function parseHistoryCallback(list, notehistory) {
checkHistoryList();
//sort by pinned then timestamp
list.sort('', {
sortFunction(a, b) {
const notea = a.values();
const noteb = b.values();
if (notea.pinned && !noteb.pinned) {
return -1;
} else if (!notea.pinned && noteb.pinned) {
return 1;
} else {
if (notea.timestamp > noteb.timestamp) {
return -1;
} else if (notea.timestamp < noteb.timestamp) {
return 1;
} else {
return 0;
}
}
}
});
// parse filter tags
const filtertags = [];
for (let i = 0, l = list.items.length; i < l; i++) {
const tags = list.items[i]._values.tags;
if (tags && tags.length > 0) {
for (let j = 0; j < tags.length; j++) {
//push info filtertags if not found
let found = false;
if (filtertags.includes(tags[j]))
found = true;
if (!found)
filtertags.push(tags[j]);
}
function parseHistoryCallback (list, notehistory) {
checkHistoryList()
// sort by pinned then timestamp
list.sort('', {
sortFunction (a, b) {
const notea = a.values()
const noteb = b.values()
if (notea.pinned && !noteb.pinned) {
return -1
} else if (!notea.pinned && noteb.pinned) {
return 1
} else {
if (notea.timestamp > noteb.timestamp) {
return -1
} else if (notea.timestamp < noteb.timestamp) {
return 1
} else {
return 0
}
}
}
buildTagsFilter(filtertags);
})
// parse filter tags
const filtertags = []
for (let i = 0, l = list.items.length; i < l; i++) {
const tags = list.items[i]._values.tags
if (tags && tags.length > 0) {
for (let j = 0; j < tags.length; j++) {
// push info filtertags if not found
let found = false
if (filtertags.includes(tags[j])) { found = true }
if (!found) { filtertags.push(tags[j]) }
}
}
}
buildTagsFilter(filtertags)
}
// update items whenever list updated
historyList.on('updated', e => {
for (let i = 0, l = e.items.length; i < l; i++) {
const item = e.items[i];
if (item.visible()) {
const itemEl = $(item.elm);
const values = item._values;
const a = itemEl.find("a");
const pin = itemEl.find(".ui-history-pin");
const tagsEl = itemEl.find(".tags");
//parse link to element a
a.attr('href', `${serverurl}/${values.id}`);
//parse pinned
if (values.pinned) {
pin.addClass('active');
} else {
pin.removeClass('active');
}
//parse tags
const tags = values.tags;
if (tags && tags.length > 0 && tagsEl.children().length <= 0) {
const labels = [];
for (let j = 0; j < tags.length; j++) {
//push into the item label
labels.push(`<span class='label label-default'>${tags[j]}</span>`);
}
tagsEl.html(labels.join(' '));
}
for (let i = 0, l = e.items.length; i < l; i++) {
const item = e.items[i]
if (item.visible()) {
const itemEl = $(item.elm)
const values = item._values
const a = itemEl.find('a')
const pin = itemEl.find('.ui-history-pin')
const tagsEl = itemEl.find('.tags')
// parse link to element a
a.attr('href', `${serverurl}/${values.id}`)
// parse pinned
if (values.pinned) {
pin.addClass('active')
} else {
pin.removeClass('active')
}
// parse tags
const tags = values.tags
if (tags && tags.length > 0 && tagsEl.children().length <= 0) {
const labels = []
for (let j = 0; j < tags.length; j++) {
// push into the item label
labels.push(`<span class='label label-default'>${tags[j]}</span>`)
}
tagsEl.html(labels.join(' '))
}
}
$(".ui-history-close").off('click');
$(".ui-history-close").on('click', historyCloseClick);
$(".ui-history-pin").off('click');
$(".ui-history-pin").on('click', historyPinClick);
});
}
$('.ui-history-close').off('click')
$('.ui-history-close').on('click', historyCloseClick)
$('.ui-history-pin').off('click')
$('.ui-history-pin').on('click', historyPinClick)
})
function historyCloseClick(e) {
e.preventDefault();
const id = $(this).closest("a").siblings("span").html();
const value = historyList.get('id', id)[0]._values;
$('.ui-delete-modal-msg').text('Do you really want to delete below history?');
$('.ui-delete-modal-item').html(`<i class="fa fa-file-text"></i> ${value.text}<br><i class="fa fa-clock-o"></i> ${value.time}`);
clearHistory = false;
deleteId = id;
function historyCloseClick (e) {
e.preventDefault()
const id = $(this).closest('a').siblings('span').html()
const value = historyList.get('id', id)[0]._values
$('.ui-delete-modal-msg').text('Do you really want to delete below history?')
$('.ui-delete-modal-item').html(`<i class="fa fa-file-text"></i> ${value.text}<br><i class="fa fa-clock-o"></i> ${value.time}`)
clearHistory = false
deleteId = id
}
function historyPinClick(e) {
e.preventDefault();
const $this = $(this);
const id = $this.closest("a").siblings("span").html();
const item = historyList.get('id', id)[0];
const values = item._values;
let pinned = values.pinned;
if (!values.pinned) {
pinned = true;
item._values.pinned = true;
} else {
pinned = false;
item._values.pinned = false;
}
checkIfAuth(() => {
postHistoryToServer(id, {
pinned
}, (err, result) => {
if (!err) {
if (pinned)
$this.addClass('active');
else
$this.removeClass('active');
}
});
}, () => {
getHistory(notehistory => {
for(let i = 0; i < notehistory.length; i++) {
if (notehistory[i].id == id) {
notehistory[i].pinned = pinned;
break;
}
}
saveHistory(notehistory);
if (pinned)
$this.addClass('active');
else
$this.removeClass('active');
});
});
function historyPinClick (e) {
e.preventDefault()
const $this = $(this)
const id = $this.closest('a').siblings('span').html()
const item = historyList.get('id', id)[0]
const values = item._values
let pinned = values.pinned
if (!values.pinned) {
pinned = true
item._values.pinned = true
} else {
pinned = false
item._values.pinned = false
}
checkIfAuth(() => {
postHistoryToServer(id, {
pinned
}, (err, result) => {
if (!err) {
if (pinned) { $this.addClass('active') } else { $this.removeClass('active') }
}
})
}, () => {
getHistory(notehistory => {
for (let i = 0; i < notehistory.length; i++) {
if (notehistory[i].id === id) {
notehistory[i].pinned = pinned
break
}
}
saveHistory(notehistory)
if (pinned) { $this.addClass('active') } else { $this.removeClass('active') }
})
})
}
//auto update item fromNow every minutes
setInterval(updateItemFromNow, 60000);
// auto update item fromNow every minutes
setInterval(updateItemFromNow, 60000)
function updateItemFromNow() {
const items = $('.item').toArray();
for (let i = 0; i < items.length; i++) {
const item = $(items[i]);
const timestamp = parseInt(item.find('.timestamp').text());
item.find('.fromNow').text(moment(timestamp).fromNow());
}
function updateItemFromNow () {
const items = $('.item').toArray()
for (let i = 0; i < items.length; i++) {
const item = $(items[i])
const timestamp = parseInt(item.find('.timestamp').text())
item.find('.fromNow').text(moment(timestamp).fromNow())
}
}
var clearHistory = false;
var deleteId = null;
var clearHistory = false
var deleteId = null
function deleteHistory() {
checkIfAuth(() => {
deleteServerHistory(deleteId, (err, result) => {
if (!err) {
if (clearHistory) {
historyList.clear();
checkHistoryList();
} else {
historyList.remove('id', deleteId);
checkHistoryList();
}
}
$('.delete-modal').modal('hide');
deleteId = null;
clearHistory = false;
});
}, () => {
function deleteHistory () {
checkIfAuth(() => {
deleteServerHistory(deleteId, (err, result) => {
if (!err) {
if (clearHistory) {
saveHistory([]);
historyList.clear();
checkHistoryList();
deleteId = null;
historyList.clear()
checkHistoryList()
} else {
if (!deleteId) return;
getHistory(notehistory => {
const newnotehistory = removeHistory(deleteId, notehistory);
saveHistory(newnotehistory);
historyList.remove('id', deleteId);
checkHistoryList();
deleteId = null;
});
historyList.remove('id', deleteId)
checkHistoryList()
}
$('.delete-modal').modal('hide');
clearHistory = false;
});
}
$(".ui-delete-modal-confirm").click(() => {
deleteHistory();
});
$(".ui-import-from-browser").click(() => {
saveStorageHistoryToServer(() => {
parseStorageToHistory(historyList, parseHistoryCallback);
});
});
$(".ui-save-history").click(() => {
getHistory(data => {
const history = JSON.stringify(data);
const blob = new Blob([history], {
type: "application/json;charset=utf-8"
});
saveAs(blob, `hackmd_history_${moment().format('YYYYMMDDHHmmss')}`, true);
});
});
$(".ui-open-history").bind("change", e => {
const files = e.target.files || e.dataTransfer.files;
const file = files[0];
const reader = new FileReader();
reader.onload = () => {
const notehistory = JSON.parse(reader.result);
//console.log(notehistory);
if (!reader.result) return;
getHistory(data => {
let mergedata = data.concat(notehistory);
mergedata = clearDuplicatedHistory(mergedata);
saveHistory(mergedata);
parseHistory(historyList, parseHistoryCallback);
});
$(".ui-open-history").replaceWith($(".ui-open-history").val('').clone(true));
};
reader.readAsText(file);
});
$(".ui-clear-history").click(() => {
$('.ui-delete-modal-msg').text('Do you really want to clear all history?');
$('.ui-delete-modal-item').html('There is no turning back.');
clearHistory = true;
deleteId = null;
});
$(".ui-refresh-history").click(() => {
const lastTags = $(".ui-use-tags").select2('val');
$(".ui-use-tags").select2('val', '');
historyList.filter();
const lastKeyword = $('.search').val();
$('.search').val('');
historyList.search();
$('#history-list').slideUp('fast');
$('.pagination').hide();
resetCheckAuth();
historyList.clear();
parseHistory(historyList, (list, notehistory) => {
parseHistoryCallback(list, notehistory);
$(".ui-use-tags").select2('val', lastTags);
$(".ui-use-tags").trigger('change');
historyList.search(lastKeyword);
$('.search').val(lastKeyword);
checkHistoryList();
$('#history-list').slideDown('fast');
});
});
$(".ui-logout").click(() => {
clearLoginState();
location.href = `${serverurl}/logout`;
});
let filtertags = [];
$(".ui-use-tags").select2({
placeholder: $(".ui-use-tags").attr('placeholder'),
multiple: true,
data() {
return {
results: filtertags
};
}
});
$('.select2-input').css('width', 'inherit');
buildTagsFilter([]);
function buildTagsFilter(tags) {
for (let i = 0; i < tags.length; i++)
tags[i] = {
id: i,
text: S(tags[i]).unescapeHTML().s
};
filtertags = tags;
}
$(".ui-use-tags").on('change', function () {
const tags = [];
const data = $(this).select2('data');
for (let i = 0; i < data.length; i++)
tags.push(data[i].text);
if (tags.length > 0) {
historyList.filter(item => {
const values = item.values();
if (!values.tags) return false;
let found = false;
for (let i = 0; i < tags.length; i++) {
if (values.tags.includes(tags[i])) {
found = true;
break;
}
}
return found;
});
}
$('.delete-modal').modal('hide')
deleteId = null
clearHistory = false
})
}, () => {
if (clearHistory) {
saveHistory([])
historyList.clear()
checkHistoryList()
deleteId = null
} else {
historyList.filter();
if (!deleteId) return
getHistory(notehistory => {
const newnotehistory = removeHistory(deleteId, notehistory)
saveHistory(newnotehistory)
historyList.remove('id', deleteId)
checkHistoryList()
deleteId = null
})
}
checkHistoryList();
});
$('.delete-modal').modal('hide')
clearHistory = false
})
}
$('.ui-delete-modal-confirm').click(() => {
deleteHistory()
})
$('.ui-import-from-browser').click(() => {
saveStorageHistoryToServer(() => {
parseStorageToHistory(historyList, parseHistoryCallback)
})
})
$('.ui-save-history').click(() => {
getHistory(data => {
const history = JSON.stringify(data)
const blob = new Blob([history], {
type: 'application/json;charset=utf-8'
})
saveAs(blob, `hackmd_history_${moment().format('YYYYMMDDHHmmss')}`, true)
})
})
$('.ui-open-history').bind('change', e => {
const files = e.target.files || e.dataTransfer.files
const file = files[0]
const reader = new FileReader()
reader.onload = () => {
const notehistory = JSON.parse(reader.result)
// console.log(notehistory);
if (!reader.result) return
getHistory(data => {
let mergedata = data.concat(notehistory)
mergedata = clearDuplicatedHistory(mergedata)
saveHistory(mergedata)
parseHistory(historyList, parseHistoryCallback)
})
$('.ui-open-history').replaceWith($('.ui-open-history').val('').clone(true))
}
reader.readAsText(file)
})
$('.ui-clear-history').click(() => {
$('.ui-delete-modal-msg').text('Do you really want to clear all history?')
$('.ui-delete-modal-item').html('There is no turning back.')
clearHistory = true
deleteId = null
})
$('.ui-refresh-history').click(() => {
const lastTags = $('.ui-use-tags').select2('val')
$('.ui-use-tags').select2('val', '')
historyList.filter()
const lastKeyword = $('.search').val()
$('.search').val('')
historyList.search()
$('#history-list').slideUp('fast')
$('.pagination').hide()
resetCheckAuth()
historyList.clear()
parseHistory(historyList, (list, notehistory) => {
parseHistoryCallback(list, notehistory)
$('.ui-use-tags').select2('val', lastTags)
$('.ui-use-tags').trigger('change')
historyList.search(lastKeyword)
$('.search').val(lastKeyword)
checkHistoryList()
$('#history-list').slideDown('fast')
})
})
$('.ui-logout').click(() => {
clearLoginState()
location.href = `${serverurl}/logout`
})
let filtertags = []
$('.ui-use-tags').select2({
placeholder: $('.ui-use-tags').attr('placeholder'),
multiple: true,
data () {
return {
results: filtertags
}
}
})
$('.select2-input').css('width', 'inherit')
buildTagsFilter([])
function buildTagsFilter (tags) {
for (let i = 0; i < tags.length; i++) {
tags[i] = {
id: i,
text: S(tags[i]).unescapeHTML().s
}
}
filtertags = tags
}
$('.ui-use-tags').on('change', function () {
const tags = []
const data = $(this).select2('data')
for (let i = 0; i < data.length; i++) { tags.push(data[i].text) }
if (tags.length > 0) {
historyList.filter(item => {
const values = item.values()
if (!values.tags) return false
let found = false
for (let i = 0; i < tags.length; i++) {
if (values.tags.includes(tags[i])) {
found = true
break
}
}
return found
})
} else {
historyList.filter()
}
checkHistoryList()
})
$('.search').keyup(() => {
checkHistoryList();
});
checkHistoryList()
})

File diff suppressed because it is too large Load Diff

View File

@ -1,119 +1,118 @@
/**!
/** !
* Google Drive File Picker Example
* By Daniel Lo Nigro (http://dan.cx/)
*/
(function() {
/**
* Initialise a Google Driver file picker
*/
var FilePicker = window.FilePicker = function(options) {
// Config
this.apiKey = options.apiKey;
this.clientId = options.clientId;
// Elements
this.buttonEl = options.buttonEl;
// Events
this.onSelect = options.onSelect;
this.buttonEl.on('click', this.open.bind(this));
// Disable the button until the API loads, as it won't work properly until then.
this.buttonEl.prop('disabled', true);
(function () {
/**
* Initialise a Google Driver file picker
*/
var FilePicker = window.FilePicker = function (options) {
// Config
this.apiKey = options.apiKey
this.clientId = options.clientId
// Load the drive API
gapi.client.setApiKey(this.apiKey);
gapi.client.load('drive', 'v2', this._driveApiLoaded.bind(this));
google.load('picker', '1', { callback: this._pickerApiLoaded.bind(this) });
}
// Elements
this.buttonEl = options.buttonEl
FilePicker.prototype = {
/**
* Open the file picker.
*/
open: function() {
// Check if the user has already authenticated
var token = gapi.auth.getToken();
if (token) {
this._showPicker();
} else {
// The user has not yet authenticated with Google
// We need to do the authentication before displaying the Drive picker.
this._doAuth(false, function() { this._showPicker(); }.bind(this));
}
},
/**
* Show the file picker once authentication has been done.
* @private
*/
_showPicker: function() {
var accessToken = gapi.auth.getToken().access_token;
var view = new google.picker.DocsView();
view.setMimeTypes("text/markdown,text/html");
view.setIncludeFolders(true);
view.setOwnedByMe(true);
this.picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.NAV_HIDDEN).
addView(view).
setAppId(this.clientId).
setOAuthToken(accessToken).
setCallback(this._pickerCallback.bind(this)).
build().
setVisible(true);
},
/**
* Called when a file has been selected in the Google Drive file picker.
* @private
*/
_pickerCallback: function(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var file = data[google.picker.Response.DOCUMENTS][0],
id = file[google.picker.Document.ID],
request = gapi.client.drive.files.get({
fileId: id
});
request.execute(this._fileGetCallback.bind(this));
}
},
/**
* Called when file details have been retrieved from Google Drive.
* @private
*/
_fileGetCallback: function(file) {
if (this.onSelect) {
this.onSelect(file);
}
},
/**
* Called when the Google Drive file picker API has finished loading.
* @private
*/
_pickerApiLoaded: function() {
this.buttonEl.prop('disabled', false);
},
/**
* Called when the Google Drive API has finished loading.
* @private
*/
_driveApiLoaded: function() {
this._doAuth(true);
},
/**
* Authenticate with Google Drive via the Google JavaScript API.
* @private
*/
_doAuth: function(immediate, callback) {
gapi.auth.authorize({
client_id: this.clientId,
scope: 'https://www.googleapis.com/auth/drive.readonly',
immediate: immediate
}, callback ? callback : function() {});
}
};
}());
// Events
this.onSelect = options.onSelect
this.buttonEl.on('click', this.open.bind(this))
// Disable the button until the API loads, as it won't work properly until then.
this.buttonEl.prop('disabled', true)
// Load the drive API
window.gapi.client.setApiKey(this.apiKey)
window.gapi.client.load('drive', 'v2', this._driveApiLoaded.bind(this))
window.google.load('picker', '1', { callback: this._pickerApiLoaded.bind(this) })
}
FilePicker.prototype = {
/**
* Open the file picker.
*/
open: function () {
// Check if the user has already authenticated
var token = window.gapi.auth.getToken()
if (token) {
this._showPicker()
} else {
// The user has not yet authenticated with Google
// We need to do the authentication before displaying the Drive picker.
this._doAuth(false, function () { this._showPicker() }.bind(this))
}
},
/**
* Show the file picker once authentication has been done.
* @private
*/
_showPicker: function () {
var accessToken = window.gapi.auth.getToken().access_token
var view = new window.google.picker.DocsView()
view.setMimeTypes('text/markdown,text/html')
view.setIncludeFolders(true)
view.setOwnedByMe(true)
this.picker = new window.google.picker.PickerBuilder()
.enableFeature(window.google.picker.Feature.NAV_HIDDEN)
.addView(view)
.setAppId(this.clientId)
.setOAuthToken(accessToken)
.setCallback(this._pickerCallback.bind(this))
.build()
.setVisible(true)
},
/**
* Called when a file has been selected in the Google Drive file picker.
* @private
*/
_pickerCallback: function (data) {
if (data[window.google.picker.Response.ACTION] === window.google.picker.Action.PICKED) {
var file = data[window.google.picker.Response.DOCUMENTS][0]
var id = file[window.google.picker.Document.ID]
var request = window.gapi.client.drive.files.get({
fileId: id
})
request.execute(this._fileGetCallback.bind(this))
}
},
/**
* Called when file details have been retrieved from Google Drive.
* @private
*/
_fileGetCallback: function (file) {
if (this.onSelect) {
this.onSelect(file)
}
},
/**
* Called when the Google Drive file picker API has finished loading.
* @private
*/
_pickerApiLoaded: function () {
this.buttonEl.prop('disabled', false)
},
/**
* Called when the Google Drive API has finished loading.
* @private
*/
_driveApiLoaded: function () {
this._doAuth(true)
},
/**
* Authenticate with Google Drive via the Google JavaScript API.
* @private
*/
_doAuth: function (immediate, callback) {
window.gapi.auth.authorize({
client_id: this.clientId,
scope: 'https://www.googleapis.com/auth/drive.readonly',
immediate: immediate
}, callback || function () {})
}
}
}())

View File

@ -1,30 +1,31 @@
/* eslint-env browser, jquery */
/**
* Helper for implementing retries with backoff. Initial retry
* delay is 1 second, increasing by 2x (+jitter) for subsequent retries
*
* @constructor
*/
var RetryHandler = function() {
this.interval = 1000; // Start at one second
this.maxInterval = 60 * 1000; // Don't wait longer than a minute
};
var RetryHandler = function () {
this.interval = 1000 // Start at one second
this.maxInterval = 60 * 1000 // Don't wait longer than a minute
}
/**
* Invoke the function after waiting
*
* @param {function} fn Function to invoke
*/
RetryHandler.prototype.retry = function(fn) {
setTimeout(fn, this.interval);
this.interval = this.nextInterval_();
};
RetryHandler.prototype.retry = function (fn) {
setTimeout(fn, this.interval)
this.interval = this.nextInterval_()
}
/**
* Reset the counter (e.g. after successful request.)
*/
RetryHandler.prototype.reset = function() {
this.interval = 1000;
};
RetryHandler.prototype.reset = function () {
this.interval = 1000
}
/**
* Calculate the next wait time.
@ -32,10 +33,10 @@ RetryHandler.prototype.reset = function() {
*
* @private
*/
RetryHandler.prototype.nextInterval_ = function() {
var interval = this.interval * 2 + this.getRandomInt_(0, 1000);
return Math.min(interval, this.maxInterval);
};
RetryHandler.prototype.nextInterval_ = function () {
var interval = this.interval * 2 + this.getRandomInt_(0, 1000)
return Math.min(interval, this.maxInterval)
}
/**
* Get a random int in the range of min to max. Used to add jitter to wait times.
@ -44,10 +45,9 @@ RetryHandler.prototype.nextInterval_ = function() {
* @param {number} max Upper bounds
* @private
*/
RetryHandler.prototype.getRandomInt_ = function(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
};
RetryHandler.prototype.getRandomInt_ = function (min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
/**
* Helper class for resumable uploads using XHR/CORS. Can upload any Blob-like item, whether
@ -75,116 +75,115 @@ RetryHandler.prototype.getRandomInt_ = function(min, max) {
* @param {function} [options.onProgress] Callback for status for the in-progress upload
* @param {function} [options.onError] Callback if upload fails
*/
var MediaUploader = function(options) {
var noop = function() {};
this.file = options.file;
this.contentType = options.contentType || this.file.type || 'application/octet-stream';
var MediaUploader = function (options) {
var noop = function () {}
this.file = options.file
this.contentType = options.contentType || this.file.type || 'application/octet-stream'
this.metadata = options.metadata || {
'title': this.file.name,
'mimeType': this.contentType
};
this.token = options.token;
this.onComplete = options.onComplete || noop;
this.onProgress = options.onProgress || noop;
this.onError = options.onError || noop;
this.offset = options.offset || 0;
this.chunkSize = options.chunkSize || 0;
this.retryHandler = new RetryHandler();
this.url = options.url;
if (!this.url) {
var params = options.params || {};
params.uploadType = 'resumable';
this.url = this.buildUrl_(options.fileId, params, options.baseUrl);
}
this.httpMethod = options.fileId ? 'PUT' : 'POST';
};
this.token = options.token
this.onComplete = options.onComplete || noop
this.onProgress = options.onProgress || noop
this.onError = options.onError || noop
this.offset = options.offset || 0
this.chunkSize = options.chunkSize || 0
this.retryHandler = new RetryHandler()
this.url = options.url
if (!this.url) {
var params = options.params || {}
params.uploadType = 'resumable'
this.url = this.buildUrl_(options.fileId, params, options.baseUrl)
}
this.httpMethod = options.fileId ? 'PUT' : 'POST'
}
/**
* Initiate the upload.
*/
MediaUploader.prototype.upload = function() {
var self = this;
var xhr = new XMLHttpRequest();
MediaUploader.prototype.upload = function () {
var xhr = new XMLHttpRequest()
xhr.open(this.httpMethod, this.url, true);
xhr.setRequestHeader('Authorization', 'Bearer ' + this.token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('X-Upload-Content-Length', this.file.size);
xhr.setRequestHeader('X-Upload-Content-Type', this.contentType);
xhr.open(this.httpMethod, this.url, true)
xhr.setRequestHeader('Authorization', 'Bearer ' + this.token)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.setRequestHeader('X-Upload-Content-Length', this.file.size)
xhr.setRequestHeader('X-Upload-Content-Type', this.contentType)
xhr.onload = function(e) {
xhr.onload = function (e) {
if (e.target.status < 400) {
var location = e.target.getResponseHeader('Location');
this.url = location;
this.sendFile_();
var location = e.target.getResponseHeader('Location')
this.url = location
this.sendFile_()
} else {
this.onUploadError_(e);
this.onUploadError_(e)
}
}.bind(this);
xhr.onerror = this.onUploadError_.bind(this);
xhr.send(JSON.stringify(this.metadata));
};
}.bind(this)
xhr.onerror = this.onUploadError_.bind(this)
xhr.send(JSON.stringify(this.metadata))
}
/**
* Send the actual file content.
*
* @private
*/
MediaUploader.prototype.sendFile_ = function() {
var content = this.file;
var end = this.file.size;
MediaUploader.prototype.sendFile_ = function () {
var content = this.file
var end = this.file.size
if (this.offset || this.chunkSize) {
// Only bother to slice the file if we're either resuming or uploading in chunks
if (this.chunkSize) {
end = Math.min(this.offset + this.chunkSize, this.file.size);
end = Math.min(this.offset + this.chunkSize, this.file.size)
}
content = content.slice(this.offset, end);
content = content.slice(this.offset, end)
}
var xhr = new XMLHttpRequest();
xhr.open('PUT', this.url, true);
xhr.setRequestHeader('Content-Type', this.contentType);
xhr.setRequestHeader('Content-Range', "bytes " + this.offset + "-" + (end - 1) + "/" + this.file.size);
xhr.setRequestHeader('X-Upload-Content-Type', this.file.type);
var xhr = new XMLHttpRequest()
xhr.open('PUT', this.url, true)
xhr.setRequestHeader('Content-Type', this.contentType)
xhr.setRequestHeader('Content-Range', 'bytes ' + this.offset + '-' + (end - 1) + '/' + this.file.size)
xhr.setRequestHeader('X-Upload-Content-Type', this.file.type)
if (xhr.upload) {
xhr.upload.addEventListener('progress', this.onProgress);
xhr.upload.addEventListener('progress', this.onProgress)
}
xhr.onload = this.onContentUploadSuccess_.bind(this);
xhr.onerror = this.onContentUploadError_.bind(this);
xhr.send(content);
};
xhr.onload = this.onContentUploadSuccess_.bind(this)
xhr.onerror = this.onContentUploadError_.bind(this)
xhr.send(content)
}
/**
* Query for the state of the file for resumption.
*
* @private
*/
MediaUploader.prototype.resume_ = function() {
var xhr = new XMLHttpRequest();
xhr.open('PUT', this.url, true);
xhr.setRequestHeader('Content-Range', "bytes */" + this.file.size);
xhr.setRequestHeader('X-Upload-Content-Type', this.file.type);
MediaUploader.prototype.resume_ = function () {
var xhr = new XMLHttpRequest()
xhr.open('PUT', this.url, true)
xhr.setRequestHeader('Content-Range', 'bytes */' + this.file.size)
xhr.setRequestHeader('X-Upload-Content-Type', this.file.type)
if (xhr.upload) {
xhr.upload.addEventListener('progress', this.onProgress);
xhr.upload.addEventListener('progress', this.onProgress)
}
xhr.onload = this.onContentUploadSuccess_.bind(this);
xhr.onerror = this.onContentUploadError_.bind(this);
xhr.send();
};
xhr.onload = this.onContentUploadSuccess_.bind(this)
xhr.onerror = this.onContentUploadError_.bind(this)
xhr.send()
}
/**
* Extract the last saved range if available in the request.
*
* @param {XMLHttpRequest} xhr Request object
*/
MediaUploader.prototype.extractRange_ = function(xhr) {
var range = xhr.getResponseHeader('Range');
MediaUploader.prototype.extractRange_ = function (xhr) {
var range = xhr.getResponseHeader('Range')
if (range) {
this.offset = parseInt(range.match(/\d+/g).pop(), 10) + 1;
this.offset = parseInt(range.match(/\d+/g).pop(), 10) + 1
}
};
}
/**
* Handle successful responses for uploads. Depending on the context,
@ -194,17 +193,17 @@ MediaUploader.prototype.extractRange_ = function(xhr) {
* @private
* @param {object} e XHR event
*/
MediaUploader.prototype.onContentUploadSuccess_ = function(e) {
if (e.target.status == 200 || e.target.status == 201) {
this.onComplete(e.target.response);
} else if (e.target.status == 308) {
this.extractRange_(e.target);
this.retryHandler.reset();
this.sendFile_();
MediaUploader.prototype.onContentUploadSuccess_ = function (e) {
if (e.target.status === 200 || e.target.status === 201) {
this.onComplete(e.target.response)
} else if (e.target.status === 308) {
this.extractRange_(e.target)
this.retryHandler.reset()
this.sendFile_()
} else {
this.onContentUploadError_(e);
this.onContentUploadError_(e)
}
};
}
/**
* Handles errors for uploads. Either retries or aborts depending
@ -213,13 +212,13 @@ MediaUploader.prototype.onContentUploadSuccess_ = function(e) {
* @private
* @param {object} e XHR event
*/
MediaUploader.prototype.onContentUploadError_ = function(e) {
MediaUploader.prototype.onContentUploadError_ = function (e) {
if (e.target.status && e.target.status < 500) {
this.onError(e.target.response);
this.onError(e.target.response)
} else {
this.retryHandler.retry(this.resume_.bind(this));
this.retryHandler.retry(this.resume_.bind(this))
}
};
}
/**
* Handles errors for the initial request.
@ -227,9 +226,9 @@ MediaUploader.prototype.onContentUploadError_ = function(e) {
* @private
* @param {object} e XHR event
*/
MediaUploader.prototype.onUploadError_ = function(e) {
this.onError(e.target.response); // TODO - Retries for initial upload
};
MediaUploader.prototype.onUploadError_ = function (e) {
this.onError(e.target.response) // TODO - Retries for initial upload
}
/**
* Construct a query string from a hash/object
@ -238,12 +237,12 @@ MediaUploader.prototype.onUploadError_ = function(e) {
* @param {object} [params] Key/value pairs for query string
* @return {string} query string
*/
MediaUploader.prototype.buildQuery_ = function(params) {
params = params || {};
return Object.keys(params).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
};
MediaUploader.prototype.buildQuery_ = function (params) {
params = params || {}
return Object.keys(params).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
}).join('&')
}
/**
* Build the drive upload URL
@ -253,16 +252,16 @@ MediaUploader.prototype.buildQuery_ = function(params) {
* @param {object} [params] Query parameters
* @return {string} URL
*/
MediaUploader.prototype.buildUrl_ = function(id, params, baseUrl) {
var url = baseUrl || 'https://www.googleapis.com/upload/drive/v2/files/';
MediaUploader.prototype.buildUrl_ = function (id, params, baseUrl) {
var url = baseUrl || 'https://www.googleapis.com/upload/drive/v2/files/'
if (id) {
url += id;
url += id
}
var query = this.buildQuery_(params);
var query = this.buildQuery_(params)
if (query) {
url += '?' + query;
url += '?' + query
}
return url;
};
return url
}
window.MediaUploader = MediaUploader;
window.MediaUploader = MediaUploader

View File

@ -1,372 +1,328 @@
import store from 'store';
import S from 'string';
/* eslint-env browser, jquery */
/* global serverurl, Cookies, moment */
import store from 'store'
import S from 'string'
import {
checkIfAuth
} from './lib/common/login';
} from './lib/common/login'
import {
urlpath
} from './lib/config';
} from './lib/config'
window.migrateHistoryFromTempCallback = null;
window.migrateHistoryFromTempCallback = null
migrateHistoryFromTemp();
migrateHistoryFromTemp()
function migrateHistoryFromTemp() {
if (url('#tempid')) {
$.get(`${serverurl}/temp`, {
tempid: url('#tempid')
})
.done(data => {
if (data && data.temp) {
getStorageHistory(olddata => {
if (!olddata || olddata.length == 0) {
saveHistoryToStorage(JSON.parse(data.temp));
}
});
}
})
.always(() => {
let hash = location.hash.split('#')[1];
hash = hash.split('&');
for (let i = 0; i < hash.length; i++)
if (hash[i].indexOf('tempid') == 0) {
hash.splice(i, 1);
i--;
}
hash = hash.join('&');
location.hash = hash;
if (migrateHistoryFromTempCallback)
migrateHistoryFromTempCallback();
});
}
function migrateHistoryFromTemp () {
if (window.url('#tempid')) {
$.get(`${serverurl}/temp`, {
tempid: window.url('#tempid')
})
.done(data => {
if (data && data.temp) {
getStorageHistory(olddata => {
if (!olddata || olddata.length === 0) {
saveHistoryToStorage(JSON.parse(data.temp))
}
})
}
})
.always(() => {
let hash = location.hash.split('#')[1]
hash = hash.split('&')
for (let i = 0; i < hash.length; i++) {
if (hash[i].indexOf('tempid') === 0) {
hash.splice(i, 1)
i--
}
}
hash = hash.join('&')
location.hash = hash
if (window.migrateHistoryFromTempCallback) { window.migrateHistoryFromTempCallback() }
})
}
}
export function saveHistory(notehistory) {
checkIfAuth(
export function saveHistory (notehistory) {
checkIfAuth(
() => {
saveHistoryToServer(notehistory);
saveHistoryToServer(notehistory)
},
() => {
saveHistoryToStorage(notehistory);
saveHistoryToStorage(notehistory)
}
);
)
}
function saveHistoryToStorage(notehistory) {
if (store.enabled)
store.set('notehistory', JSON.stringify(notehistory));
else
saveHistoryToCookie(notehistory);
function saveHistoryToStorage (notehistory) {
if (store.enabled) { store.set('notehistory', JSON.stringify(notehistory)) } else { saveHistoryToCookie(notehistory) }
}
function saveHistoryToCookie(notehistory) {
Cookies.set('notehistory', notehistory, {
expires: 365
});
function saveHistoryToCookie (notehistory) {
Cookies.set('notehistory', notehistory, {
expires: 365
})
}
function saveHistoryToServer(notehistory) {
function saveHistoryToServer (notehistory) {
$.post(`${serverurl}/history`, {
history: JSON.stringify(notehistory)
})
}
export function saveStorageHistoryToServer (callback) {
const data = store.get('notehistory')
if (data) {
$.post(`${serverurl}/history`, {
history: JSON.stringify(notehistory)
});
}
function saveCookieHistoryToStorage(callback) {
store.set('notehistory', Cookies.get('notehistory'));
callback();
}
export function saveStorageHistoryToServer(callback) {
const data = store.get('notehistory');
if (data) {
$.post(`${serverurl}/history`, {
history: data
})
history: data
})
.done(data => {
callback(data);
});
}
callback(data)
})
}
}
function saveCookieHistoryToServer(callback) {
$.post(`${serverurl}/history`, {
history: Cookies.get('notehistory')
})
.done(data => {
callback(data);
});
}
export function clearDuplicatedHistory(notehistory) {
const newnotehistory = [];
for (let i = 0; i < notehistory.length; i++) {
let found = false;
for (let j = 0; j < newnotehistory.length; j++) {
const id = notehistory[i].id.replace(/\=+$/, '');
const newId = newnotehistory[j].id.replace(/\=+$/, '');
if (id == newId || notehistory[i].id == newnotehistory[j].id || !notehistory[i].id || !newnotehistory[j].id) {
const time = (typeof notehistory[i].time === 'number' ? moment(notehistory[i].time) : moment(notehistory[i].time, 'MMMM Do YYYY, h:mm:ss a'));
const newTime = (typeof newnotehistory[i].time === 'number' ? moment(newnotehistory[i].time) : moment(newnotehistory[i].time, 'MMMM Do YYYY, h:mm:ss a'));
if(time >= newTime) {
newnotehistory[j] = notehistory[i];
}
found = true;
break;
}
export function clearDuplicatedHistory (notehistory) {
const newnotehistory = []
for (let i = 0; i < notehistory.length; i++) {
let found = false
for (let j = 0; j < newnotehistory.length; j++) {
const id = notehistory[i].id.replace(/=+$/, '')
const newId = newnotehistory[j].id.replace(/=+$/, '')
if (id === newId || notehistory[i].id === newnotehistory[j].id || !notehistory[i].id || !newnotehistory[j].id) {
const time = (typeof notehistory[i].time === 'number' ? moment(notehistory[i].time) : moment(notehistory[i].time, 'MMMM Do YYYY, h:mm:ss a'))
const newTime = (typeof newnotehistory[i].time === 'number' ? moment(newnotehistory[i].time) : moment(newnotehistory[i].time, 'MMMM Do YYYY, h:mm:ss a'))
if (time >= newTime) {
newnotehistory[j] = notehistory[i]
}
if (!found)
newnotehistory.push(notehistory[i]);
found = true
break
}
}
return newnotehistory;
if (!found) { newnotehistory.push(notehistory[i]) }
}
return newnotehistory
}
function addHistory(id, text, time, tags, pinned, notehistory) {
function addHistory (id, text, time, tags, pinned, notehistory) {
// only add when note id exists
if (id) {
notehistory.push({
id,
text,
time,
tags,
pinned
});
}
return notehistory;
if (id) {
notehistory.push({
id,
text,
time,
tags,
pinned
})
}
return notehistory
}
export function removeHistory(id, notehistory) {
for (let i = 0; i < notehistory.length; i++) {
if (notehistory[i].id == id) {
notehistory.splice(i, 1);
i -= 1;
}
export function removeHistory (id, notehistory) {
for (let i = 0; i < notehistory.length; i++) {
if (notehistory[i].id === id) {
notehistory.splice(i, 1)
i -= 1
}
return notehistory;
}
return notehistory
}
//used for inner
export function writeHistory(title, tags) {
checkIfAuth(
// used for inner
export function writeHistory (title, tags) {
checkIfAuth(
() => {
// no need to do this anymore, this will count from server-side
// writeHistoryToServer(title, tags);
},
() => {
writeHistoryToStorage(title, tags);
writeHistoryToStorage(title, tags)
}
);
)
}
function writeHistoryToServer(title, tags) {
$.get(`${serverurl}/history`)
.done(data => {
try {
if (data.history) {
var notehistory = data.history;
} else {
var notehistory = [];
}
} catch (err) {
var notehistory = [];
}
if (!notehistory)
notehistory = [];
const newnotehistory = generateHistory(title, tags, notehistory);
saveHistoryToServer(newnotehistory);
})
.fail((xhr, status, error) => {
console.error(xhr.responseText);
});
function writeHistoryToCookie (title, tags) {
var notehistory
try {
notehistory = Cookies.getJSON('notehistory')
} catch (err) {
notehistory = []
}
if (!notehistory) { notehistory = [] }
const newnotehistory = generateHistory(title, tags, notehistory)
saveHistoryToCookie(newnotehistory)
}
function writeHistoryToCookie(title, tags) {
try {
var notehistory = Cookies.getJSON('notehistory');
} catch (err) {
var notehistory = [];
}
if (!notehistory)
notehistory = [];
const newnotehistory = generateHistory(title, tags, notehistory);
saveHistoryToCookie(newnotehistory);
}
function writeHistoryToStorage(title, tags) {
if (store.enabled) {
let data = store.get('notehistory');
if (data) {
if (typeof data == "string")
data = JSON.parse(data);
var notehistory = data;
} else
var notehistory = [];
if (!notehistory)
notehistory = [];
const newnotehistory = generateHistory(title, tags, notehistory);
saveHistoryToStorage(newnotehistory);
function writeHistoryToStorage (title, tags) {
if (store.enabled) {
let data = store.get('notehistory')
var notehistory
if (data) {
if (typeof data === 'string') { data = JSON.parse(data) }
notehistory = data
} else {
writeHistoryToCookie(title, tags);
notehistory = []
}
if (!notehistory) { notehistory = [] }
const newnotehistory = generateHistory(title, tags, notehistory)
saveHistoryToStorage(newnotehistory)
} else {
writeHistoryToCookie(title, tags)
}
}
if (!Array.isArray) {
Array.isArray = arg => Object.prototype.toString.call(arg) === '[object Array]';
Array.isArray = arg => Object.prototype.toString.call(arg) === '[object Array]'
}
function renderHistory(title, tags) {
//console.debug(tags);
const id = urlpath ? location.pathname.slice(urlpath.length + 1, location.pathname.length).split('/')[1] : location.pathname.split('/')[1];
return {
id,
text: title,
time: moment().valueOf(),
tags
};
function renderHistory (title, tags) {
// console.debug(tags);
const id = urlpath ? location.pathname.slice(urlpath.length + 1, location.pathname.length).split('/')[1] : location.pathname.split('/')[1]
return {
id,
text: title,
time: moment().valueOf(),
tags
}
}
function generateHistory(title, tags, notehistory) {
const info = renderHistory(title, tags);
//keep any pinned data
let pinned = false;
function generateHistory (title, tags, notehistory) {
const info = renderHistory(title, tags)
// keep any pinned data
let pinned = false
for (let i = 0; i < notehistory.length; i++) {
if (notehistory[i].id === info.id && notehistory[i].pinned) {
pinned = true
break
}
}
notehistory = removeHistory(info.id, notehistory)
notehistory = addHistory(info.id, info.text, info.time, info.tags, pinned, notehistory)
notehistory = clearDuplicatedHistory(notehistory)
return notehistory
}
// used for outer
export function getHistory (callback) {
checkIfAuth(
() => {
getServerHistory(callback)
},
() => {
getStorageHistory(callback)
}
)
}
function getServerHistory (callback) {
$.get(`${serverurl}/history`)
.done(data => {
if (data.history) {
callback(data.history)
}
})
.fail((xhr, status, error) => {
console.error(xhr.responseText)
})
}
function getCookieHistory (callback) {
callback(Cookies.getJSON('notehistory'))
}
export function getStorageHistory (callback) {
if (store.enabled) {
let data = store.get('notehistory')
if (data) {
if (typeof data === 'string') { data = JSON.parse(data) }
callback(data)
} else { getCookieHistory(callback) }
} else {
getCookieHistory(callback)
}
}
export function parseHistory (list, callback) {
checkIfAuth(
() => {
parseServerToHistory(list, callback)
},
() => {
parseStorageToHistory(list, callback)
}
)
}
export function parseServerToHistory (list, callback) {
$.get(`${serverurl}/history`)
.done(data => {
if (data.history) {
parseToHistory(list, data.history, callback)
}
})
.fail((xhr, status, error) => {
console.error(xhr.responseText)
})
}
function parseCookieToHistory (list, callback) {
const notehistory = Cookies.getJSON('notehistory')
parseToHistory(list, notehistory, callback)
}
export function parseStorageToHistory (list, callback) {
if (store.enabled) {
let data = store.get('notehistory')
if (data) {
if (typeof data === 'string') { data = JSON.parse(data) }
parseToHistory(list, data, callback)
} else { parseCookieToHistory(list, callback) }
} else {
parseCookieToHistory(list, callback)
}
}
function parseToHistory (list, notehistory, callback) {
if (!callback) return
else if (!list || !notehistory) callback(list, notehistory)
else if (notehistory && notehistory.length > 0) {
for (let i = 0; i < notehistory.length; i++) {
if (notehistory[i].id == info.id && notehistory[i].pinned) {
pinned = true;
break;
}
}
notehistory = removeHistory(info.id, notehistory);
notehistory = addHistory(info.id, info.text, info.time, info.tags, pinned, notehistory);
notehistory = clearDuplicatedHistory(notehistory);
return notehistory;
}
//used for outer
export function getHistory(callback) {
checkIfAuth(
() => {
getServerHistory(callback);
},
() => {
getStorageHistory(callback);
}
);
}
function getServerHistory(callback) {
$.get(`${serverurl}/history`)
.done(data => {
if (data.history) {
callback(data.history);
}
})
.fail((xhr, status, error) => {
console.error(xhr.responseText);
});
}
function getCookieHistory(callback) {
callback(Cookies.getJSON('notehistory'));
}
export function getStorageHistory(callback) {
if (store.enabled) {
let data = store.get('notehistory');
if (data) {
if (typeof data == "string")
data = JSON.parse(data);
callback(data);
} else
getCookieHistory(callback);
} else {
getCookieHistory(callback);
}
}
export function parseHistory(list, callback) {
checkIfAuth(
() => {
parseServerToHistory(list, callback);
},
() => {
parseStorageToHistory(list, callback);
}
);
}
export function parseServerToHistory(list, callback) {
$.get(`${serverurl}/history`)
.done(data => {
if (data.history) {
parseToHistory(list, data.history, callback);
}
})
.fail((xhr, status, error) => {
console.error(xhr.responseText);
});
}
function parseCookieToHistory(list, callback) {
const notehistory = Cookies.getJSON('notehistory');
parseToHistory(list, notehistory, callback);
}
export function parseStorageToHistory(list, callback) {
if (store.enabled) {
let data = store.get('notehistory');
if (data) {
if (typeof data == "string")
data = JSON.parse(data);
parseToHistory(list, data, callback);
} else
parseCookieToHistory(list, callback);
} else {
parseCookieToHistory(list, callback);
}
}
function parseToHistory(list, notehistory, callback) {
if (!callback) return;
else if (!list || !notehistory) callback(list, notehistory);
else if (notehistory && notehistory.length > 0) {
for (let i = 0; i < notehistory.length; i++) {
//parse time to timestamp and fromNow
const timestamp = (typeof notehistory[i].time === 'number' ? moment(notehistory[i].time) : moment(notehistory[i].time, 'MMMM Do YYYY, h:mm:ss a'));
notehistory[i].timestamp = timestamp.valueOf();
notehistory[i].fromNow = timestamp.fromNow();
notehistory[i].time = timestamp.format('llll');
// parse time to timestamp and fromNow
const timestamp = (typeof notehistory[i].time === 'number' ? moment(notehistory[i].time) : moment(notehistory[i].time, 'MMMM Do YYYY, h:mm:ss a'))
notehistory[i].timestamp = timestamp.valueOf()
notehistory[i].fromNow = timestamp.fromNow()
notehistory[i].time = timestamp.format('llll')
// prevent XSS
notehistory[i].text = S(notehistory[i].text).escapeHTML().s;
notehistory[i].tags = (notehistory[i].tags && notehistory[i].tags.length > 0) ? S(notehistory[i].tags).escapeHTML().s.split(',') : [];
notehistory[i].text = S(notehistory[i].text).escapeHTML().s
notehistory[i].tags = (notehistory[i].tags && notehistory[i].tags.length > 0) ? S(notehistory[i].tags).escapeHTML().s.split(',') : []
// add to list
if (notehistory[i].id && list.get('id', notehistory[i].id).length == 0)
list.add(notehistory[i]);
}
if (notehistory[i].id && list.get('id', notehistory[i].id).length === 0) { list.add(notehistory[i]) }
}
callback(list, notehistory);
}
callback(list, notehistory)
}
export function postHistoryToServer(noteId, data, callback) {
$.post(`${serverurl}/history/${noteId}`, data)
export function postHistoryToServer (noteId, data, callback) {
$.post(`${serverurl}/history/${noteId}`, data)
.done(result => callback(null, result))
.fail((xhr, status, error) => {
console.error(xhr.responseText);
return callback(error, null);
});
}
export function deleteServerHistory(noteId, callback) {
$.ajax({
url: `${serverurl}/history${noteId ? '/' + noteId : ""}`,
type: 'DELETE'
console.error(xhr.responseText)
return callback(error, null)
})
}
export function deleteServerHistory (noteId, callback) {
$.ajax({
url: `${serverurl}/history${noteId ? '/' + noteId : ''}`,
type: 'DELETE'
})
.done(result => callback(null, result))
.fail((xhr, status, error) => {
console.error(xhr.responseText);
return callback(error, null);
});
console.error(xhr.responseText)
return callback(error, null)
})
}

View File

@ -1,6 +1,6 @@
require('../css/github-extract.css');
require('../css/markdown.css');
require('../css/extra.css');
require('../css/slide-preview.css');
require('../css/google-font.css');
require('../css/site.css');
require('../css/github-extract.css')
require('../css/markdown.css')
require('../css/extra.css')
require('../css/slide-preview.css')
require('../css/google-font.css')
require('../css/site.css')

File diff suppressed because it is too large Load Diff

View File

@ -1,89 +1,92 @@
import { serverurl } from '../config';
/* eslint-env browser, jquery */
/* global Cookies */
let checkAuth = false;
let profile = null;
let lastLoginState = getLoginState();
let lastUserId = getUserId();
var loginStateChangeEvent = null;
import { serverurl } from '../config'
export function setloginStateChangeEvent(func) {
loginStateChangeEvent = func;
let checkAuth = false
let profile = null
let lastLoginState = getLoginState()
let lastUserId = getUserId()
var loginStateChangeEvent = null
export function setloginStateChangeEvent (func) {
loginStateChangeEvent = func
}
export function resetCheckAuth() {
checkAuth = false;
export function resetCheckAuth () {
checkAuth = false
}
export function setLoginState(bool, id) {
Cookies.set('loginstate', bool, {
expires: 365
});
if (id) {
Cookies.set('userid', id, {
expires: 365
});
} else {
Cookies.remove('userid');
}
lastLoginState = bool;
lastUserId = id;
checkLoginStateChanged();
export function setLoginState (bool, id) {
Cookies.set('loginstate', bool, {
expires: 365
})
if (id) {
Cookies.set('userid', id, {
expires: 365
})
} else {
Cookies.remove('userid')
}
lastLoginState = bool
lastUserId = id
checkLoginStateChanged()
}
export function checkLoginStateChanged() {
if (getLoginState() != lastLoginState || getUserId() != lastUserId) {
if (loginStateChangeEvent) setTimeout(loginStateChangeEvent, 100);
return true;
} else {
return false;
}
export function checkLoginStateChanged () {
if (getLoginState() !== lastLoginState || getUserId() !== lastUserId) {
if (loginStateChangeEvent) setTimeout(loginStateChangeEvent, 100)
return true
} else {
return false
}
}
export function getLoginState() {
const state = Cookies.get('loginstate');
return state === "true" || state === true;
export function getLoginState () {
const state = Cookies.get('loginstate')
return state === 'true' || state === true
}
export function getUserId() {
return Cookies.get('userid');
export function getUserId () {
return Cookies.get('userid')
}
export function clearLoginState() {
Cookies.remove('loginstate');
export function clearLoginState () {
Cookies.remove('loginstate')
}
export function checkIfAuth(yesCallback, noCallback) {
const cookieLoginState = getLoginState();
if (checkLoginStateChanged()) checkAuth = false;
if (!checkAuth || typeof cookieLoginState == 'undefined') {
$.get(`${serverurl}/me`)
export function checkIfAuth (yesCallback, noCallback) {
const cookieLoginState = getLoginState()
if (checkLoginStateChanged()) checkAuth = false
if (!checkAuth || typeof cookieLoginState === 'undefined') {
$.get(`${serverurl}/me`)
.done(data => {
if (data && data.status == 'ok') {
profile = data;
yesCallback(profile);
setLoginState(true, data.id);
} else {
noCallback();
setLoginState(false);
}
if (data && data.status === 'ok') {
profile = data
yesCallback(profile)
setLoginState(true, data.id)
} else {
noCallback()
setLoginState(false)
}
})
.fail(() => {
noCallback();
noCallback()
})
.always(() => {
checkAuth = true;
});
} else if (cookieLoginState) {
yesCallback(profile);
} else {
noCallback();
}
checkAuth = true
})
} else if (cookieLoginState) {
yesCallback(profile)
} else {
noCallback()
}
}
export default {
checkAuth,
profile,
lastLoginState,
lastUserId,
loginStateChangeEvent
};
checkAuth,
profile,
lastLoginState,
lastUserId,
loginStateChangeEvent
}

View File

@ -1,19 +1,19 @@
import configJson from '../../../../config.json'; // root path json config
import configJson from '../../../../config.json' // root path json config
const config = 'production' === process.env.NODE_ENV ? configJson.production : configJson.development;
const config = process.env.NODE_ENV === 'production' ? configJson.production : configJson.development
export const GOOGLE_API_KEY = (config.google && config.google.apiKey) || '';
export const GOOGLE_CLIENT_ID = (config.google && config.google.clientID) || '';
export const DROPBOX_APP_KEY = (config.dropbox && config.dropbox.appKey) || '';
export const GOOGLE_API_KEY = (config.google && config.google.apiKey) || ''
export const GOOGLE_CLIENT_ID = (config.google && config.google.clientID) || ''
export const DROPBOX_APP_KEY = (config.dropbox && config.dropbox.appKey) || ''
export const domain = config.domain || ''; // domain name
export const urlpath = config.urlpath || ''; // sub url path, like: www.example.com/<urlpath>
export const debug = config.debug || false;
export const domain = config.domain || '' // domain name
export const urlpath = config.urlpath || '' // sub url path, like: www.example.com/<urlpath>
export const debug = config.debug || false
export const port = window.location.port;
export const serverurl = `${window.location.protocol}//${domain ? domain : window.location.hostname}${port ? ':' + port : ''}${urlpath ? '/' + urlpath : ''}`;
window.serverurl = serverurl;
export const noteid = urlpath ? window.location.pathname.slice(urlpath.length + 1, window.location.pathname.length).split('/')[1] : window.location.pathname.split('/')[1];
export const noteurl = `${serverurl}/${noteid}`;
export const port = window.location.port
export const serverurl = `${window.location.protocol}//${domain || window.location.hostname}${port ? ':' + port : ''}${urlpath ? '/' + urlpath : ''}`
window.serverurl = serverurl
export const noteid = urlpath ? window.location.pathname.slice(urlpath.length + 1, window.location.pathname.length).split('/')[1] : window.location.pathname.split('/')[1]
export const noteurl = `${serverurl}/${noteid}`
export const version = '0.5.0';
export const version = '0.5.0'

View File

@ -1,26 +1,28 @@
var lang = "en";
var userLang = navigator.language || navigator.userLanguage;
var userLangCode = userLang.split('-')[0];
var userCountryCode = userLang.split('-')[1];
var locale = $('.ui-locale');
var supportLangs = [];
$(".ui-locale option").each(function() {
supportLangs.push($(this).val());
});
/* eslint-env browser, jquery */
/* global Cookies */
var lang = 'en'
var userLang = navigator.language || navigator.userLanguage
var userLangCode = userLang.split('-')[0]
var locale = $('.ui-locale')
var supportLangs = []
$('.ui-locale option').each(function () {
supportLangs.push($(this).val())
})
if (Cookies.get('locale')) {
lang = Cookies.get('locale');
lang = Cookies.get('locale')
} else if (supportLangs.indexOf(userLang) !== -1) {
lang = supportLangs[supportLangs.indexOf(userLang)];
lang = supportLangs[supportLangs.indexOf(userLang)]
} else if (supportLangs.indexOf(userLangCode) !== -1) {
lang = supportLangs[supportLangs.indexOf(userLangCode)];
lang = supportLangs[supportLangs.indexOf(userLangCode)]
}
locale.val(lang);
$('select.ui-locale option[value="' + lang + '"]').attr('selected','selected');
locale.val(lang)
$('select.ui-locale option[value="' + lang + '"]').attr('selected', 'selected')
locale.change(function() {
Cookies.set('locale', $(this).val(), {
expires: 365
});
window.location.reload();
});
locale.change(function () {
Cookies.set('locale', $(this).val(), {
expires: 365
})
window.location.reload()
})

View File

@ -1,8 +1,11 @@
require('../css/extra.css');
require('../css/slide-preview.css');
require('../css/site.css');
/* eslint-env browser, jquery */
/* global refreshView */
require('highlight.js/styles/github-gist.css');
require('../css/extra.css')
require('../css/slide-preview.css')
require('../css/site.css')
require('highlight.js/styles/github-gist.css')
import {
autoLinkify,
@ -16,126 +19,126 @@ import {
scrollToHash,
smoothHashScroll,
updateLastChange
} from './extra';
} from './extra'
import { preventXSS } from './render';
import { preventXSS } from './render'
const markdown = $("#doc.markdown-body");
const text = markdown.text();
const lastMeta = md.meta;
md.meta = {};
delete md.metaError;
let rendered = md.render(text);
const markdown = $('#doc.markdown-body')
const text = markdown.text()
const lastMeta = md.meta
md.meta = {}
delete md.metaError
let rendered = md.render(text)
if (md.meta.type && md.meta.type === 'slide') {
const slideOptions = {
separator: '^(\r\n?|\n)---(\r\n?|\n)$',
verticalSeparator: '^(\r\n?|\n)----(\r\n?|\n)$'
};
const slides = RevealMarkdown.slidify(text, slideOptions);
markdown.html(slides);
RevealMarkdown.initialize();
const slideOptions = {
separator: '^(\r\n?|\n)---(\r\n?|\n)$',
verticalSeparator: '^(\r\n?|\n)----(\r\n?|\n)$'
}
const slides = window.RevealMarkdown.slidify(text, slideOptions)
markdown.html(slides)
window.RevealMarkdown.initialize()
// prevent XSS
markdown.html(preventXSS(markdown.html()));
markdown.addClass('slides');
markdown.html(preventXSS(markdown.html()))
markdown.addClass('slides')
} else {
if (lastMeta.type && lastMeta.type === 'slide') {
refreshView();
markdown.removeClass('slides');
}
if (lastMeta.type && lastMeta.type === 'slide') {
refreshView()
markdown.removeClass('slides')
}
// only render again when meta changed
if (JSON.stringify(md.meta) != JSON.stringify(lastMeta)) {
parseMeta(md, null, markdown, $('#ui-toc'), $('#ui-toc-affix'));
rendered = md.render(text);
}
if (JSON.stringify(md.meta) !== JSON.stringify(lastMeta)) {
parseMeta(md, null, markdown, $('#ui-toc'), $('#ui-toc-affix'))
rendered = md.render(text)
}
// prevent XSS
rendered = preventXSS(rendered);
const result = postProcess(rendered);
markdown.html(result.html());
rendered = preventXSS(rendered)
const result = postProcess(rendered)
markdown.html(result.html())
}
$(document.body).show();
$(document.body).show()
finishView(markdown);
autoLinkify(markdown);
deduplicatedHeaderId(markdown);
renderTOC(markdown);
generateToc('ui-toc');
generateToc('ui-toc-affix');
smoothHashScroll();
createtime = lastchangeui.time.attr('data-createtime');
lastchangetime = lastchangeui.time.attr('data-updatetime');
updateLastChange();
finishView(markdown)
autoLinkify(markdown)
deduplicatedHeaderId(markdown)
renderTOC(markdown)
generateToc('ui-toc')
generateToc('ui-toc-affix')
smoothHashScroll()
window.createtime = window.lastchangeui.time.attr('data-createtime')
window.lastchangetime = window.lastchangeui.time.attr('data-updatetime')
updateLastChange()
const url = window.location.pathname;
$('.ui-edit').attr('href', `${url}/edit`);
const toc = $('.ui-toc');
const tocAffix = $('.ui-affix-toc');
const tocDropdown = $('.ui-toc-dropdown');
//toc
const url = window.location.pathname
$('.ui-edit').attr('href', `${url}/edit`)
const toc = $('.ui-toc')
const tocAffix = $('.ui-affix-toc')
const tocDropdown = $('.ui-toc-dropdown')
// toc
tocDropdown.click(e => {
e.stopPropagation();
});
e.stopPropagation()
})
let enoughForAffixToc = true;
let enoughForAffixToc = true
function generateScrollspy() {
$(document.body).scrollspy({
target: ''
});
$(document.body).scrollspy('refresh');
if (enoughForAffixToc) {
toc.hide();
tocAffix.show();
} else {
tocAffix.hide();
toc.show();
}
$(document.body).scroll();
function generateScrollspy () {
$(document.body).scrollspy({
target: ''
})
$(document.body).scrollspy('refresh')
if (enoughForAffixToc) {
toc.hide()
tocAffix.show()
} else {
tocAffix.hide()
toc.show()
}
$(document.body).scroll()
}
function windowResize() {
//toc right
const paddingRight = parseFloat(markdown.css('padding-right'));
const right = ($(window).width() - (markdown.offset().left + markdown.outerWidth() - paddingRight));
toc.css('right', `${right}px`);
//affix toc left
let newbool;
const rightMargin = (markdown.parent().outerWidth() - markdown.outerWidth()) / 2;
//for ipad or wider device
if (rightMargin >= 133) {
newbool = true;
const affixLeftMargin = (tocAffix.outerWidth() - tocAffix.width()) / 2;
const left = markdown.offset().left + markdown.outerWidth() - affixLeftMargin;
tocAffix.css('left', `${left}px`);
} else {
newbool = false;
}
if (newbool != enoughForAffixToc) {
enoughForAffixToc = newbool;
generateScrollspy();
}
function windowResize () {
// toc right
const paddingRight = parseFloat(markdown.css('padding-right'))
const right = ($(window).width() - (markdown.offset().left + markdown.outerWidth() - paddingRight))
toc.css('right', `${right}px`)
// affix toc left
let newbool
const rightMargin = (markdown.parent().outerWidth() - markdown.outerWidth()) / 2
// for ipad or wider device
if (rightMargin >= 133) {
newbool = true
const affixLeftMargin = (tocAffix.outerWidth() - tocAffix.width()) / 2
const left = markdown.offset().left + markdown.outerWidth() - affixLeftMargin
tocAffix.css('left', `${left}px`)
} else {
newbool = false
}
if (newbool !== enoughForAffixToc) {
enoughForAffixToc = newbool
generateScrollspy()
}
}
$(window).resize(() => {
windowResize();
});
windowResize()
})
$(document).ready(() => {
windowResize();
generateScrollspy();
setTimeout(scrollToHash, 0);
//tooltip
$('[data-toggle="tooltip"]').tooltip();
});
windowResize()
generateScrollspy()
setTimeout(scrollToHash, 0)
// tooltip
$('[data-toggle="tooltip"]').tooltip()
})
export function scrollToTop() {
$('body, html').stop(true, true).animate({
scrollTop: 0
}, 100, "linear");
export function scrollToTop () {
$('body, html').stop(true, true).animate({
scrollTop: 0
}, 100, 'linear')
}
export function scrollToBottom() {
$('body, html').stop(true, true).animate({
scrollTop: $(document.body)[0].scrollHeight
}, 100, "linear");
export function scrollToBottom () {
$('body, html').stop(true, true).animate({
scrollTop: $(document.body)[0].scrollHeight
}, 100, 'linear')
}
window.scrollToTop = scrollToTop;
window.scrollToBottom = scrollToBottom;
window.scrollToTop = scrollToTop
window.scrollToBottom = scrollToBottom

View File

@ -1,62 +1,64 @@
/* eslint-env browser, jquery */
/* global filterXSS */
// allow some attributes
var whiteListAttr = ['id', 'class', 'style'];
window.whiteListAttr = whiteListAttr;
var whiteListAttr = ['id', 'class', 'style']
window.whiteListAttr = whiteListAttr
// allow link starts with '.', '/' and custom protocol with '://'
var linkRegex = /^([\w|-]+:\/\/)|^([\.|\/])+/;
var linkRegex = /^([\w|-]+:\/\/)|^([.|/])+/
// allow data uri, from https://gist.github.com/bgrins/6194623
var dataUriRegex = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*)\s*$/i;
var dataUriRegex = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@/?%\s]*)\s*$/i
// custom white list
var whiteList = filterXSS.whiteList;
var whiteList = filterXSS.whiteList
// allow ol specify start number
whiteList['ol'] = ['start'];
whiteList['ol'] = ['start']
// allow li specify value number
whiteList['li'] = ['value'];
whiteList['li'] = ['value']
// allow style tag
whiteList['style'] = [];
whiteList['style'] = []
// allow kbd tag
whiteList['kbd'] = [];
whiteList['kbd'] = []
// allow ifram tag with some safe attributes
whiteList['iframe'] = ['allowfullscreen', 'name', 'referrerpolicy', 'sandbox', 'src', 'srcdoc', 'width', 'height'];
whiteList['iframe'] = ['allowfullscreen', 'name', 'referrerpolicy', 'sandbox', 'src', 'srcdoc', 'width', 'height']
// allow summary tag
whiteList['summary'] = [];
whiteList['summary'] = []
var filterXSSOptions = {
allowCommentTag: true,
whiteList: whiteList,
escapeHtml: function (html) {
allowCommentTag: true,
whiteList: whiteList,
escapeHtml: function (html) {
// allow html comment in multiple lines
return html.replace(/<(.*?)>/g, '&lt;$1&gt;');
},
onIgnoreTag: function (tag, html, options) {
return html.replace(/<(.*?)>/g, '&lt;$1&gt;')
},
onIgnoreTag: function (tag, html, options) {
// allow comment tag
if (tag == "!--") {
if (tag === '!--') {
// do not filter its attributes
return html;
}
},
onTagAttr: function (tag, name, value, isWhiteAttr) {
// allow href and src that match linkRegex
if (isWhiteAttr && (name === 'href' || name === 'src') && linkRegex.test(value)) {
return name + '="' + filterXSS.escapeAttrValue(value) + '"';
}
// allow data uri in img src
if (isWhiteAttr && (tag == "img" && name === 'src') && dataUriRegex.test(value)) {
return name + '="' + filterXSS.escapeAttrValue(value) + '"';
}
},
onIgnoreTagAttr: function (tag, name, value, isWhiteAttr) {
// allow attr start with 'data-' or in the whiteListAttr
if (name.substr(0, 5) === 'data-' || whiteListAttr.indexOf(name) !== -1) {
// escape its value using built-in escapeAttrValue function
return name + '="' + filterXSS.escapeAttrValue(value) + '"';
}
return html
}
};
function preventXSS(html) {
return filterXSS(html, filterXSSOptions);
},
onTagAttr: function (tag, name, value, isWhiteAttr) {
// allow href and src that match linkRegex
if (isWhiteAttr && (name === 'href' || name === 'src') && linkRegex.test(value)) {
return name + '="' + filterXSS.escapeAttrValue(value) + '"'
}
// allow data uri in img src
if (isWhiteAttr && (tag === 'img' && name === 'src') && dataUriRegex.test(value)) {
return name + '="' + filterXSS.escapeAttrValue(value) + '"'
}
},
onIgnoreTagAttr: function (tag, name, value, isWhiteAttr) {
// allow attr start with 'data-' or in the whiteListAttr
if (name.substr(0, 5) === 'data-' || window.whiteListAttr.indexOf(name) !== -1) {
// escape its value using built-in escapeAttrValue function
return name + '="' + filterXSS.escapeAttrValue(value) + '"'
}
}
}
window.preventXSS = preventXSS;
function preventXSS (html) {
return filterXSS(html, filterXSSOptions)
}
window.preventXSS = preventXSS
module.exports = {
preventXSS: preventXSS

View File

@ -1,396 +1,355 @@
/* eslint-env browser, jquery */
import { preventXSS } from './render'
import { md } from './extra'
/**
* The reveal.js markdown plugin. Handles parsing of
* markdown inside of presentations as well as loading
* of external markdown documents.
*/
(function( root, factory ) {
if( typeof exports === 'object' ) {
module.exports = factory();
}
else {
// Browser globals (root is window)
root.RevealMarkdown = factory();
root.RevealMarkdown.initialize();
}
}( this, function() {
var DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$',
DEFAULT_NOTES_SEPARATOR = 'note:',
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';
var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';
/**
* Retrieves the markdown contents of a slide section
* element. Normalizes leading tabs/whitespace.
*/
function getMarkdownFromSlide( section ) {
var template = section.querySelector( 'script' );
// strip leading whitespace so it isn't evaluated as code
var text = ( template || section ).textContent;
// restore script end tags
text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );
var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
if( leadingTabs > 0 ) {
text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
}
else if( leadingWs > 1 ) {
text = text.replace( new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n' );
}
return text;
}
/**
* Given a markdown slide section element, this will
* return all arguments that aren't related to markdown
* parsing. Used to forward any other user-defined arguments
* to the output markdown slide.
*/
function getForwardedAttributes( section ) {
var attributes = section.attributes;
var result = [];
for( var i = 0, len = attributes.length; i < len; i++ ) {
var name = attributes[i].name,
value = attributes[i].value;
// disregard attributes that are used for markdown loading/parsing
if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
if( value ) {
result.push( name + '="' + value + '"' );
}
else {
result.push( name );
}
}
return result.join( ' ' );
}
/**
* Inspects the given options and fills out default
* values for what's not defined.
*/
function getSlidifyOptions( options ) {
options = options || {};
options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
options.attributes = options.attributes || '';
return options;
}
/**
* Helper function for constructing a markdown slide.
*/
function createMarkdownSlide( content, options ) {
options = getSlidifyOptions( options );
var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
if( notesMatch.length === 2 ) {
content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>';
}
// prevent script end tags in the content from interfering
// with parsing
content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );
return '<script type="text/template">' + content + '</script>';
}
/**
* Parses a data string into multiple slides based
* on the passed in separator arguments.
*/
function slidify( markdown, options ) {
options = getSlidifyOptions( options );
var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
horizontalSeparatorRegex = new RegExp( options.separator );
var matches,
lastIndex = 0,
isHorizontal,
wasHorizontal = true,
content,
sectionStack = [];
// iterate until all blocks between separators are stacked up
while( matches = separatorRegex.exec( markdown ) ) {
notes = null;
// determine direction (horizontal by default)
isHorizontal = horizontalSeparatorRegex.test( matches[0] );
if( !isHorizontal && wasHorizontal ) {
// create vertical stack
sectionStack.push( [] );
}
// pluck slide content from markdown input
content = markdown.substring( lastIndex, matches.index );
if( isHorizontal && wasHorizontal ) {
// add to horizontal stack
sectionStack.push( content );
}
else {
// add to vertical stack
sectionStack[sectionStack.length-1].push( content );
}
lastIndex = separatorRegex.lastIndex;
wasHorizontal = isHorizontal;
}
// add the remaining slide
( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
var markdownSections = '';
// flatten the hierarchical stack, and insert <section data-markdown> tags
for( var i = 0, len = sectionStack.length; i < len; i++ ) {
// vertical
if( sectionStack[i] instanceof Array ) {
markdownSections += '<section '+ options.attributes +'>';
sectionStack[i].forEach( function( child ) {
markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
} );
markdownSections += '</section>';
}
else {
markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
}
}
return markdownSections;
}
/**
* Parses any current data-markdown slides, splits
* multi-slide markdown into separate sections and
* handles loading of external markdown.
*/
function processSlides() {
var sections = document.querySelectorAll( '[data-markdown]'),
section;
for( var i = 0, len = sections.length; i < len; i++ ) {
section = sections[i];
if( section.getAttribute( 'data-markdown' ).length ) {
var xhr = new XMLHttpRequest(),
url = section.getAttribute( 'data-markdown' );
datacharset = section.getAttribute( 'data-charset' );
// see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
if( datacharset != null && datacharset != '' ) {
xhr.overrideMimeType( 'text/html; charset=' + datacharset );
}
xhr.onreadystatechange = function() {
if( xhr.readyState === 4 ) {
// file protocol yields status code 0 (useful for local debug, mobile applications etc.)
if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {
section.outerHTML = slidify( xhr.responseText, {
separator: section.getAttribute( 'data-separator' ),
verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
notesSeparator: section.getAttribute( 'data-separator-notes' ),
attributes: getForwardedAttributes( section )
});
}
else {
section.outerHTML = '<section data-state="alert">' +
'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
'Check your browser\'s JavaScript console for more details.' +
'<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
'</section>';
}
}
};
xhr.open( 'GET', url, false );
try {
xhr.send();
}
catch ( e ) {
alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e );
}
}
else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) {
section.outerHTML = slidify( getMarkdownFromSlide( section ), {
separator: section.getAttribute( 'data-separator' ),
verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
notesSeparator: section.getAttribute( 'data-separator-notes' ),
attributes: getForwardedAttributes( section )
});
}
else {
section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
}
}
}
/**
* Check if a node value has the attributes pattern.
* If yes, extract it and add that value as one or several attributes
* the the terget element.
*
* You need Cache Killer on Chrome to see the effect on any FOM transformation
* directly on refresh (F5)
* http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
*/
function addAttributeInElement( node, elementTarget, separator ) {
var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
var nodeValue = node.nodeValue;
if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
var classes = matches[1];
nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
node.nodeValue = nodeValue;
while( matchesClass = mardownClassRegex.exec( classes ) ) {
var name = matchesClass[1];
var value = matchesClass[2];
if (name.substr(0, 5) === 'data-' || whiteListAttr.indexOf(name) !== -1)
elementTarget.setAttribute( name, filterXSS.escapeAttrValue(value) );
}
return true;
}
return false;
}
/**
* Add attributes to the parent element of a text node,
* or the element of an attribute node.
*/
function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
previousParentElement = element;
for( var i = 0; i < element.childNodes.length; i++ ) {
childElement = element.childNodes[i];
if ( i > 0 ) {
j = i - 1;
while ( j >= 0 ) {
aPreviousChildElement = element.childNodes[j];
if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
previousParentElement = aPreviousChildElement;
break;
}
j = j - 1;
}
}
parentSection = section;
if( childElement.nodeName == "section" ) {
parentSection = childElement ;
previousParentElement = childElement ;
}
if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
}
}
}
if ( element.nodeType == Node.COMMENT_NODE ) {
if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
addAttributeInElement( element, section, separatorSectionAttributes );
}
}
}
/**
* Converts any current data-markdown slides in the
* DOM to HTML.
*/
function convertSlides() {
var sections = document.querySelectorAll( '[data-markdown]');
for( var i = 0, len = sections.length; i < len; i++ ) {
var section = sections[i];
// Only parse the same slide once
if( !section.getAttribute( 'data-markdown-parsed' ) ) {
section.setAttribute( 'data-markdown-parsed', true )
var notes = section.querySelector( 'aside.notes' );
var markdown = getMarkdownFromSlide( section );
var rendered = md.render(markdown);
rendered = preventXSS(rendered);
var result = postProcess(rendered);
section.innerHTML = result[0].outerHTML;
addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
section.parentNode.getAttribute( 'data-element-attributes' ) ||
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
section.getAttribute( 'data-attributes' ) ||
section.parentNode.getAttribute( 'data-attributes' ) ||
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
// If there were notes, we need to re-add them after
// having overwritten the section's HTML
if( notes ) {
section.appendChild( notes );
}
}
}
}
// API
return {
initialize: function() {
processSlides();
convertSlides();
},
// TODO: Do these belong in the API?
processSlides: processSlides,
convertSlides: convertSlides,
slidify: slidify
};
}));
(function (root, factory) {
if (typeof exports === 'object') {
module.exports = factory()
} else {
// Browser globals (root is window)
root.RevealMarkdown = factory()
root.RevealMarkdown.initialize()
}
}(this, function () {
var DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$'
var DEFAULT_NOTES_SEPARATOR = 'note:'
var DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\.element\\s*?(.+?)$'
var DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\.slide:\\s*?(\\S.+?)$'
var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__'
/**
* Retrieves the markdown contents of a slide section
* element. Normalizes leading tabs/whitespace.
*/
function getMarkdownFromSlide (section) {
var template = section.querySelector('script')
// strip leading whitespace so it isn't evaluated as code
var text = (template || section).textContent
// restore script end tags
text = text.replace(new RegExp(SCRIPT_END_PLACEHOLDER, 'g'), '</script>')
var leadingWs = text.match(/^\n?(\s*)/)[1].length
var leadingTabs = text.match(/^\n?(\t*)/)[1].length
if (leadingTabs > 0) {
text = text.replace(new RegExp('\\n?\\t{' + leadingTabs + '}', 'g'), '\n')
} else if (leadingWs > 1) {
text = text.replace(new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n')
}
return text
}
/**
* Given a markdown slide section element, this will
* return all arguments that aren't related to markdown
* parsing. Used to forward any other user-defined arguments
* to the output markdown slide.
*/
function getForwardedAttributes (section) {
var attributes = section.attributes
var result = []
for (var i = 0, len = attributes.length; i < len; i++) {
var name = attributes[i].name
var value = attributes[i].value
// disregard attributes that are used for markdown loading/parsing
if (/data-(markdown|separator|vertical|notes)/gi.test(name)) continue
if (value) {
result.push(name + '="' + value + '"')
} else {
result.push(name)
}
}
return result.join(' ')
}
/**
* Inspects the given options and fills out default
* values for what's not defined.
*/
function getSlidifyOptions (options) {
options = options || {}
options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR
options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR
options.attributes = options.attributes || ''
return options
}
/**
* Helper function for constructing a markdown slide.
*/
function createMarkdownSlide (content, options) {
options = getSlidifyOptions(options)
var notesMatch = content.split(new RegExp(options.notesSeparator, 'mgi'))
if (notesMatch.length === 2) {
content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>'
}
// prevent script end tags in the content from interfering
// with parsing
content = content.replace(/<\/script>/g, SCRIPT_END_PLACEHOLDER)
return '<script type="text/template">' + content + '</script>'
}
/**
* Parses a data string into multiple slides based
* on the passed in separator arguments.
*/
function slidify (markdown, options) {
options = getSlidifyOptions(options)
var separatorRegex = new RegExp(options.separator + (options.verticalSeparator ? '|' + options.verticalSeparator : ''), 'mg')
var horizontalSeparatorRegex = new RegExp(options.separator)
var matches
var lastIndex = 0
var isHorizontal
var wasHorizontal = true
var content
var sectionStack = []
// iterate until all blocks between separators are stacked up
while ((matches = separatorRegex.exec(markdown)) !== null) {
// determine direction (horizontal by default)
isHorizontal = horizontalSeparatorRegex.test(matches[0])
if (!isHorizontal && wasHorizontal) {
// create vertical stack
sectionStack.push([])
}
// pluck slide content from markdown input
content = markdown.substring(lastIndex, matches.index)
if (isHorizontal && wasHorizontal) {
// add to horizontal stack
sectionStack.push(content)
} else {
// add to vertical stack
sectionStack[sectionStack.length - 1].push(content)
}
lastIndex = separatorRegex.lastIndex
wasHorizontal = isHorizontal
}
// add the remaining slide
(wasHorizontal ? sectionStack : sectionStack[sectionStack.length - 1]).push(markdown.substring(lastIndex))
var markdownSections = ''
// flatten the hierarchical stack, and insert <section data-markdown> tags
for (var i = 0, len = sectionStack.length; i < len; i++) {
// vertical
if (sectionStack[i] instanceof Array) {
markdownSections += '<section ' + options.attributes + '>'
sectionStack[i].forEach(function (child) {
markdownSections += '<section data-markdown>' + createMarkdownSlide(child, options) + '</section>'
})
markdownSections += '</section>'
} else {
markdownSections += '<section ' + options.attributes + ' data-markdown>' + createMarkdownSlide(sectionStack[i], options) + '</section>'
}
}
return markdownSections
}
/**
* Parses any current data-markdown slides, splits
* multi-slide markdown into separate sections and
* handles loading of external markdown.
*/
function processSlides () {
var sections = document.querySelectorAll('[data-markdown]')
var section
for (var i = 0, len = sections.length; i < len; i++) {
section = sections[i]
if (section.getAttribute('data-markdown').length) {
var xhr = new XMLHttpRequest()
var url = section.getAttribute('data-markdown')
var datacharset = section.getAttribute('data-charset')
// see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
if (datacharset !== null && datacharset !== '') {
xhr.overrideMimeType('text/html; charset=' + datacharset)
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// file protocol yields status code 0 (useful for local debug, mobile applications etc.)
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) {
section.outerHTML = slidify(xhr.responseText, {
separator: section.getAttribute('data-separator'),
verticalSeparator: section.getAttribute('data-separator-vertical'),
notesSeparator: section.getAttribute('data-separator-notes'),
attributes: getForwardedAttributes(section)
})
} else {
section.outerHTML = '<section data-state="alert">' +
'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
'Check your browser\'s JavaScript console for more details.' +
'<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
'</section>'
}
}
}
xhr.open('GET', url, false)
try {
xhr.send()
} catch (e) {
alert('Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e)
}
} else if (section.getAttribute('data-separator') || section.getAttribute('data-separator-vertical') || section.getAttribute('data-separator-notes')) {
section.outerHTML = slidify(getMarkdownFromSlide(section), {
separator: section.getAttribute('data-separator'),
verticalSeparator: section.getAttribute('data-separator-vertical'),
notesSeparator: section.getAttribute('data-separator-notes'),
attributes: getForwardedAttributes(section)
})
} else {
section.innerHTML = createMarkdownSlide(getMarkdownFromSlide(section))
}
}
}
/**
* Check if a node value has the attributes pattern.
* If yes, extract it and add that value as one or several attributes
* the the terget element.
*
* You need Cache Killer on Chrome to see the effect on any FOM transformation
* directly on refresh (F5)
* http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
*/
function addAttributeInElement (node, elementTarget, separator) {
var mardownClassesInElementsRegex = new RegExp(separator, 'mg')
var mardownClassRegex = new RegExp('([^"= ]+?)="([^"=]+?)"', 'mg')
var nodeValue = node.nodeValue
var matches
var matchesClass
if ((matches = mardownClassesInElementsRegex.exec(nodeValue))) {
var classes = matches[1]
nodeValue = nodeValue.substring(0, matches.index) + nodeValue.substring(mardownClassesInElementsRegex.lastIndex)
node.nodeValue = nodeValue
while ((matchesClass = mardownClassRegex.exec(classes))) {
var name = matchesClass[1]
var value = matchesClass[2]
if (name.substr(0, 5) === 'data-' || window.whiteListAttr.indexOf(name) !== -1) { elementTarget.setAttribute(name, window.filterXSS.escapeAttrValue(value)) }
}
return true
}
return false
}
/**
* Add attributes to the parent element of a text node,
* or the element of an attribute node.
*/
function addAttributes (section, element, previousElement, separatorElementAttributes, separatorSectionAttributes) {
if (element != null && element.childNodes !== undefined && element.childNodes.length > 0) {
var previousParentElement = element
for (var i = 0; i < element.childNodes.length; i++) {
var childElement = element.childNodes[i]
if (i > 0) {
let j = i - 1
while (j >= 0) {
var aPreviousChildElement = element.childNodes[j]
if (typeof aPreviousChildElement.setAttribute === 'function' && aPreviousChildElement.tagName !== 'BR') {
previousParentElement = aPreviousChildElement
break
}
j = j - 1
}
}
var parentSection = section
if (childElement.nodeName === 'section') {
parentSection = childElement
previousParentElement = childElement
}
if (typeof childElement.setAttribute === 'function' || childElement.nodeType === Node.COMMENT_NODE) {
addAttributes(parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes)
}
}
}
if (element.nodeType === Node.COMMENT_NODE) {
if (addAttributeInElement(element, previousElement, separatorElementAttributes) === false) {
addAttributeInElement(element, section, separatorSectionAttributes)
}
}
}
/**
* Converts any current data-markdown slides in the
* DOM to HTML.
*/
function convertSlides () {
var sections = document.querySelectorAll('[data-markdown]')
for (var i = 0, len = sections.length; i < len; i++) {
var section = sections[i]
// Only parse the same slide once
if (!section.getAttribute('data-markdown-parsed')) {
section.setAttribute('data-markdown-parsed', true)
var notes = section.querySelector('aside.notes')
var markdown = getMarkdownFromSlide(section)
var rendered = md.render(markdown)
rendered = preventXSS(rendered)
var result = window.postProcess(rendered)
section.innerHTML = result[0].outerHTML
addAttributes(section, section, null, section.getAttribute('data-element-attributes') ||
section.parentNode.getAttribute('data-element-attributes') ||
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
section.getAttribute('data-attributes') ||
section.parentNode.getAttribute('data-attributes') ||
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR)
// If there were notes, we need to re-add them after
// having overwritten the section's HTML
if (notes) {
section.appendChild(notes)
}
}
}
}
// API
return {
initialize: function () {
processSlides()
convertSlides()
},
// TODO: Do these belong in the API?
processSlides: processSlides,
convertSlides: convertSlides,
slidify: slidify
}
}))

View File

@ -1,138 +1,139 @@
require('../css/extra.css');
require('../css/site.css');
/* eslint-env browser, jquery */
/* global serverurl, Reveal */
import { md, updateLastChange, finishView } from './extra';
require('../css/extra.css')
require('../css/site.css')
import { preventXSS } from './render';
import { md, updateLastChange, finishView } from './extra'
const body = $(".slides").text();
const body = $('.slides').text()
createtime = lastchangeui.time.attr('data-createtime');
lastchangetime = lastchangeui.time.attr('data-updatetime');
updateLastChange();
const url = window.location.pathname;
$('.ui-edit').attr('href', `${url}/edit`);
window.createtime = window.lastchangeui.time.attr('data-createtime')
window.lastchangetime = window.lastchangeui.time.attr('data-updatetime')
updateLastChange()
const url = window.location.pathname
$('.ui-edit').attr('href', `${url}/edit`)
$(document).ready(() => {
//tooltip
$('[data-toggle="tooltip"]').tooltip();
});
// tooltip
$('[data-toggle="tooltip"]').tooltip()
})
function extend() {
const target = {};
function extend () {
const target = {}
for (const source of arguments) {
for (const key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
for (const source of arguments) {
for (const key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key]
}
}
}
return target;
return target
}
// Optional libraries used to extend on reveal.js
const deps = [{
src: `${serverurl}/build/reveal.js/lib/js/classList.js`,
condition() {
return !document.body.classList;
}
src: `${serverurl}/build/reveal.js/lib/js/classList.js`,
condition () {
return !document.body.classList
}
}, {
src: `${serverurl}/js/reveal-markdown.js`,
callback() {
const slideOptions = {
separator: '^(\r\n?|\n)---(\r\n?|\n)$',
verticalSeparator: '^(\r\n?|\n)----(\r\n?|\n)$'
};
const slides = RevealMarkdown.slidify(body, slideOptions);
$(".slides").html(slides);
RevealMarkdown.initialize();
$(".slides").show();
src: `${serverurl}/js/reveal-markdown.js`,
callback () {
const slideOptions = {
separator: '^(\r\n?|\n)---(\r\n?|\n)$',
verticalSeparator: '^(\r\n?|\n)----(\r\n?|\n)$'
}
const slides = window.RevealMarkdown.slidify(body, slideOptions)
$('.slides').html(slides)
window.RevealMarkdown.initialize()
$('.slides').show()
}
}, {
src: `${serverurl}/build/reveal.js/plugin/notes/notes.js`,
async: true,
condition() {
return !!document.body.classList;
}
}];
src: `${serverurl}/build/reveal.js/plugin/notes/notes.js`,
async: true,
condition () {
return !!document.body.classList
}
}]
// default options to init reveal.js
const defaultOptions = {
controls: true,
progress: true,
slideNumber: true,
history: true,
center: true,
transition: 'none',
dependencies: deps
};
controls: true,
progress: true,
slideNumber: true,
history: true,
center: true,
transition: 'none',
dependencies: deps
}
// options from yaml meta
const meta = JSON.parse($("#meta").text());
var options = meta.slideOptions || {};
const meta = JSON.parse($('#meta').text())
var options = meta.slideOptions || {}
const view = $('.reveal');
const view = $('.reveal')
//text language
if (meta.lang && typeof meta.lang == "string") {
view.attr('lang', meta.lang);
// text language
if (meta.lang && typeof meta.lang === 'string') {
view.attr('lang', meta.lang)
} else {
view.removeAttr('lang');
view.removeAttr('lang')
}
//text direction
if (meta.dir && typeof meta.dir == "string" && meta.dir == "rtl") {
options.rtl = true;
// text direction
if (meta.dir && typeof meta.dir === 'string' && meta.dir === 'rtl') {
options.rtl = true
} else {
options.rtl = false;
options.rtl = false
}
//breaks
// breaks
if (typeof meta.breaks === 'boolean' && !meta.breaks) {
md.options.breaks = false;
md.options.breaks = false
} else {
md.options.breaks = true;
md.options.breaks = true
}
// options from URL query string
const queryOptions = Reveal.getQueryHash() || {};
const queryOptions = Reveal.getQueryHash() || {}
var options = extend(defaultOptions, options, queryOptions);
Reveal.initialize(options);
options = extend(defaultOptions, options, queryOptions)
Reveal.initialize(options)
window.viewAjaxCallback = () => {
Reveal.layout();
};
Reveal.layout()
}
function renderSlide(event) {
if (window.location.search.match( /print-pdf/gi )) {
const slides = $('.slides');
var title = document.title;
finishView(slides);
document.title = title;
Reveal.layout();
} else {
const markdown = $(event.currentSlide);
if (!markdown.attr('data-rendered')) {
var title = document.title;
finishView(markdown);
markdown.attr('data-rendered', 'true');
document.title = title;
Reveal.layout();
}
function renderSlide (event) {
if (window.location.search.match(/print-pdf/gi)) {
const slides = $('.slides')
let title = document.title
finishView(slides)
document.title = title
Reveal.layout()
} else {
const markdown = $(event.currentSlide)
if (!markdown.attr('data-rendered')) {
let title = document.title
finishView(markdown)
markdown.attr('data-rendered', 'true')
document.title = title
Reveal.layout()
}
}
}
Reveal.addEventListener('ready', event => {
renderSlide(event);
const markdown = $(event.currentSlide);
renderSlide(event)
const markdown = $(event.currentSlide)
// force browser redraw
setTimeout(() => {
markdown.hide().show(0);
}, 0);
});
Reveal.addEventListener('slidechanged', renderSlide);
setTimeout(() => {
markdown.hide().show(0)
}, 0)
})
Reveal.addEventListener('slidechanged', renderSlide)
const isMacLike = navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) ? true : false;
const isMacLike = !!navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i)
if (!isMacLike) $('.container').addClass('hidescrollbar');
if (!isMacLike) $('.container').addClass('hidescrollbar')

View File

@ -1,365 +1,367 @@
/* eslint-env browser, jquery */
/* global _ */
// Inject line numbers for sync scroll.
import markdownitContainer from 'markdown-it-container';
import markdownitContainer from 'markdown-it-container'
import { md } from './extra';
import { md } from './extra'
function addPart(tokens, idx) {
if (tokens[idx].map && tokens[idx].level === 0) {
const startline = tokens[idx].map[0] + 1;
const endline = tokens[idx].map[1];
tokens[idx].attrJoin('class', 'part');
tokens[idx].attrJoin('data-startline', startline);
tokens[idx].attrJoin('data-endline', endline);
}
function addPart (tokens, idx) {
if (tokens[idx].map && tokens[idx].level === 0) {
const startline = tokens[idx].map[0] + 1
const endline = tokens[idx].map[1]
tokens[idx].attrJoin('class', 'part')
tokens[idx].attrJoin('data-startline', startline)
tokens[idx].attrJoin('data-endline', endline)
}
}
md.renderer.rules.blockquote_open = function (tokens, idx, options, env, self) {
tokens[idx].attrJoin('class', 'raw');
addPart(tokens, idx);
return self.renderToken(...arguments);
};
tokens[idx].attrJoin('class', 'raw')
addPart(tokens, idx)
return self.renderToken(...arguments)
}
md.renderer.rules.table_open = function (tokens, idx, options, env, self) {
addPart(tokens, idx);
return self.renderToken(...arguments);
};
addPart(tokens, idx)
return self.renderToken(...arguments)
}
md.renderer.rules.bullet_list_open = function (tokens, idx, options, env, self) {
addPart(tokens, idx);
return self.renderToken(...arguments);
};
addPart(tokens, idx)
return self.renderToken(...arguments)
}
md.renderer.rules.list_item_open = function (tokens, idx, options, env, self) {
tokens[idx].attrJoin('class', 'raw');
if (tokens[idx].map) {
const startline = tokens[idx].map[0] + 1;
const endline = tokens[idx].map[1];
tokens[idx].attrJoin('data-startline', startline);
tokens[idx].attrJoin('data-endline', endline);
}
return self.renderToken(...arguments);
};
tokens[idx].attrJoin('class', 'raw')
if (tokens[idx].map) {
const startline = tokens[idx].map[0] + 1
const endline = tokens[idx].map[1]
tokens[idx].attrJoin('data-startline', startline)
tokens[idx].attrJoin('data-endline', endline)
}
return self.renderToken(...arguments)
}
md.renderer.rules.ordered_list_open = function (tokens, idx, options, env, self) {
addPart(tokens, idx);
return self.renderToken(...arguments);
};
addPart(tokens, idx)
return self.renderToken(...arguments)
}
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
addPart(tokens, idx);
return self.renderToken(...arguments);
};
addPart(tokens, idx)
return self.renderToken(...arguments)
}
md.renderer.rules.paragraph_open = function (tokens, idx, options, env, self) {
addPart(tokens, idx);
return self.renderToken(...arguments);
};
addPart(tokens, idx)
return self.renderToken(...arguments)
}
md.renderer.rules.heading_open = function (tokens, idx, options, env, self) {
tokens[idx].attrJoin('class', 'raw');
addPart(tokens, idx);
return self.renderToken(...arguments);
};
tokens[idx].attrJoin('class', 'raw')
addPart(tokens, idx)
return self.renderToken(...arguments)
}
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
const token = tokens[idx];
const info = token.info ? md.utils.unescapeAll(token.info).trim() : '';
let langName = '';
let highlighted;
const token = tokens[idx]
const info = token.info ? md.utils.unescapeAll(token.info).trim() : ''
let langName = ''
let highlighted
if (info) {
langName = info.split(/\s+/g)[0];
if (/\!$/.test(info)) token.attrJoin('class', 'wrap');
token.attrJoin('class', options.langPrefix + langName.replace(/\=$|\=\d+$|\=\+$|\!$|\=\!/, ''));
token.attrJoin('class', 'hljs');
token.attrJoin('class', 'raw');
}
if (info) {
langName = info.split(/\s+/g)[0]
if (/!$/.test(info)) token.attrJoin('class', 'wrap')
token.attrJoin('class', options.langPrefix + langName.replace(/=$|=\d+$|=\+$|!$|=!/, ''))
token.attrJoin('class', 'hljs')
token.attrJoin('class', 'raw')
}
if (options.highlight) {
highlighted = options.highlight(token.content, langName) || md.utils.escapeHtml(token.content);
} else {
highlighted = md.utils.escapeHtml(token.content);
}
if (options.highlight) {
highlighted = options.highlight(token.content, langName) || md.utils.escapeHtml(token.content)
} else {
highlighted = md.utils.escapeHtml(token.content)
}
if (highlighted.indexOf('<pre') === 0) {
return `${highlighted}\n`;
}
if (highlighted.indexOf('<pre') === 0) {
return `${highlighted}\n`
}
if (tokens[idx].map && tokens[idx].level === 0) {
const startline = tokens[idx].map[0] + 1;
const endline = tokens[idx].map[1];
return `<pre class="part" data-startline="${startline}" data-endline="${endline}"><code${self.renderAttrs(token)}>${highlighted}</code></pre>\n`;
}
if (tokens[idx].map && tokens[idx].level === 0) {
const startline = tokens[idx].map[0] + 1
const endline = tokens[idx].map[1]
return `<pre class="part" data-startline="${startline}" data-endline="${endline}"><code${self.renderAttrs(token)}>${highlighted}</code></pre>\n`
}
return `<pre><code${self.renderAttrs(token)}>${highlighted}</code></pre>\n`;
};
return `<pre><code${self.renderAttrs(token)}>${highlighted}</code></pre>\n`
}
md.renderer.rules.code_block = (tokens, idx, options, env, self) => {
if (tokens[idx].map && tokens[idx].level === 0) {
const startline = tokens[idx].map[0] + 1;
const endline = tokens[idx].map[1];
return `<pre class="part" data-startline="${startline}" data-endline="${endline}"><code>${md.utils.escapeHtml(tokens[idx].content)}</code></pre>\n`;
}
return `<pre><code>${md.utils.escapeHtml(tokens[idx].content)}</code></pre>\n`;
};
function renderContainer(tokens, idx, options, env, self) {
tokens[idx].attrJoin('role', 'alert');
tokens[idx].attrJoin('class', 'alert');
tokens[idx].attrJoin('class', `alert-${tokens[idx].info.trim()}`);
addPart(tokens, idx);
return self.renderToken(...arguments);
if (tokens[idx].map && tokens[idx].level === 0) {
const startline = tokens[idx].map[0] + 1
const endline = tokens[idx].map[1]
return `<pre class="part" data-startline="${startline}" data-endline="${endline}"><code>${md.utils.escapeHtml(tokens[idx].content)}</code></pre>\n`
}
return `<pre><code>${md.utils.escapeHtml(tokens[idx].content)}</code></pre>\n`
}
function renderContainer (tokens, idx, options, env, self) {
tokens[idx].attrJoin('role', 'alert')
tokens[idx].attrJoin('class', 'alert')
tokens[idx].attrJoin('class', `alert-${tokens[idx].info.trim()}`)
addPart(tokens, idx)
return self.renderToken(...arguments)
}
md.use(markdownitContainer, 'success', { render: renderContainer });
md.use(markdownitContainer, 'info', { render: renderContainer });
md.use(markdownitContainer, 'warning', { render: renderContainer });
md.use(markdownitContainer, 'danger', { render: renderContainer });
md.use(markdownitContainer, 'success', { render: renderContainer })
md.use(markdownitContainer, 'info', { render: renderContainer })
md.use(markdownitContainer, 'warning', { render: renderContainer })
md.use(markdownitContainer, 'danger', { render: renderContainer })
// FIXME: expose syncscroll to window
window.syncscroll = true;
window.syncscroll = true
window.preventSyncScrollToEdit = false;
window.preventSyncScrollToView = false;
window.preventSyncScrollToEdit = false
window.preventSyncScrollToView = false
const editScrollThrottle = 5;
const viewScrollThrottle = 5;
const buildMapThrottle = 100;
const editScrollThrottle = 5
const viewScrollThrottle = 5
const buildMapThrottle = 100
let viewScrolling = false;
let editScrolling = false;
let viewScrolling = false
let editScrolling = false
let editArea = null;
let viewArea = null;
let markdownArea = null;
let editArea = null
let viewArea = null
let markdownArea = null
export function setupSyncAreas(edit, view, markdown) {
editArea = edit;
viewArea = view;
markdownArea = markdown;
editArea.on('scroll', _.throttle(syncScrollToView, editScrollThrottle));
viewArea.on('scroll', _.throttle(syncScrollToEdit, viewScrollThrottle));
export function setupSyncAreas (edit, view, markdown) {
editArea = edit
viewArea = view
markdownArea = markdown
editArea.on('scroll', _.throttle(syncScrollToView, editScrollThrottle))
viewArea.on('scroll', _.throttle(syncScrollToEdit, viewScrollThrottle))
}
let scrollMap, lineHeightMap, viewTop, viewBottom;
let scrollMap, lineHeightMap, viewTop, viewBottom
export function clearMap() {
scrollMap = null;
lineHeightMap = null;
viewTop = null;
viewBottom = null;
export function clearMap () {
scrollMap = null
lineHeightMap = null
viewTop = null
viewBottom = null
}
window.viewAjaxCallback = clearMap;
window.viewAjaxCallback = clearMap
const buildMap = _.throttle(buildMapInner, buildMapThrottle);
const buildMap = _.throttle(buildMapInner, buildMapThrottle)
// Build offsets for each line (lines can be wrapped)
// That's a bit dirty to process each line everytime, but ok for demo.
// Optimizations are required only for big texts.
function buildMapInner(callback) {
if (!viewArea || !markdownArea) return;
let i, offset, nonEmptyList, pos, a, b, _lineHeightMap, linesCount, acc, _scrollMap;
function buildMapInner (callback) {
if (!viewArea || !markdownArea) return
let i, offset, nonEmptyList, pos, a, b, _lineHeightMap, linesCount, acc, _scrollMap
offset = viewArea.scrollTop() - viewArea.offset().top;
_scrollMap = [];
nonEmptyList = [];
_lineHeightMap = [];
viewTop = 0;
viewBottom = viewArea[0].scrollHeight - viewArea.height();
offset = viewArea.scrollTop() - viewArea.offset().top
_scrollMap = []
nonEmptyList = []
_lineHeightMap = []
viewTop = 0
viewBottom = viewArea[0].scrollHeight - viewArea.height()
acc = 0;
const lines = editor.getValue().split('\n');
const lineHeight = editor.defaultTextHeight();
for (i = 0; i < lines.length; i++) {
const str = lines[i];
acc = 0
const lines = window.editor.getValue().split('\n')
const lineHeight = window.editor.defaultTextHeight()
for (i = 0; i < lines.length; i++) {
const str = lines[i]
_lineHeightMap.push(acc);
_lineHeightMap.push(acc)
if (str.length === 0) {
acc++;
continue;
}
const h = editor.heightAtLine(i + 1) - editor.heightAtLine(i);
acc += Math.round(h / lineHeight);
}
_lineHeightMap.push(acc);
linesCount = acc;
for (i = 0; i < linesCount; i++) {
_scrollMap.push(-1);
if (str.length === 0) {
acc++
continue
}
nonEmptyList.push(0);
const h = window.editor.heightAtLine(i + 1) - window.editor.heightAtLine(i)
acc += Math.round(h / lineHeight)
}
_lineHeightMap.push(acc)
linesCount = acc
for (i = 0; i < linesCount; i++) {
_scrollMap.push(-1)
}
nonEmptyList.push(0)
// make the first line go top
_scrollMap[0] = viewTop;
_scrollMap[0] = viewTop
const parts = markdownArea.find('.part').toArray();
for (i = 0; i < parts.length; i++) {
const $el = $(parts[i]);
let t = $el.attr('data-startline') - 1;
if (t === '') {
return;
}
t = _lineHeightMap[t];
if (t !== 0 && t !== nonEmptyList[nonEmptyList.length - 1]) {
nonEmptyList.push(t);
}
_scrollMap[t] = Math.round($el.offset().top + offset - 10);
const parts = markdownArea.find('.part').toArray()
for (i = 0; i < parts.length; i++) {
const $el = $(parts[i])
let t = $el.attr('data-startline') - 1
if (t === '') {
return
}
t = _lineHeightMap[t]
if (t !== 0 && t !== nonEmptyList[nonEmptyList.length - 1]) {
nonEmptyList.push(t)
}
_scrollMap[t] = Math.round($el.offset().top + offset - 10)
}
nonEmptyList.push(linesCount)
_scrollMap[linesCount] = viewArea[0].scrollHeight
pos = 0
for (i = 1; i < linesCount; i++) {
if (_scrollMap[i] !== -1) {
pos++
continue
}
nonEmptyList.push(linesCount);
_scrollMap[linesCount] = viewArea[0].scrollHeight;
a = nonEmptyList[pos]
b = nonEmptyList[pos + 1]
_scrollMap[i] = Math.round((_scrollMap[b] * (i - a) + _scrollMap[a] * (b - i)) / (b - a))
}
pos = 0;
for (i = 1; i < linesCount; i++) {
if (_scrollMap[i] !== -1) {
pos++;
continue;
}
_scrollMap[0] = 0
a = nonEmptyList[pos];
b = nonEmptyList[pos + 1];
_scrollMap[i] = Math.round((_scrollMap[b] * (i - a) + _scrollMap[a] * (b - i)) / (b - a));
}
scrollMap = _scrollMap
lineHeightMap = _lineHeightMap
_scrollMap[0] = 0;
scrollMap = _scrollMap;
lineHeightMap = _lineHeightMap;
if (loaded && callback) callback();
if (window.loaded && callback) callback()
}
// sync view scroll progress to edit
let viewScrollingTimer = null;
let viewScrollingTimer = null
export function syncScrollToEdit(event, preventAnimate) {
if (currentMode != modeType.both || !syncscroll || !editArea) return;
if (preventSyncScrollToEdit) {
if (typeof preventSyncScrollToEdit === 'number') {
preventSyncScrollToEdit--;
} else {
preventSyncScrollToEdit = false;
}
return;
}
if (!scrollMap || !lineHeightMap) {
buildMap(() => {
syncScrollToEdit(event, preventAnimate);
});
return;
}
if (editScrolling) return;
const scrollTop = viewArea[0].scrollTop;
let lineIndex = 0;
for (var i = 0, l = scrollMap.length; i < l; i++) {
if (scrollMap[i] > scrollTop) {
break;
} else {
lineIndex = i;
}
}
let lineNo = 0;
let lineDiff = 0;
for (var i = 0, l = lineHeightMap.length; i < l; i++) {
if (lineHeightMap[i] > lineIndex) {
break;
} else {
lineNo = lineHeightMap[i];
lineDiff = lineHeightMap[i + 1] - lineNo;
}
}
let posTo = 0;
let topDiffPercent = 0;
let posToNextDiff = 0;
const scrollInfo = editor.getScrollInfo();
const textHeight = editor.defaultTextHeight();
const preLastLineHeight = scrollInfo.height - scrollInfo.clientHeight - textHeight;
const preLastLineNo = Math.round(preLastLineHeight / textHeight);
const preLastLinePos = scrollMap[preLastLineNo];
if (scrollInfo.height > scrollInfo.clientHeight && scrollTop >= preLastLinePos) {
posTo = preLastLineHeight;
topDiffPercent = (scrollTop - preLastLinePos) / (viewBottom - preLastLinePos);
posToNextDiff = textHeight * topDiffPercent;
posTo += Math.ceil(posToNextDiff);
export function syncScrollToEdit (event, preventAnimate) {
if (window.currentMode !== window.modeType.both || !window.syncscroll || !editArea) return
if (window.preventSyncScrollToEdit) {
if (typeof window.preventSyncScrollToEdit === 'number') {
window.preventSyncScrollToEdit--
} else {
posTo = lineNo * textHeight;
topDiffPercent = (scrollTop - scrollMap[lineNo]) / (scrollMap[lineNo + lineDiff] - scrollMap[lineNo]);
posToNextDiff = textHeight * lineDiff * topDiffPercent;
posTo += Math.ceil(posToNextDiff);
window.preventSyncScrollToEdit = false
}
return
}
if (!scrollMap || !lineHeightMap) {
buildMap(() => {
syncScrollToEdit(event, preventAnimate)
})
return
}
if (editScrolling) return
if (preventAnimate) {
editArea.scrollTop(posTo);
const scrollTop = viewArea[0].scrollTop
let lineIndex = 0
for (let i = 0, l = scrollMap.length; i < l; i++) {
if (scrollMap[i] > scrollTop) {
break
} else {
const posDiff = Math.abs(scrollInfo.top - posTo);
var duration = posDiff / 50;
duration = duration >= 100 ? duration : 100;
editArea.stop(true, true).animate({
scrollTop: posTo
}, duration, "linear");
lineIndex = i
}
}
let lineNo = 0
let lineDiff = 0
for (let i = 0, l = lineHeightMap.length; i < l; i++) {
if (lineHeightMap[i] > lineIndex) {
break
} else {
lineNo = lineHeightMap[i]
lineDiff = lineHeightMap[i + 1] - lineNo
}
}
viewScrolling = true;
clearTimeout(viewScrollingTimer);
viewScrollingTimer = setTimeout(viewScrollingTimeoutInner, duration * 1.5);
let posTo = 0
let topDiffPercent = 0
let posToNextDiff = 0
const scrollInfo = window.editor.getScrollInfo()
const textHeight = window.editor.defaultTextHeight()
const preLastLineHeight = scrollInfo.height - scrollInfo.clientHeight - textHeight
const preLastLineNo = Math.round(preLastLineHeight / textHeight)
const preLastLinePos = scrollMap[preLastLineNo]
if (scrollInfo.height > scrollInfo.clientHeight && scrollTop >= preLastLinePos) {
posTo = preLastLineHeight
topDiffPercent = (scrollTop - preLastLinePos) / (viewBottom - preLastLinePos)
posToNextDiff = textHeight * topDiffPercent
posTo += Math.ceil(posToNextDiff)
} else {
posTo = lineNo * textHeight
topDiffPercent = (scrollTop - scrollMap[lineNo]) / (scrollMap[lineNo + lineDiff] - scrollMap[lineNo])
posToNextDiff = textHeight * lineDiff * topDiffPercent
posTo += Math.ceil(posToNextDiff)
}
if (preventAnimate) {
editArea.scrollTop(posTo)
} else {
const posDiff = Math.abs(scrollInfo.top - posTo)
var duration = posDiff / 50
duration = duration >= 100 ? duration : 100
editArea.stop(true, true).animate({
scrollTop: posTo
}, duration, 'linear')
}
viewScrolling = true
clearTimeout(viewScrollingTimer)
viewScrollingTimer = setTimeout(viewScrollingTimeoutInner, duration * 1.5)
}
function viewScrollingTimeoutInner() {
viewScrolling = false;
function viewScrollingTimeoutInner () {
viewScrolling = false
}
// sync edit scroll progress to view
let editScrollingTimer = null;
let editScrollingTimer = null
export function syncScrollToView(event, preventAnimate) {
if (currentMode != modeType.both || !syncscroll || !viewArea) return;
if (preventSyncScrollToView) {
if (typeof preventSyncScrollToView === 'number') {
preventSyncScrollToView--;
} else {
preventSyncScrollToView = false;
}
return;
export function syncScrollToView (event, preventAnimate) {
if (window.currentMode !== window.modeType.both || !window.syncscroll || !viewArea) return
if (window.preventSyncScrollToView) {
if (typeof preventSyncScrollToView === 'number') {
window.preventSyncScrollToView--
} else {
window.preventSyncScrollToView = false
}
if (!scrollMap || !lineHeightMap) {
buildMap(() => {
syncScrollToView(event, preventAnimate);
});
return;
}
if (viewScrolling) return;
return
}
if (!scrollMap || !lineHeightMap) {
buildMap(() => {
syncScrollToView(event, preventAnimate)
})
return
}
if (viewScrolling) return
let lineNo, posTo;
let topDiffPercent, posToNextDiff;
const scrollInfo = editor.getScrollInfo();
const textHeight = editor.defaultTextHeight();
lineNo = Math.floor(scrollInfo.top / textHeight);
let lineNo, posTo
let topDiffPercent, posToNextDiff
const scrollInfo = window.editor.getScrollInfo()
const textHeight = window.editor.defaultTextHeight()
lineNo = Math.floor(scrollInfo.top / textHeight)
// if reach the last line, will start lerp to the bottom
const diffToBottom = (scrollInfo.top + scrollInfo.clientHeight) - (scrollInfo.height - textHeight);
if (scrollInfo.height > scrollInfo.clientHeight && diffToBottom > 0) {
topDiffPercent = diffToBottom / textHeight;
posTo = scrollMap[lineNo + 1];
posToNextDiff = (viewBottom - posTo) * topDiffPercent;
posTo += Math.floor(posToNextDiff);
} else {
topDiffPercent = (scrollInfo.top % textHeight) / textHeight;
posTo = scrollMap[lineNo];
posToNextDiff = (scrollMap[lineNo + 1] - posTo) * topDiffPercent;
posTo += Math.floor(posToNextDiff);
}
const diffToBottom = (scrollInfo.top + scrollInfo.clientHeight) - (scrollInfo.height - textHeight)
if (scrollInfo.height > scrollInfo.clientHeight && diffToBottom > 0) {
topDiffPercent = diffToBottom / textHeight
posTo = scrollMap[lineNo + 1]
posToNextDiff = (viewBottom - posTo) * topDiffPercent
posTo += Math.floor(posToNextDiff)
} else {
topDiffPercent = (scrollInfo.top % textHeight) / textHeight
posTo = scrollMap[lineNo]
posToNextDiff = (scrollMap[lineNo + 1] - posTo) * topDiffPercent
posTo += Math.floor(posToNextDiff)
}
if (preventAnimate) {
viewArea.scrollTop(posTo);
} else {
const posDiff = Math.abs(viewArea.scrollTop() - posTo);
var duration = posDiff / 50;
duration = duration >= 100 ? duration : 100;
viewArea.stop(true, true).animate({
scrollTop: posTo
}, duration, "linear");
}
if (preventAnimate) {
viewArea.scrollTop(posTo)
} else {
const posDiff = Math.abs(viewArea.scrollTop() - posTo)
var duration = posDiff / 50
duration = duration >= 100 ? duration : 100
viewArea.stop(true, true).animate({
scrollTop: posTo
}, duration, 'linear')
}
editScrolling = true;
clearTimeout(editScrollingTimer);
editScrollingTimer = setTimeout(editScrollingTimeoutInner, duration * 1.5);
editScrolling = true
clearTimeout(editScrollingTimer)
editScrollingTimer = setTimeout(editScrollingTimeoutInner, duration * 1.5)
}
function editScrollingTimeoutInner() {
editScrolling = false;
function editScrollingTimeoutInner () {
editScrolling = false
}

View File

@ -1,129 +1,123 @@
/* eslint-env browser, jquery */
/**
* md-toc.js v1.0.2
* https://github.com/yijian166/md-toc.js
*/
(function (window) {
function Toc(id, options) {
this.el = document.getElementById(id);
if (!this.el) return;
this.options = options || {};
this.tocLevel = parseInt(options.level) || 0;
this.tocClass = options['class'] || 'toc';
this.ulClass = options['ulClass'];
this.tocTop = parseInt(options.top) || 0;
this.elChilds = this.el.children;
this.process = options['process'];
if (!this.elChilds.length) return;
this._init();
function Toc (id, options) {
this.el = document.getElementById(id)
if (!this.el) return
this.options = options || {}
this.tocLevel = parseInt(options.level) || 0
this.tocClass = options['class'] || 'toc'
this.ulClass = options['ulClass']
this.tocTop = parseInt(options.top) || 0
this.elChilds = this.el.children
this.process = options['process']
if (!this.elChilds.length) return
this._init()
}
Toc.prototype._init = function () {
this._collectTitleElements()
this._createTocContent()
this._showToc()
}
Toc.prototype._collectTitleElements = function () {
this._elTitlesNames = []
this.elTitleElements = []
for (var i = 1; i < 7; i++) {
if (this.el.getElementsByTagName('h' + i).length) {
this._elTitlesNames.push('h' + i)
}
}
Toc.prototype._init = function () {
this._collectTitleElements();
this._createTocContent();
this._showToc();
};
this._elTitlesNames.length = this._elTitlesNames.length > this.tocLevel ? this.tocLevel : this._elTitlesNames.length
Toc.prototype._collectTitleElements = function () {
this._elTitlesNames = [],
this.elTitleElements = [];
for (var i = 1; i < 7; i++) {
if (this.el.getElementsByTagName('h' + i).length) {
this._elTitlesNames.push('h' + i);
for (var j = 0; j < this.elChilds.length; j++) {
this._elChildName = this.elChilds[j].tagName.toLowerCase()
if (this._elTitlesNames.toString().match(this._elChildName)) {
this.elTitleElements.push(this.elChilds[j])
}
}
}
Toc.prototype._createTocContent = function () {
this._elTitleElementsLen = this.elTitleElements.length
if (!this._elTitleElementsLen) return
this.tocContent = ''
this._tempLists = []
for (var i = 0; i < this._elTitleElementsLen; i++) {
var j = i + 1
this._elTitleElement = this.elTitleElements[i]
this._elTitleElementName = this._elTitleElement.tagName
this._elTitleElementText = (typeof this.process === 'function' ? this.process(this._elTitleElement) : this._elTitleElement.innerHTML).replace(/<(?:.|\n)*?>/gm, '')
var id = this._elTitleElement.getAttribute('id')
if (!id) {
this._elTitleElement.setAttribute('id', 'tip' + i)
id = '#tip' + i
} else {
id = '#' + id
}
this.tocContent += '<li><a href="' + id + '">' + this._elTitleElementText + '</a>'
if (j !== this._elTitleElementsLen) {
this._elNextTitleElementName = this.elTitleElements[j].tagName
if (this._elTitleElementName !== this._elNextTitleElementName) {
var checkColse = false
var y = 1
for (var t = this._tempLists.length - 1; t >= 0; t--) {
if (this._tempLists[t].tagName === this._elNextTitleElementName) {
checkColse = true
break
}
}
this._elTitlesNames.length = this._elTitlesNames.length > this.tocLevel ? this.tocLevel : this._elTitlesNames.length;
for (var j = 0; j < this.elChilds.length; j++) {
this._elChildName = this.elChilds[j].tagName.toLowerCase();
if (this._elTitlesNames.toString().match(this._elChildName)) {
this.elTitleElements.push(this.elChilds[j]);
}
}
};
Toc.prototype._createTocContent = function () {
this._elTitleElementsLen = this.elTitleElements.length;
if (!this._elTitleElementsLen) return;
this.tocContent = '';
this._tempLists = [];
var url = location.origin + location.pathname;
for (var i = 0; i < this._elTitleElementsLen; i++) {
var j = i + 1;
this._elTitleElement = this.elTitleElements[i];
this._elTitleElementName = this._elTitleElement.tagName;
this._elTitleElementText = (typeof this.process === 'function' ? this.process(this._elTitleElement) : this._elTitleElement.innerHTML).replace(/<(?:.|\n)*?>/gm, '');
var id = this._elTitleElement.getAttribute('id');
if (!id) {
this._elTitleElement.setAttribute('id', 'tip' + i);
id = '#tip' + i;
} else {
id = '#' + id;
}
this.tocContent += '<li><a href="' + id + '">' + this._elTitleElementText + '</a>';
if (j != this._elTitleElementsLen) {
this._elNextTitleElementName = this.elTitleElements[j].tagName;
if (this._elTitleElementName != this._elNextTitleElementName) {
var checkColse = false,
y = 1;
for (var t = this._tempLists.length - 1; t >= 0; t--) {
if (this._tempLists[t].tagName == this._elNextTitleElementName) {
checkColse = true;
break;
}
y++;
}
if (checkColse) {
this.tocContent += new Array(y + 1).join('</li></ul>');
this._tempLists.length = this._tempLists.length - y;
} else {
this._tempLists.push(this._elTitleElement);
if (this.ulClass)
this.tocContent += '<ul class="' + this.ulClass + '">';
else
this.tocContent += '<ul>';
}
} else {
this.tocContent += '</li>';
}
} else {
if (this._tempLists.length) {
this.tocContent += new Array(this._tempLists.length + 1).join('</li></ul>');
} else {
this.tocContent += '</li>';
}
}
}
if (this.ulClass)
this.tocContent = '<ul class="' + this.ulClass + '">' + this.tocContent + '</ul>';
else
this.tocContent = '<ul>' + this.tocContent + '</ul>';
};
Toc.prototype._showToc = function () {
this.toc = document.createElement('div');
this.toc.innerHTML = this.tocContent;
this.toc.setAttribute('class', this.tocClass);
if (!this.options.targetId) {
this.el.appendChild(this.toc);
y++
}
if (checkColse) {
this.tocContent += new Array(y + 1).join('</li></ul>')
this._tempLists.length = this._tempLists.length - y
} else {
this._tempLists.push(this._elTitleElement)
if (this.ulClass) { this.tocContent += '<ul class="' + this.ulClass + '">' } else { this.tocContent += '<ul>' }
}
} else {
document.getElementById(this.options.targetId).appendChild(this.toc);
this.tocContent += '</li>'
}
var self = this;
if (this.tocTop > -1) {
window.onscroll = function () {
var t = document.documentElement.scrollTop || document.body.scrollTop;
if (t < self.tocTop) {
self.toc.setAttribute('style', 'position:absolute;top:' + self.tocTop + 'px;');
} else {
self.toc.setAttribute('style', 'position:fixed;top:10px;');
}
}
} else {
if (this._tempLists.length) {
this.tocContent += new Array(this._tempLists.length + 1).join('</li></ul>')
} else {
this.tocContent += '</li>'
}
};
window.Toc = Toc;
})(window);
}
}
if (this.ulClass) { this.tocContent = '<ul class="' + this.ulClass + '">' + this.tocContent + '</ul>' } else { this.tocContent = '<ul>' + this.tocContent + '</ul>' }
}
Toc.prototype._showToc = function () {
this.toc = document.createElement('div')
this.toc.innerHTML = this.tocContent
this.toc.setAttribute('class', this.tocClass)
if (!this.options.targetId) {
this.el.appendChild(this.toc)
} else {
document.getElementById(this.options.targetId).appendChild(this.toc)
}
var self = this
if (this.tocTop > -1) {
window.onscroll = function () {
var t = document.documentElement.scrollTop || document.body.scrollTop
if (t < self.tocTop) {
self.toc.setAttribute('style', 'position:absolute;top:' + self.tocTop + 'px;')
} else {
self.toc.setAttribute('style', 'position:fixed;top:10px;')
}
}
}
}
window.Toc = Toc
})(window)

View File

@ -1,33 +1,33 @@
var baseConfig = require('./webpackBaseConfig');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require('path');
var baseConfig = require('./webpackBaseConfig')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var path = require('path')
module.exports = [Object.assign({}, baseConfig, {
plugins: baseConfig.plugins.concat([
new ExtractTextPlugin("[name].css")
])
plugins: baseConfig.plugins.concat([
new ExtractTextPlugin('[name].css')
])
}), {
entry: {
htmlExport: path.join(__dirname, 'public/js/htmlExport.js')
},
module: {
loaders: [{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'sass-loader')
}, {
test: /\.less$/,
loader: ExtractTextPlugin.extract('style-loader', 'less-loader')
}]
},
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[name].js'
},
plugins: [
new ExtractTextPlugin("html.min.css")
]
}];
entry: {
htmlExport: path.join(__dirname, 'public/js/htmlExport.js')
},
module: {
loaders: [{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'sass-loader')
}, {
test: /\.less$/,
loader: ExtractTextPlugin.extract('style-loader', 'less-loader')
}]
},
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[name].js'
},
plugins: [
new ExtractTextPlugin('html.min.css')
]
}]

View File

@ -1,63 +1,63 @@
var baseConfig = require('./webpackBaseConfig');
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
var ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
var baseConfig = require('./webpackBaseConfig')
var webpack = require('webpack')
var path = require('path')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
var ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin')
module.exports = [Object.assign({}, baseConfig, {
plugins: baseConfig.plugins.concat([
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new ParallelUglifyPlugin({
uglifyJS: {
compress: {
warnings: false
},
mangle: false,
sourceMap: false
}
}),
new ExtractTextPlugin("[name].[hash].css")
]),
plugins: baseConfig.plugins.concat([
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new ParallelUglifyPlugin({
uglifyJS: {
compress: {
warnings: false
},
mangle: false,
sourceMap: false
}
}),
new ExtractTextPlugin('[name].[hash].css')
]),
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[id].[name].[hash].js',
baseUrl: '<%- url %>'
}
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[id].[name].[hash].js',
baseUrl: '<%- url %>'
}
}), {
entry: {
htmlExport: path.join(__dirname, 'public/js/htmlExport.js')
},
module: {
loaders: [{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'sass-loader')
}, {
test: /\.less$/,
loader: ExtractTextPlugin.extract('style-loader', 'less-loader')
}]
},
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[name].js'
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new ExtractTextPlugin("html.min.css"),
new OptimizeCssAssetsPlugin()
]
}];
entry: {
htmlExport: path.join(__dirname, 'public/js/htmlExport.js')
},
module: {
loaders: [{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'sass-loader')
}, {
test: /\.less$/,
loader: ExtractTextPlugin.extract('style-loader', 'less-loader')
}]
},
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[name].js'
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new ExtractTextPlugin('html.min.css'),
new OptimizeCssAssetsPlugin()
]
}]

View File

@ -1,423 +1,423 @@
var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var webpack = require('webpack')
var path = require('path')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
plugins: [
new webpack.ProvidePlugin({
Visibility: "visibilityjs",
Cookies: "js-cookie",
key: "keymaster",
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"moment": "moment",
"Handlebars": "handlebars"
}),
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.optimize.CommonsChunkPlugin({
names: ["cover", "index", "pretty", "slide", "vendor"],
children: true,
async: true,
filename: '[name].js',
minChunks: Infinity
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font', 'index-styles', 'index'],
filename: path.join(__dirname, 'public/views/build/index-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font-pack', 'index-styles-pack', 'index-styles', 'index'],
filename: path.join(__dirname, 'public/views/build/index-pack-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['index'],
filename: path.join(__dirname, 'public/views/build/index-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['common', 'index-pack'],
filename: path.join(__dirname, 'public/views/build/index-pack-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font', 'cover'],
filename: path.join(__dirname, 'public/views/build/cover-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font-pack', 'cover-styles-pack', 'cover'],
filename: path.join(__dirname, 'public/views/build/cover-pack-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['cover'],
filename: path.join(__dirname, 'public/views/build/cover-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['common', 'cover-pack'],
filename: path.join(__dirname, 'public/views/build/cover-pack-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font', 'pretty-styles', 'pretty'],
filename: path.join(__dirname, 'public/views/build/pretty-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font-pack', 'pretty-styles-pack', 'pretty-styles', 'pretty'],
filename: path.join(__dirname, 'public/views/build/pretty-pack-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['pretty'],
filename: path.join(__dirname, 'public/views/build/pretty-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['common', 'pretty-pack'],
filename: path.join(__dirname, 'public/views/build/pretty-pack-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font', 'slide-styles', 'slide'],
filename: path.join(__dirname, 'public/views/build/slide-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font-pack', 'slide-styles-pack', 'slide-styles', 'slide'],
filename: path.join(__dirname, 'public/views/build/slide-pack-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['slide'],
filename: path.join(__dirname, 'public/views/build/slide-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['slide-pack'],
filename: path.join(__dirname, 'public/views/build/slide-pack-scripts.ejs'),
inject: false
}),
new CopyWebpackPlugin([
{
context: path.join(__dirname, 'node_modules/mathjax'),
from: {
glob: '**/*',
dot: false
},
to: 'MathJax/'
},
{
context: path.join(__dirname, 'node_modules/emojify.js'),
from: {
glob: '**/*',
dot: false
},
to: 'emojify.js/'
},
{
context: path.join(__dirname, 'node_modules/reveal.js'),
from: {
glob: '**/*',
dot: false
},
to: 'reveal.js/'
}
])
plugins: [
new webpack.ProvidePlugin({
Visibility: 'visibilityjs',
Cookies: 'js-cookie',
key: 'keymaster',
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'moment': 'moment',
'Handlebars': 'handlebars'
}),
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.optimize.CommonsChunkPlugin({
names: ['cover', 'index', 'pretty', 'slide', 'vendor'],
children: true,
async: true,
filename: '[name].js',
minChunks: Infinity
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font', 'index-styles', 'index'],
filename: path.join(__dirname, 'public/views/build/index-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font-pack', 'index-styles-pack', 'index-styles', 'index'],
filename: path.join(__dirname, 'public/views/build/index-pack-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['index'],
filename: path.join(__dirname, 'public/views/build/index-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['common', 'index-pack'],
filename: path.join(__dirname, 'public/views/build/index-pack-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font', 'cover'],
filename: path.join(__dirname, 'public/views/build/cover-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font-pack', 'cover-styles-pack', 'cover'],
filename: path.join(__dirname, 'public/views/build/cover-pack-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['cover'],
filename: path.join(__dirname, 'public/views/build/cover-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['common', 'cover-pack'],
filename: path.join(__dirname, 'public/views/build/cover-pack-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font', 'pretty-styles', 'pretty'],
filename: path.join(__dirname, 'public/views/build/pretty-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font-pack', 'pretty-styles-pack', 'pretty-styles', 'pretty'],
filename: path.join(__dirname, 'public/views/build/pretty-pack-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['pretty'],
filename: path.join(__dirname, 'public/views/build/pretty-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['common', 'pretty-pack'],
filename: path.join(__dirname, 'public/views/build/pretty-pack-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font', 'slide-styles', 'slide'],
filename: path.join(__dirname, 'public/views/build/slide-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/header.ejs',
chunks: ['font-pack', 'slide-styles-pack', 'slide-styles', 'slide'],
filename: path.join(__dirname, 'public/views/build/slide-pack-header.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['slide'],
filename: path.join(__dirname, 'public/views/build/slide-scripts.ejs'),
inject: false
}),
new HtmlWebpackPlugin({
template: 'public/views/includes/scripts.ejs',
chunks: ['slide-pack'],
filename: path.join(__dirname, 'public/views/build/slide-pack-scripts.ejs'),
inject: false
}),
new CopyWebpackPlugin([
{
context: path.join(__dirname, 'node_modules/mathjax'),
from: {
glob: '**/*',
dot: false
},
to: 'MathJax/'
},
{
context: path.join(__dirname, 'node_modules/emojify.js'),
from: {
glob: '**/*',
dot: false
},
to: 'emojify.js/'
},
{
context: path.join(__dirname, 'node_modules/reveal.js'),
from: {
glob: '**/*',
dot: false
},
to: 'reveal.js/'
}
])
],
entry: {
font: path.join(__dirname, 'public/css/google-font.css'),
'font-pack': path.join(__dirname, 'public/css/font.css'),
common: [
'expose?jQuery!expose?$!jquery',
'velocity-animate',
'imports?$=jquery!jquery-mousewheel',
'bootstrap'
],
cover: [
'babel-polyfill',
path.join(__dirname, 'public/js/cover.js')
],
'cover-styles-pack': [
path.join(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.min.css'),
path.join(__dirname, 'node_modules/font-awesome/css/font-awesome.min.css'),
path.join(__dirname, 'public/css/bootstrap-social.css'),
path.join(__dirname, 'node_modules/select2/select2.css'),
path.join(__dirname, 'node_modules/select2/select2-bootstrap.css')
],
'cover-pack': [
'babel-polyfill',
'bootstrap-validator',
'script!listPagnation',
'expose?select2!select2',
'expose?moment!moment',
'script!js-url',
path.join(__dirname, 'public/js/cover.js')
],
index: [
'babel-polyfill',
'script!jquery-ui-resizable',
'script!js-url',
'expose?filterXSS!xss',
'script!Idle.Js',
'expose?LZString!lz-string',
'script!codemirror',
'script!inlineAttachment',
'script!jqueryTextcomplete',
'script!codemirrorSpellChecker',
'script!codemirrorInlineAttachment',
'script!ot',
'flowchart.js',
'js-sequence-diagrams',
'expose?RevealMarkdown!reveal-markdown',
path.join(__dirname, 'public/js/google-drive-upload.js'),
path.join(__dirname, 'public/js/google-drive-picker.js'),
path.join(__dirname, 'public/js/index.js')
],
'index-styles': [
path.join(__dirname, 'public/vendor/jquery-ui/jquery-ui.min.css'),
path.join(__dirname, 'public/vendor/codemirror-spell-checker/spell-checker.min.css'),
path.join(__dirname, 'node_modules/codemirror/lib/codemirror.css'),
path.join(__dirname, 'node_modules/codemirror/addon/fold/foldgutter.css'),
path.join(__dirname, 'node_modules/codemirror/addon/display/fullscreen.css'),
path.join(__dirname, 'node_modules/codemirror/addon/dialog/dialog.css'),
path.join(__dirname, 'node_modules/codemirror/addon/scroll/simplescrollbars.css'),
path.join(__dirname, 'node_modules/codemirror/addon/search/matchesonscrollbar.css'),
path.join(__dirname, 'node_modules/codemirror/theme/monokai.css'),
path.join(__dirname, 'node_modules/codemirror/theme/one-dark.css'),
path.join(__dirname, 'node_modules/codemirror/mode/tiddlywiki/tiddlywiki.css'),
path.join(__dirname, 'node_modules/codemirror/mode/mediawiki/mediawiki.css'),
path.join(__dirname, 'public/css/github-extract.css'),
path.join(__dirname, 'public/vendor/showup/showup.css'),
path.join(__dirname, 'public/css/mermaid.css'),
path.join(__dirname, 'public/css/markdown.css'),
path.join(__dirname, 'public/css/slide-preview.css')
],
'index-styles-pack': [
path.join(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.min.css'),
path.join(__dirname, 'node_modules/font-awesome/css/font-awesome.min.css'),
path.join(__dirname, 'public/css/bootstrap-social.css'),
path.join(__dirname, 'node_modules/ionicons/css/ionicons.min.css'),
path.join(__dirname, 'node_modules/octicons/octicons/octicons.css')
],
'index-pack': [
'babel-polyfill',
'expose?Spinner!spin.js',
'script!jquery-ui-resizable',
'bootstrap-validator',
'expose?jsyaml!js-yaml',
'script!mermaid',
'expose?moment!moment',
'script!js-url',
'script!handlebars',
'expose?hljs!highlight.js',
'expose?emojify!emojify.js',
'expose?filterXSS!xss',
'script!Idle.Js',
'script!gist-embed',
'expose?LZString!lz-string',
'script!codemirror',
'script!inlineAttachment',
'script!jqueryTextcomplete',
'script!codemirrorSpellChecker',
'script!codemirrorInlineAttachment',
'script!ot',
'flowchart.js',
'js-sequence-diagrams',
'expose?Viz!viz.js',
'expose?io!socket.io-client',
'expose?RevealMarkdown!reveal-markdown',
path.join(__dirname, 'public/js/google-drive-upload.js'),
path.join(__dirname, 'public/js/google-drive-picker.js'),
path.join(__dirname, 'public/js/index.js')
],
pretty: [
'babel-polyfill',
'expose?filterXSS!xss',
'flowchart.js',
'js-sequence-diagrams',
'expose?RevealMarkdown!reveal-markdown',
path.join(__dirname, 'public/js/pretty.js')
],
'pretty-styles': [
path.join(__dirname, 'public/css/github-extract.css'),
path.join(__dirname, 'public/css/mermaid.css'),
path.join(__dirname, 'public/css/markdown.css'),
path.join(__dirname, 'public/css/slide-preview.css')
],
'pretty-styles-pack': [
path.join(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.min.css'),
path.join(__dirname, 'node_modules/font-awesome/css/font-awesome.min.css'),
path.join(__dirname, 'node_modules/ionicons/css/ionicons.min.css'),
path.join(__dirname, 'node_modules/octicons/octicons/octicons.css')
],
'pretty-pack': [
'babel-polyfill',
'expose?jsyaml!js-yaml',
'script!mermaid',
'expose?moment!moment',
'script!handlebars',
'expose?hljs!highlight.js',
'expose?emojify!emojify.js',
'expose?filterXSS!xss',
'script!gist-embed',
'flowchart.js',
'js-sequence-diagrams',
'expose?Viz!viz.js',
'expose?RevealMarkdown!reveal-markdown',
path.join(__dirname, 'public/js/pretty.js')
],
slide: [
'babel-polyfill',
'bootstrap-tooltip',
'expose?filterXSS!xss',
'flowchart.js',
'js-sequence-diagrams',
'expose?RevealMarkdown!reveal-markdown',
path.join(__dirname, 'public/js/slide.js')
],
'slide-styles': [
path.join(__dirname, 'public/vendor/bootstrap/tooltip.min.css'),
path.join(__dirname, 'public/css/github-extract.css'),
path.join(__dirname, 'public/css/mermaid.css'),
path.join(__dirname, 'public/css/markdown.css')
],
'slide-styles-pack': [
path.join(__dirname, 'node_modules/font-awesome/css/font-awesome.min.css'),
path.join(__dirname, 'node_modules/ionicons/css/ionicons.min.css'),
path.join(__dirname, 'node_modules/octicons/octicons/octicons.css')
],
'slide-pack': [
'babel-polyfill',
'expose?jQuery!expose?$!jquery',
'velocity-animate',
'imports?$=jquery!jquery-mousewheel',
'bootstrap-tooltip',
'expose?jsyaml!js-yaml',
'script!mermaid',
'expose?moment!moment',
'script!handlebars',
'expose?hljs!highlight.js',
'expose?emojify!emojify.js',
'expose?filterXSS!xss',
'script!gist-embed',
'flowchart.js',
'js-sequence-diagrams',
'expose?Viz!viz.js',
'headjs',
'expose?Reveal!reveal.js',
'expose?RevealMarkdown!reveal-markdown',
path.join(__dirname, 'public/js/slide.js')
]
},
entry: {
font: path.join(__dirname, 'public/css/google-font.css'),
"font-pack": path.join(__dirname, 'public/css/font.css'),
common: [
"expose?jQuery!expose?$!jquery",
"velocity-animate",
"imports?$=jquery!jquery-mousewheel",
"bootstrap"
],
cover: [
"babel-polyfill",
path.join(__dirname, 'public/js/cover.js')
],
"cover-styles-pack": [
path.join(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.min.css'),
path.join(__dirname, 'node_modules/font-awesome/css/font-awesome.min.css'),
path.join(__dirname, 'public/css/bootstrap-social.css'),
path.join(__dirname, 'node_modules/select2/select2.css'),
path.join(__dirname, 'node_modules/select2/select2-bootstrap.css'),
],
"cover-pack": [
"babel-polyfill",
"bootstrap-validator",
"script!listPagnation",
"expose?select2!select2",
"expose?moment!moment",
"script!js-url",
path.join(__dirname, 'public/js/cover.js')
],
index: [
"babel-polyfill",
"script!jquery-ui-resizable",
"script!js-url",
"expose?filterXSS!xss",
"script!Idle.Js",
"expose?LZString!lz-string",
"script!codemirror",
"script!inlineAttachment",
"script!jqueryTextcomplete",
"script!codemirrorSpellChecker",
"script!codemirrorInlineAttachment",
"script!ot",
"flowchart.js",
"js-sequence-diagrams",
"expose?RevealMarkdown!reveal-markdown",
path.join(__dirname, 'public/js/google-drive-upload.js'),
path.join(__dirname, 'public/js/google-drive-picker.js'),
path.join(__dirname, 'public/js/index.js')
],
"index-styles": [
path.join(__dirname, 'public/vendor/jquery-ui/jquery-ui.min.css'),
path.join(__dirname, 'public/vendor/codemirror-spell-checker/spell-checker.min.css'),
path.join(__dirname, 'node_modules/codemirror/lib/codemirror.css'),
path.join(__dirname, 'node_modules/codemirror/addon/fold/foldgutter.css'),
path.join(__dirname, 'node_modules/codemirror/addon/display/fullscreen.css'),
path.join(__dirname, 'node_modules/codemirror/addon/dialog/dialog.css'),
path.join(__dirname, 'node_modules/codemirror/addon/scroll/simplescrollbars.css'),
path.join(__dirname, 'node_modules/codemirror/addon/search/matchesonscrollbar.css'),
path.join(__dirname, 'node_modules/codemirror/theme/monokai.css'),
path.join(__dirname, 'node_modules/codemirror/theme/one-dark.css'),
path.join(__dirname, 'node_modules/codemirror/mode/tiddlywiki/tiddlywiki.css'),
path.join(__dirname, 'node_modules/codemirror/mode/mediawiki/mediawiki.css'),
path.join(__dirname, 'public/css/github-extract.css'),
path.join(__dirname, 'public/vendor/showup/showup.css'),
path.join(__dirname, 'public/css/mermaid.css'),
path.join(__dirname, 'public/css/markdown.css'),
path.join(__dirname, 'public/css/slide-preview.css')
],
"index-styles-pack": [
path.join(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.min.css'),
path.join(__dirname, 'node_modules/font-awesome/css/font-awesome.min.css'),
path.join(__dirname, 'public/css/bootstrap-social.css'),
path.join(__dirname, 'node_modules/ionicons/css/ionicons.min.css'),
path.join(__dirname, 'node_modules/octicons/octicons/octicons.css')
],
"index-pack": [
"babel-polyfill",
"expose?Spinner!spin.js",
"script!jquery-ui-resizable",
"bootstrap-validator",
"expose?jsyaml!js-yaml",
"script!mermaid",
"expose?moment!moment",
"script!js-url",
"script!handlebars",
"expose?hljs!highlight.js",
"expose?emojify!emojify.js",
"expose?filterXSS!xss",
"script!Idle.Js",
"script!gist-embed",
"expose?LZString!lz-string",
"script!codemirror",
"script!inlineAttachment",
"script!jqueryTextcomplete",
"script!codemirrorSpellChecker",
"script!codemirrorInlineAttachment",
"script!ot",
"flowchart.js",
"js-sequence-diagrams",
"expose?Viz!viz.js",
"expose?io!socket.io-client",
"expose?RevealMarkdown!reveal-markdown",
path.join(__dirname, 'public/js/google-drive-upload.js'),
path.join(__dirname, 'public/js/google-drive-picker.js'),
path.join(__dirname, 'public/js/index.js')
],
pretty: [
"babel-polyfill",
"expose?filterXSS!xss",
"flowchart.js",
"js-sequence-diagrams",
"expose?RevealMarkdown!reveal-markdown",
path.join(__dirname, 'public/js/pretty.js')
],
"pretty-styles": [
path.join(__dirname, 'public/css/github-extract.css'),
path.join(__dirname, 'public/css/mermaid.css'),
path.join(__dirname, 'public/css/markdown.css'),
path.join(__dirname, 'public/css/slide-preview.css')
],
"pretty-styles-pack": [
path.join(__dirname, 'node_modules/bootstrap/dist/css/bootstrap.min.css'),
path.join(__dirname, 'node_modules/font-awesome/css/font-awesome.min.css'),
path.join(__dirname, 'node_modules/ionicons/css/ionicons.min.css'),
path.join(__dirname, 'node_modules/octicons/octicons/octicons.css')
],
"pretty-pack": [
"babel-polyfill",
"expose?jsyaml!js-yaml",
"script!mermaid",
"expose?moment!moment",
"script!handlebars",
"expose?hljs!highlight.js",
"expose?emojify!emojify.js",
"expose?filterXSS!xss",
"script!gist-embed",
"flowchart.js",
"js-sequence-diagrams",
"expose?Viz!viz.js",
"expose?RevealMarkdown!reveal-markdown",
path.join(__dirname, 'public/js/pretty.js')
],
slide: [
"babel-polyfill",
"bootstrap-tooltip",
"expose?filterXSS!xss",
"flowchart.js",
"js-sequence-diagrams",
"expose?RevealMarkdown!reveal-markdown",
path.join(__dirname, 'public/js/slide.js')
],
"slide-styles": [
path.join(__dirname, 'public/vendor/bootstrap/tooltip.min.css'),
path.join(__dirname, 'public/css/github-extract.css'),
path.join(__dirname, 'public/css/mermaid.css'),
path.join(__dirname, 'public/css/markdown.css')
],
"slide-styles-pack": [
path.join(__dirname, 'node_modules/font-awesome/css/font-awesome.min.css'),
path.join(__dirname, 'node_modules/ionicons/css/ionicons.min.css'),
path.join(__dirname, 'node_modules/octicons/octicons/octicons.css')
],
"slide-pack": [
"babel-polyfill",
"expose?jQuery!expose?$!jquery",
"velocity-animate",
"imports?$=jquery!jquery-mousewheel",
"bootstrap-tooltip",
"expose?jsyaml!js-yaml",
"script!mermaid",
"expose?moment!moment",
"script!handlebars",
"expose?hljs!highlight.js",
"expose?emojify!emojify.js",
"expose?filterXSS!xss",
"script!gist-embed",
"flowchart.js",
"js-sequence-diagrams",
"expose?Viz!viz.js",
"headjs",
"expose?Reveal!reveal.js",
"expose?RevealMarkdown!reveal-markdown",
path.join(__dirname, 'public/js/slide.js')
]
},
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[name].js',
baseUrl: '<%- url %>'
},
output: {
path: path.join(__dirname, 'public/build'),
publicPath: '/build/',
filename: '[name].js',
baseUrl: '<%- url %>'
},
resolve: {
modulesDirectories: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules')
],
extensions: ["", ".js"],
alias: {
codemirror: path.join(__dirname, 'node_modules/codemirror/codemirror.min.js'),
inlineAttachment: path.join(__dirname, 'public/vendor/inlineAttachment/inline-attachment.js'),
jqueryTextcomplete: path.join(__dirname, 'public/vendor/jquery-textcomplete/jquery.textcomplete.js'),
codemirrorSpellChecker: path.join(__dirname, 'public/vendor/codemirror-spell-checker/spell-checker.min.js'),
codemirrorInlineAttachment: path.join(__dirname, 'public/vendor/inlineAttachment/codemirror.inline-attachment.js'),
ot: path.join(__dirname, 'public/vendor/ot/ot.min.js'),
listPagnation: path.join(__dirname, 'node_modules/list.pagination.js/dist/list.pagination.min.js'),
mermaid: path.join(__dirname, 'node_modules/mermaid/dist/mermaid.min.js'),
handlebars: path.join(__dirname, 'node_modules/handlebars/dist/handlebars.min.js'),
"jquery-ui-resizable": path.join(__dirname, 'public/vendor/jquery-ui/jquery-ui.min.js'),
"gist-embed": path.join(__dirname, 'node_modules/gist-embed/gist-embed.min.js'),
"bootstrap-tooltip": path.join(__dirname, 'public/vendor/bootstrap/tooltip.min.js'),
"headjs": path.join(__dirname, 'node_modules/reveal.js/lib/js/head.min.js'),
"reveal-markdown": path.join(__dirname, 'public/js/reveal-markdown.js')
}
},
externals: {
"viz.js": "Viz",
"socket.io-client": "io",
"lodash": "_",
"jquery": "$",
"moment": "moment",
"handlebars": "Handlebars",
"highlight.js": "hljs",
"select2": "select2"
},
module: {
loaders: [{
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.js$/,
loader: 'babel',
exclude: [/node_modules/, /public\/vendor/]
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'sass-loader')
}, {
test: /\.less$/,
loader: ExtractTextPlugin.extract('style-loader', 'less-loader')
}, {
test: require.resolve("js-sequence-diagrams"),
loader: "imports?Raphael=raphael"
}, {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: "file"
}, {
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?prefix=font/&limit=5000"
}, {
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/octet-stream"
}, {
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/svg+xml"
}, {
test: /\.png(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/png"
}, {
test: /\.gif(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=image/gif"
}]
},
node: {
fs: "empty"
resolve: {
modulesDirectories: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules')
],
extensions: ['', '.js'],
alias: {
codemirror: path.join(__dirname, 'node_modules/codemirror/codemirror.min.js'),
inlineAttachment: path.join(__dirname, 'public/vendor/inlineAttachment/inline-attachment.js'),
jqueryTextcomplete: path.join(__dirname, 'public/vendor/jquery-textcomplete/jquery.textcomplete.js'),
codemirrorSpellChecker: path.join(__dirname, 'public/vendor/codemirror-spell-checker/spell-checker.min.js'),
codemirrorInlineAttachment: path.join(__dirname, 'public/vendor/inlineAttachment/codemirror.inline-attachment.js'),
ot: path.join(__dirname, 'public/vendor/ot/ot.min.js'),
listPagnation: path.join(__dirname, 'node_modules/list.pagination.js/dist/list.pagination.min.js'),
mermaid: path.join(__dirname, 'node_modules/mermaid/dist/mermaid.min.js'),
handlebars: path.join(__dirname, 'node_modules/handlebars/dist/handlebars.min.js'),
'jquery-ui-resizable': path.join(__dirname, 'public/vendor/jquery-ui/jquery-ui.min.js'),
'gist-embed': path.join(__dirname, 'node_modules/gist-embed/gist-embed.min.js'),
'bootstrap-tooltip': path.join(__dirname, 'public/vendor/bootstrap/tooltip.min.js'),
'headjs': path.join(__dirname, 'node_modules/reveal.js/lib/js/head.min.js'),
'reveal-markdown': path.join(__dirname, 'public/js/reveal-markdown.js')
}
};
},
externals: {
'viz.js': 'Viz',
'socket.io-client': 'io',
'lodash': '_',
'jquery': '$',
'moment': 'moment',
'handlebars': 'Handlebars',
'highlight.js': 'hljs',
'select2': 'select2'
},
module: {
loaders: [{
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.js$/,
loader: 'babel',
exclude: [/node_modules/, /public\/vendor/]
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}, {
test: /\.scss$/,
loader: ExtractTextPlugin.extract('style-loader', 'sass-loader')
}, {
test: /\.less$/,
loader: ExtractTextPlugin.extract('style-loader', 'less-loader')
}, {
test: require.resolve('js-sequence-diagrams'),
loader: 'imports?Raphael=raphael'
}, {
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file'
}, {
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?prefix=font/&limit=5000'
}, {
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
}, {
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/svg+xml'
}, {
test: /\.png(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/png'
}, {
test: /\.gif(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/gif'
}]
},
node: {
fs: 'empty'
}
}