diff options
Diffstat (limited to 'public/js')
-rw-r--r-- | public/js/common.js | 118 | ||||
-rw-r--r-- | public/js/config.js.example | 11 | ||||
-rw-r--r-- | public/js/cover.js | 253 | ||||
-rw-r--r-- | public/js/extra.js | 665 | ||||
-rw-r--r-- | public/js/google-drive-picker.js | 3 | ||||
-rw-r--r-- | public/js/history.js | 206 | ||||
-rw-r--r-- | public/js/index.js | 131 | ||||
-rw-r--r-- | public/js/lib/common/login.js | 89 | ||||
-rw-r--r-- | public/js/lib/config/index.js | 19 | ||||
-rw-r--r-- | public/js/pretty.js | 88 | ||||
-rw-r--r-- | public/js/render.js | 2 | ||||
-rw-r--r-- | public/js/slide.js | 64 | ||||
-rw-r--r-- | public/js/syncscroll.js | 169 |
13 files changed, 876 insertions, 942 deletions
diff --git a/public/js/common.js b/public/js/common.js deleted file mode 100644 index 7eee1071..00000000 --- a/public/js/common.js +++ /dev/null @@ -1,118 +0,0 @@ -var config = require('./config'); -var domain = config.domain; // domain name -var urlpath = config.urlpath; // sub url path, like: www.example.com/<urlpath> -var debug = config.debug; -var GOOGLE_API_KEY = config.GOOGLE_API_KEY; -var GOOGLE_CLIENT_ID = config.GOOGLE_CLIENT_ID; -var DROPBOX_APP_KEY = config.DROPBOX_APP_KEY; - -//common -var port = window.location.port; -window.serverurl = window.location.protocol + '//' + (domain ? domain : window.location.hostname) + (port ? ':' + port : '') + (urlpath ? '/' + urlpath : ''); -var noteid = urlpath ? window.location.pathname.slice(urlpath.length + 1, window.location.pathname.length).split('/')[1] : window.location.pathname.split('/')[1]; -var noteurl = serverurl + '/' + noteid; - -var version = '0.5.0'; - -var checkAuth = false; -var profile = null; -var lastLoginState = getLoginState(); -var lastUserId = getUserId(); - -window.loginStateChangeEvent = null; - -function resetCheckAuth() { - checkAuth = false; -} - -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(); -} - -function checkLoginStateChanged() { - if (getLoginState() != lastLoginState || getUserId() != lastUserId) { - if(loginStateChangeEvent) setTimeout(loginStateChangeEvent, 100); - return true; - } else { - return false; - } -} - -function getLoginState() { - var state = Cookies.get('loginstate'); - return state === "true" || state === true; -} - -function getUserId() { - return Cookies.get('userid'); -} - -function clearLoginState() { - Cookies.remove('loginstate'); -} - -function checkIfAuth(yesCallback, noCallback) { - var cookieLoginState = getLoginState(); - if (checkLoginStateChanged()) checkAuth = false; - if (!checkAuth || typeof cookieLoginState == 'undefined') { - $.get(serverurl + '/me') - .done(function (data) { - if (data && data.status == 'ok') { - profile = data; - yesCallback(profile); - setLoginState(true, data.id); - } else { - noCallback(); - setLoginState(false); - } - }) - .fail(function () { - noCallback(); - }) - .always(function () { - checkAuth = true; - }); - } else if (cookieLoginState) { - yesCallback(profile); - } else { - noCallback(); - } -} - -module.exports = { - domain: domain, - urlpath: urlpath, - debug: debug, - GOOGLE_API_KEY: GOOGLE_API_KEY, - GOOGLE_CLIENT_ID: GOOGLE_CLIENT_ID, - DROPBOX_APP_KEY: DROPBOX_APP_KEY, - port: port, - noteid: noteid, - noteurl: noteurl, - version: version, - checkAuth: checkAuth, - profile: profile, - lastLoginState: lastLoginState, - lastUserId: lastUserId, - - /* export functions */ - resetCheckAuth: resetCheckAuth, - setLoginState: setLoginState, - checkLoginStateChanged: checkLoginStateChanged, - getLoginState: getLoginState, - getUserId: getUserId, - clearLoginState: clearLoginState, - checkIfAuth: checkIfAuth -}; diff --git a/public/js/config.js.example b/public/js/config.js.example deleted file mode 100644 index c5de388f..00000000 --- a/public/js/config.js.example +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = { - domain: '', // domain name - urlpath: '', // sub url path, like: www.example.com/<urlpath> - - // settings - debug: false, - - GOOGLE_API_KEY: '', - GOOGLE_CLIENT_ID: '', - DROPBOX_APP_KEY: '' -}; diff --git a/public/js/cover.js b/public/js/cover.js index f8ffe9bf..bc6e73f9 100644 --- a/public/js/cover.js +++ b/public/js/cover.js @@ -3,37 +3,39 @@ require('./locale'); require('../css/cover.css'); require('../css/site.css'); -var common = require('./common'); -var checkIfAuth = common.checkIfAuth; -var urlpath = common.urlpath; -var resetCheckAuth = common.resetCheckAuth; -var getLoginState = common.getLoginState; -var clearLoginState = common.clearLoginState; - -var historyModule = require('./history'); -var parseStorageToHistory = historyModule.parseStorageToHistory; -var parseHistory = historyModule.parseHistory; -var getStorageHistory = historyModule.getStorageHistory; -var getHistory = historyModule.getHistory; -var saveHistory = historyModule.saveHistory; -var removeHistory = historyModule.removeHistory; -var postHistoryToServer = historyModule.postHistoryToServer; -var deleteServerHistory = historyModule.deleteServerHistory; -var parseServerToHistory = historyModule.parseServerToHistory; -var saveStorageHistoryToServer = historyModule.saveStorageHistoryToServer; -var clearDuplicatedHistory = historyModule.clearDuplicatedHistory; - -var saveAs = require('file-saver').saveAs; -var List = require('list.js'); -var S = require('string'); - -var options = { +import { + checkIfAuth, + clearLoginState, + getLoginState, + resetCheckAuth, + setloginStateChangeEvent +} from './lib/common/login'; + +import { + clearDuplicatedHistory, + deleteServerHistory, + getHistory, + getStorageHistory, + parseHistory, + parseServerToHistory, + parseStorageToHistory, + postHistoryToServer, + removeHistory, + saveHistory, + saveStorageHistoryToServer +} from './history'; + +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-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>\ @@ -55,15 +57,16 @@ var options = { }) ] }; -var historyList = new List('history', options); +const historyList = new List('history', options); migrateHistoryFromTempCallback = pageInit; -loginStateChangeEvent = pageInit; +setloginStateChangeEvent(pageInit); + pageInit(); function pageInit() { checkIfAuth( - function (data) { + data => { $('.ui-signin').hide(); $('.ui-or').hide(); $('.ui-welcome').show(); @@ -74,7 +77,7 @@ function pageInit() { $(".ui-history").click(); parseServerToHistory(historyList, parseHistoryCallback); }, - function () { + () => { $('.ui-signin').show(); $('.ui-or').show(); $('.ui-welcome').hide(); @@ -103,7 +106,7 @@ $(".ui-home").click(function (e) { } }); -$(".ui-history").click(function (e) { +$(".ui-history").click(() => { if (!$("#history").is(':visible')) { $(".section:visible").hide(); $("#history").fadeIn(); @@ -118,7 +121,7 @@ function checkHistoryList() { } else if ($("#history-list").children().length == 0) { $('.pagination').hide(); $(".ui-nohistory").slideDown(); - getStorageHistory(function (data) { + getStorageHistory(data => { if (data && data.length > 0 && getLoginState() && historyList.items.length == 0) { $(".ui-import-from-browser").slideDown(); } @@ -128,35 +131,35 @@ function checkHistoryList() { function parseHistoryCallback(list, notehistory) { checkHistoryList(); - //sort by pinned then timestamp - list.sort('', { - sortFunction: function (a, b) { - var notea = a.values(); - var noteb = b.values(); - if (notea.pinned && !noteb.pinned) { + //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; - } - } - } - }); + if (notea.timestamp > noteb.timestamp) { + return -1; + } else if (notea.timestamp < noteb.timestamp) { + return 1; + } else { + return 0; + } + } + } + }); // parse filter tags - var filtertags = []; - for (var i = 0, l = list.items.length; i < l; i++) { - var tags = list.items[i]._values.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 (var j = 0; j < tags.length; j++) { + for (let j = 0; j < tags.length; j++) { //push info filtertags if not found - var found = false; - if (filtertags.indexOf(tags[j]) != -1) + let found = false; + if (filtertags.includes(tags[j])) found = true; if (!found) filtertags.push(tags[j]); @@ -167,17 +170,17 @@ function parseHistoryCallback(list, notehistory) { } // update items whenever list updated -historyList.on('updated', function (e) { - for (var i = 0, l = e.items.length; i < l; i++) { - var item = e.items[i]; +historyList.on('updated', e => { + for (let i = 0, l = e.items.length; i < l; i++) { + const item = e.items[i]; if (item.visible()) { - var itemEl = $(item.elm); - var values = item._values; - var a = itemEl.find("a"); - var pin = itemEl.find(".ui-history-pin"); - var tagsEl = itemEl.find(".tags"); + 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); + a.attr('href', `${serverurl}/${values.id}`); //parse pinned if (values.pinned) { pin.addClass('active'); @@ -185,12 +188,12 @@ historyList.on('updated', function (e) { pin.removeClass('active'); } //parse tags - var tags = values.tags; + const tags = values.tags; if (tags && tags.length > 0 && tagsEl.children().length <= 0) { - var labels = []; - for (var j = 0; j < tags.length; j++) { + 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>"); + labels.push(`<span class='label label-default'>${tags[j]}</span>`); } tagsEl.html(labels.join(' ')); } @@ -204,21 +207,21 @@ historyList.on('updated', function (e) { function historyCloseClick(e) { e.preventDefault(); - var id = $(this).closest("a").siblings("span").html(); - var value = historyList.get('id', id)[0]._values; + 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); + $('.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(); - var $this = $(this); - var id = $this.closest("a").siblings("span").html(); - var item = historyList.get('id', id)[0]; - var values = item._values; - var pinned = values.pinned; + 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; @@ -226,10 +229,10 @@ function historyPinClick(e) { pinned = false; item._values.pinned = false; } - checkIfAuth(function () { + checkIfAuth(() => { postHistoryToServer(id, { - pinned: pinned - }, function (err, result) { + pinned + }, (err, result) => { if (!err) { if (pinned) $this.addClass('active'); @@ -237,9 +240,9 @@ function historyPinClick(e) { $this.removeClass('active'); } }); - }, function () { - getHistory(function (notehistory) { - for(var i = 0; i < notehistory.length; i++) { + }, () => { + getHistory(notehistory => { + for(let i = 0; i < notehistory.length; i++) { if (notehistory[i].id == id) { notehistory[i].pinned = pinned; break; @@ -258,10 +261,10 @@ function historyPinClick(e) { setInterval(updateItemFromNow, 60000); function updateItemFromNow() { - var items = $('.item').toArray(); - for (var i = 0; i < items.length; i++) { - var item = $(items[i]); - var timestamp = parseInt(item.find('.timestamp').text()); + 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()); } } @@ -270,8 +273,8 @@ var clearHistory = false; var deleteId = null; function deleteHistory() { - checkIfAuth(function () { - deleteServerHistory(deleteId, function (err, result) { + checkIfAuth(() => { + deleteServerHistory(deleteId, (err, result) => { if (!err) { if (clearHistory) { historyList.clear(); @@ -285,7 +288,7 @@ function deleteHistory() { deleteId = null; clearHistory = false; }); - }, function () { + }, () => { if (clearHistory) { saveHistory([]); historyList.clear(); @@ -293,8 +296,8 @@ function deleteHistory() { deleteId = null; } else { if (!deleteId) return; - getHistory(function (notehistory) { - var newnotehistory = removeHistory(deleteId, notehistory); + getHistory(notehistory => { + const newnotehistory = removeHistory(deleteId, notehistory); saveHistory(newnotehistory); historyList.remove('id', deleteId); checkHistoryList(); @@ -306,36 +309,36 @@ function deleteHistory() { }); } -$(".ui-delete-modal-confirm").click(function () { +$(".ui-delete-modal-confirm").click(() => { deleteHistory(); }); -$(".ui-import-from-browser").click(function () { - saveStorageHistoryToServer(function () { +$(".ui-import-from-browser").click(() => { + saveStorageHistoryToServer(() => { parseStorageToHistory(historyList, parseHistoryCallback); }); }); -$(".ui-save-history").click(function () { - getHistory(function (data) { - var history = JSON.stringify(data); - var blob = new Blob([history], { +$(".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')); + saveAs(blob, `hackmd_history_${moment().format('YYYYMMDDHHmmss')}`, true); }); }); -$(".ui-open-history").bind("change", function (e) { - var files = e.target.files || e.dataTransfer.files; - var file = files[0]; - var reader = new FileReader(); - reader.onload = function () { - var notehistory = JSON.parse(reader.result); +$(".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(function (data) { - var mergedata = data.concat(notehistory); + getHistory(data => { + let mergedata = data.concat(notehistory); mergedata = clearDuplicatedHistory(mergedata); saveHistory(mergedata); parseHistory(historyList, parseHistoryCallback); @@ -345,18 +348,18 @@ $(".ui-open-history").bind("change", function (e) { reader.readAsText(file); }); -$(".ui-clear-history").click(function () { +$(".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(function () { - var lastTags = $(".ui-use-tags").select2('val'); +$(".ui-refresh-history").click(() => { + const lastTags = $(".ui-use-tags").select2('val'); $(".ui-use-tags").select2('val', ''); historyList.filter(); - var lastKeyword = $('.search').val(); + const lastKeyword = $('.search').val(); $('.search').val(''); historyList.search(); $('#history-list').slideUp('fast'); @@ -364,7 +367,7 @@ $(".ui-refresh-history").click(function () { resetCheckAuth(); historyList.clear(); - parseHistory(historyList, function (list, notehistory) { + parseHistory(historyList, (list, notehistory) => { parseHistoryCallback(list, notehistory); $(".ui-use-tags").select2('val', lastTags); $(".ui-use-tags").trigger('change'); @@ -375,16 +378,16 @@ $(".ui-refresh-history").click(function () { }); }); -$(".ui-logout").click(function () { +$(".ui-logout").click(() => { clearLoginState(); - location.href = serverurl + '/logout'; + location.href = `${serverurl}/logout`; }); -var filtertags = []; +let filtertags = []; $(".ui-use-tags").select2({ placeholder: $(".ui-use-tags").attr('placeholder'), multiple: true, - data: function () { + data() { return { results: filtertags }; @@ -394,7 +397,7 @@ $('.select2-input').css('width', 'inherit'); buildTagsFilter([]); function buildTagsFilter(tags) { - for (var i = 0; i < tags.length; i++) + for (let i = 0; i < tags.length; i++) tags[i] = { id: i, text: S(tags[i]).unescapeHTML().s @@ -402,17 +405,17 @@ function buildTagsFilter(tags) { filtertags = tags; } $(".ui-use-tags").on('change', function () { - var tags = []; - var data = $(this).select2('data'); - for (var i = 0; i < data.length; i++) + 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(function (item) { - var values = item.values(); + historyList.filter(item => { + const values = item.values(); if (!values.tags) return false; - var found = false; - for (var i = 0; i < tags.length; i++) { - if (values.tags.indexOf(tags[i]) != -1) { + let found = false; + for (let i = 0; i < tags.length; i++) { + if (values.tags.includes(tags[i])) { found = true; break; } @@ -425,6 +428,6 @@ $(".ui-use-tags").on('change', function () { checkHistoryList(); }); -$('.search').keyup(function () { +$('.search').keyup(() => { checkHistoryList(); }); diff --git a/public/js/extra.js b/public/js/extra.js index 4a9cc76e..a3e840d2 100644 --- a/public/js/extra.js +++ b/public/js/extra.js @@ -1,15 +1,17 @@ require('prismjs/themes/prism.css'); - -var Prism = require('prismjs'); require('prismjs/components/prism-wiki'); require('prismjs/components/prism-haskell'); require('prismjs/components/prism-go'); require('prismjs/components/prism-typescript'); require('prismjs/components/prism-jsx'); -var hljs = require('highlight.js'); -var PDFObject = require('pdfobject'); -var S = require('string'); -var saveAs = require('file-saver').saveAs; + +import Prism from 'prismjs'; +import hljs from 'highlight.js'; +import PDFObject from 'pdfobject'; +import S from 'string'; +import { saveAs } from 'file-saver'; + +require('./lib/common/login'); require('../vendor/md-toc'); var Viz = require("viz.js"); @@ -22,9 +24,10 @@ window.lastchangeui = { user: $(".ui-lastchangeuser"), nouser: $(".ui-no-lastchangeuser") } -var ownerui = $(".ui-owner"); -function updateLastChange() { +const ownerui = $(".ui-owner"); + +export function updateLastChange() { if (!lastchangeui) return; if (createtime) { if (createtime && !lastchangetime) { @@ -32,7 +35,7 @@ function updateLastChange() { } else { lastchangeui.status.text('changed'); } - var time = lastchangetime || createtime; + const time = lastchangetime || createtime; lastchangeui.time.html(moment(time).fromNow()); lastchangeui.time.attr('title', moment(time).format('llll')); } @@ -41,13 +44,14 @@ setInterval(updateLastChange, 60000); window.lastchangeuser = null; window.lastchangeuserprofile = null; -function updateLastChangeUser() { + +export function updateLastChangeUser() { if (lastchangeui) { if (lastchangeuser && lastchangeuserprofile) { - var icon = lastchangeui.user.children('i'); + const icon = lastchangeui.user.children('i'); icon.attr('title', lastchangeuserprofile.name).tooltip('fixTitle'); if (lastchangeuserprofile.photo) - icon.attr('style', 'background-image:url(' + lastchangeuserprofile.photo + ')'); + icon.attr('style', `background-image:url(${lastchangeuserprofile.photo})`); lastchangeui.user.show(); lastchangeui.nouser.hide(); } else { @@ -59,12 +63,13 @@ function updateLastChangeUser() { window.owner = null; window.ownerprofile = null; -function updateOwner() { + +export function updateOwner() { if (ownerui) { if (owner && ownerprofile && owner !== lastchangeuser) { - var icon = ownerui.children('i'); + const icon = ownerui.children('i'); icon.attr('title', ownerprofile.name).tooltip('fixTitle'); - var styleString = 'background-image:url(' + ownerprofile.photo + ')'; + const styleString = `background-image:url(${ownerprofile.photo})`; if (ownerprofile.photo && icon.attr('style') !== styleString) icon.attr('style', styleString); ownerui.show(); @@ -76,11 +81,11 @@ function updateOwner() { //get title function getTitle(view) { - var title = ""; + let title = ""; if (md && md.meta && md.meta.title && (typeof md.meta.title == "string" || typeof md.meta.title == "number")) { title = md.meta.title; } else { - var h1s = view.find("h1"); + const h1s = view.find("h1"); if (h1s.length > 0) { title = h1s.first().text(); } else { @@ -91,8 +96,8 @@ function getTitle(view) { } //render title -function renderTitle(view) { - var title = getTitle(view); +export function renderTitle(view) { + let title = getTitle(view); if (title) { title += ' - HackMD'; } else { @@ -102,8 +107,8 @@ function renderTitle(view) { } //render filename -function renderFilename(view) { - var filename = getTitle(view); +export function renderFilename(view) { + let filename = getTitle(view); if (!filename) { filename = 'Untitled'; } @@ -111,29 +116,29 @@ function renderFilename(view) { } // render tags -function renderTags(view) { - var tags = []; - var rawtags = []; +export function renderTags(view) { + const tags = []; + const rawtags = []; if (md && md.meta && md.meta.tags && (typeof md.meta.tags == "string" || typeof md.meta.tags == "number")) { - var metaTags = ('' + md.meta.tags).split(','); + const metaTags = (`${md.meta.tags}`).split(','); for (var i = 0; i < metaTags.length; i++) { - var text = metaTags[i].trim(); + const text = metaTags[i].trim(); if (text) rawtags.push(text); } } else { - view.find('h6').each(function (key, value) { + view.find('h6').each((key, value) => { if (/^tags/gmi.test($(value).text())) { - var codes = $(value).find("code"); - for (var i = 0; i < codes.length; i++) { - var text = codes[i].innerHTML.trim(); + const codes = $(value).find("code"); + for (let i = 0; i < codes.length; i++) { + const text = codes[i].innerHTML.trim(); if (text) rawtags.push(text); } } }); } for (var i = 0; i < rawtags.length; i++) { - var found = false; - for (var j = 0; j < tags.length; j++) { + let found = false; + for (let j = 0; j < tags.length; j++) { if (tags[j] == rawtags[i]) { found = true; break; @@ -146,13 +151,13 @@ function renderTags(view) { } function slugifyWithUTF8(text) { - var newText = S(text.toLowerCase()).trim().stripTags().dasherize().s; + let newText = S(text.toLowerCase()).trim().stripTags().dasherize().s; newText = newText.replace(/([\!\"\#\$\%\&\'\(\)\*\+\,\.\/\:\;\<\=\>\?\@\[\\\]\^\`\{\|\}\~])/g, ''); return newText; } -function isValidURL(str) { - var pattern = new RegExp('^(https?:\\/\\/)?' + // protocol +export function isValidURL(str) { + const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path @@ -166,12 +171,12 @@ function isValidURL(str) { } //parse meta -function parseMeta(md, edit, view, toc, tocAffix) { - var lang = null; - var dir = null; - var breaks = true; +export function parseMeta(md, edit, view, toc, tocAffix) { + let lang = null; + let dir = null; + let breaks = true; if (md && md.meta) { - var meta = md.meta; + const meta = md.meta; lang = meta.lang; dir = meta.dir; breaks = meta.breaks; @@ -211,13 +216,13 @@ function parseMeta(md, edit, view, toc, tocAffix) { window.viewAjaxCallback = null; //regex for extra tags -var spaceregex = /\s*/; -var notinhtmltagregex = /(?![^<]*>|[^<>]*<\/)/; -var coloregex = /\[color=([#|\(|\)|\s|\,|\w]*?)\]/; +const spaceregex = /\s*/; +const notinhtmltagregex = /(?![^<]*>|[^<>]*<\/)/; +let coloregex = /\[color=([#|\(|\)|\s|\,|\w]*?)\]/; coloregex = new RegExp(coloregex.source + notinhtmltagregex.source, "g"); -var nameregex = /\[name=(.*?)\]/; -var timeregex = /\[time=([:|,|+|-|\(|\)|\s|\w]*?)\]/; -var nameandtimeregex = new RegExp(nameregex.source + spaceregex.source + timeregex.source + notinhtmltagregex.source, "g"); +let nameregex = /\[name=(.*?)\]/; +let timeregex = /\[time=([:|,|+|-|\(|\)|\s|\w]*?)\]/; +const nameandtimeregex = new RegExp(nameregex.source + spaceregex.source + timeregex.source + notinhtmltagregex.source, "g"); nameregex = new RegExp(nameregex.source + notinhtmltagregex.source, "g"); timeregex = new RegExp(timeregex.source + notinhtmltagregex.source, "g"); @@ -232,35 +237,36 @@ function replaceExtraTags(html) { if (typeof mermaid !== 'undefined' && mermaid) mermaid.startOnLoad = false; //dynamic event or object binding here -function finishView(view) { +export function finishView(view) { //todo list - var lis = view.find('li.raw').removeClass("raw").sortByDepth().toArray(); - for (var i = 0; i < lis.length; i++) { - var li = lis[i]; - var html = $(li).clone()[0].innerHTML; - var p = $(li).children('p'); + const lis = view.find('li.raw').removeClass("raw").sortByDepth().toArray(); + + for (let li of lis) { + let html = $(li).clone()[0].innerHTML; + const p = $(li).children('p'); if (p.length == 1) { html = p.html(); li = p[0]; } html = replaceExtraTags(html); li.innerHTML = html; - var disabled = 'disabled'; + let disabled = 'disabled'; if(typeof editor !== 'undefined' && havePermission()) disabled = ''; if (/^\s*\[[x ]\]\s*/.test(html)) { - li.innerHTML = html.replace(/^\s*\[ \]\s*/, '<input type="checkbox" class="task-list-item-checkbox "' + disabled + '><label></label>') - .replace(/^\s*\[x\]\s*/, '<input type="checkbox" class="task-list-item-checkbox" checked ' + disabled + '><label></label>'); - lis[i].setAttribute('class', 'task-list-item'); + li.innerHTML = html.replace(/^\s*\[ \]\s*/, `<input type="checkbox" class="task-list-item-checkbox "${disabled}><label></label>`) + .replace(/^\s*\[x\]\s*/, `<input type="checkbox" class="task-list-item-checkbox" checked ${disabled}><label></label>`); + li.setAttribute('class', 'task-list-item'); } if (typeof editor !== 'undefined' && havePermission()) $(li).find('input').change(toggleTodoEvent); //color tag in list will convert it to tag icon with color - var tag_color = $(li).closest('ul').find(".color"); - tag_color.each(function (key, value) { + const tag_color = $(li).closest('ul').find(".color"); + tag_color.each((key, value) => { $(value).addClass('fa fa-tag').css('color', $(value).attr('data-color')); }); } + //youtube view.find("div.youtube.raw").removeClass("raw") .click(function () { @@ -271,41 +277,41 @@ function finishView(view) { .click(function () { imgPlayiframe(this, '//player.vimeo.com/video/'); }) - .each(function (key, value) { + .each((key, value) => { $.ajax({ type: 'GET', - url: '//vimeo.com/api/v2/video/' + $(value).attr('data-videoid') + '.json', + url: `//vimeo.com/api/v2/video/${$(value).attr('data-videoid')}.json`, jsonp: 'callback', dataType: 'jsonp', - success: function (data) { - var thumbnail_src = data[0].thumbnail_large; - var image = '<img src="' + thumbnail_src + '" />'; + success(data) { + const thumbnail_src = data[0].thumbnail_large; + const image = `<img src="${thumbnail_src}" />`; $(value).prepend(image); if(viewAjaxCallback) viewAjaxCallback(); } }); }); //gist - view.find("code[data-gist-id]").each(function (key, value) { + view.find("code[data-gist-id]").each((key, value) => { if ($(value).children().length == 0) $(value).gist(viewAjaxCallback); }); //sequence diagram - var sequences = view.find("div.sequence-diagram.raw").removeClass("raw"); - sequences.each(function (key, value) { + const sequences = view.find("div.sequence-diagram.raw").removeClass("raw"); + sequences.each((key, value) => { try { var $value = $(value); - var $ele = $(value).parent().parent(); + const $ele = $(value).parent().parent(); - var sequence = $value; + const sequence = $value; sequence.sequenceDiagram({ theme: 'simple' }); $ele.addClass('sequence-diagram'); $value.children().unwrap().unwrap(); - var svg = $ele.find('> svg'); - svg[0].setAttribute('viewBox', '0 0 ' + svg.attr('width') + ' ' + svg.attr('height')); + const svg = $ele.find('> svg'); + svg[0].setAttribute('viewBox', `0 0 ${svg.attr('width')} ${svg.attr('height')}`); svg[0].setAttribute('preserveAspectRatio', 'xMidYMid meet'); } catch (err) { $value.unwrap(); @@ -314,13 +320,13 @@ function finishView(view) { } }); //flowchart - var flow = view.find("div.flow-chart.raw").removeClass("raw"); - flow.each(function (key, value) { + const flow = view.find("div.flow-chart.raw").removeClass("raw"); + flow.each((key, value) => { try { var $value = $(value); - var $ele = $(value).parent().parent(); + const $ele = $(value).parent().parent(); - var chart = flowchart.parse($value.text()); + const chart = flowchart.parse($value.text()); $value.html(''); chart.drawSVG(value, { 'line-width': 2, @@ -339,41 +345,32 @@ function finishView(view) { }); //graphviz var graphvizs = view.find("div.graphviz.raw").removeClass("raw"); - function parseGraphviz(key, value) { - var $value = $(value); - var $ele = $(value).parent().parent(); - - var graphviz = Viz($value.text()); - if (!graphviz) throw Error('viz.js output empty graph'); - $value.html(graphviz); - - $ele.addClass('graphviz'); - $value.children().unwrap().unwrap(); - } graphvizs.each(function (key, value) { try { - parseGraphviz(key, value); + var $value = $(value); + var $ele = $(value).parent().parent(); + + var graphviz = Viz($value.text()); + if (!graphviz) throw Error('viz.js output empty graph'); + $value.html(graphviz); + + $ele.addClass('graphviz'); + $value.children().unwrap().unwrap(); } catch (err) { - // workaround for graphviz not recover from error - try { - parseGraphviz(key, value); - } catch (err) { - var $value = $(value); - $value.unwrap(); - $value.parent().append('<div class="alert alert-warning">' + err + '</div>'); - console.warn(err); - } + $value.unwrap(); + $value.parent().append('<div class="alert alert-warning">' + err + '</div>'); + console.warn(err); } }); //mermaid - var mermaids = view.find("div.mermaid.raw").removeClass("raw"); - mermaids.each(function (key, value) { + const mermaids = view.find("div.mermaid.raw").removeClass("raw"); + mermaids.each((key, value) => { try { var $value = $(value); - var $ele = $(value).closest('pre'); + const $ele = $(value).closest('pre'); - var mermaidError = null; - mermaid.parseError = function (err, hash) { + let mermaidError = null; + mermaid.parseError = (err, hash) => { mermaidError = err; }; @@ -391,44 +388,44 @@ function finishView(view) { } }); //image href new window(emoji not included) - var images = view.find("img.raw[src]").removeClass("raw"); - images.each(function (key, value) { + const images = view.find("img.raw[src]").removeClass("raw"); + images.each((key, value) => { // if it's already wrapped by link, then ignore - var $value = $(value); - $value[0].onload = function (e) { + const $value = $(value); + $value[0].onload = e => { if(viewAjaxCallback) viewAjaxCallback(); }; }); //blockquote - var blockquote = view.find("blockquote.raw").removeClass("raw"); - var blockquote_p = blockquote.find("p"); - blockquote_p.each(function (key, value) { - var html = $(value).html(); + const blockquote = view.find("blockquote.raw").removeClass("raw"); + const blockquote_p = blockquote.find("p"); + blockquote_p.each((key, value) => { + let html = $(value).html(); html = replaceExtraTags(html); $(value).html(html); }); //color tag in blockquote will change its left border color - var blockquote_color = blockquote.find(".color"); - blockquote_color.each(function (key, value) { + const blockquote_color = blockquote.find(".color"); + blockquote_color.each((key, value) => { $(value).closest("blockquote").css('border-left-color', $(value).attr('data-color')); }); //slideshare view.find("div.slideshare.raw").removeClass("raw") - .each(function (key, value) { + .each((key, value) => { $.ajax({ type: 'GET', - url: '//www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/' + $(value).attr('data-slideshareid') + '&format=json', + url: `//www.slideshare.net/api/oembed/2?url=http://www.slideshare.net/${$(value).attr('data-slideshareid')}&format=json`, jsonp: 'callback', dataType: 'jsonp', - success: function (data) { - var $html = $(data.html); - var iframe = $html.closest('iframe'); - var caption = $html.closest('div'); - var inner = $('<div class="inner"></div>').append(iframe); - var height = iframe.attr('height'); - var width = iframe.attr('width'); - var ratio = (height / width) * 100; - inner.css('padding-bottom', ratio + '%'); + success(data) { + const $html = $(data.html); + const iframe = $html.closest('iframe'); + const caption = $html.closest('div'); + const inner = $('<div class="inner"></div>').append(iframe); + const height = iframe.attr('height'); + const width = iframe.attr('width'); + const ratio = (height / width) * 100; + inner.css('padding-bottom', `${ratio}%`); $(value).html(inner).append(caption); if(viewAjaxCallback) viewAjaxCallback(); } @@ -436,31 +433,31 @@ function finishView(view) { }); //speakerdeck view.find("div.speakerdeck.raw").removeClass("raw") - .each(function (key, value) { - var url = 'https://speakerdeck.com/oembed.json?url=https%3A%2F%2Fspeakerdeck.com%2F' + encodeURIComponent($(value).attr('data-speakerdeckid')); + .each((key, value) => { + const url = `https://speakerdeck.com/oembed.json?url=https%3A%2F%2Fspeakerdeck.com%2F${encodeURIComponent($(value).attr('data-speakerdeckid'))}`; //use yql because speakerdeck not support jsonp $.ajax({ url: 'https://query.yahooapis.com/v1/public/yql', data: { - q: "select * from json where url ='" + url + "'", + q: `select * from json where url ='${url}'`, format: "json" }, dataType: "jsonp", - success: function (data) { + success(data) { if (!data.query || !data.query.results) return; - var json = data.query.results.json; - var html = json.html; + const json = data.query.results.json; + const html = json.html; var ratio = json.height / json.width; $(value).html(html); - var iframe = $(value).children('iframe'); - var src = iframe.attr('src'); + const iframe = $(value).children('iframe'); + const src = iframe.attr('src'); if (src.indexOf('//') == 0) - iframe.attr('src', 'https:' + src); - var inner = $('<div class="inner"></div>').append(iframe); - var height = iframe.attr('height'); - var width = iframe.attr('width'); + iframe.attr('src', `https:${src}`); + const inner = $('<div class="inner"></div>').append(iframe); + const height = iframe.attr('height'); + const width = iframe.attr('width'); var ratio = (height / width) * 100; - inner.css('padding-bottom', ratio + '%'); + inner.css('padding-bottom', `${ratio}%`); $(value).html(inner); if(viewAjaxCallback) viewAjaxCallback(); } @@ -469,8 +466,8 @@ function finishView(view) { //pdf view.find("div.pdf.raw").removeClass("raw") .each(function (key, value) { - var url = $(value).attr('data-pdfurl'); - var inner = $('<div></div>'); + const url = $(value).attr('data-pdfurl'); + const inner = $('<div></div>'); $(this).append(inner); PDFObject.embed(url, inner, { height: '400px' @@ -478,12 +475,12 @@ function finishView(view) { }); //syntax highlighting view.find("code.raw").removeClass("raw") - .each(function (key, value) { - var langDiv = $(value); + .each((key, value) => { + const langDiv = $(value); if (langDiv.length > 0) { - var reallang = langDiv[0].className.replace(/hljs|wrap/g, '').trim(); - var codeDiv = langDiv.find('.code'); - var code = ""; + const reallang = langDiv[0].className.replace(/hljs|wrap/g, '').trim(); + const codeDiv = langDiv.find('.code'); + let code = ""; if (codeDiv.length > 0) code = codeDiv.html(); else code = langDiv.html(); if (!reallang) { @@ -502,8 +499,8 @@ function finishView(view) { }; } else { code = S(code).unescapeHTML().s; - var languages = hljs.listLanguages(); - if (languages.indexOf(reallang) == -1) { + const languages = hljs.listLanguages(); + if (!languages.includes(reallang)) { var result = hljs.highlightAuto(code); } else { var result = hljs.highlight(reallang, code); @@ -514,7 +511,7 @@ function finishView(view) { } }); //mathjax - var mathjaxdivs = view.find('span.mathjax.raw').removeClass("raw").toArray(); + const mathjaxdivs = view.find('span.mathjax.raw').removeClass("raw").toArray(); try { if (mathjaxdivs.length > 1) { MathJax.Hub.Queue(["Typeset", MathJax.Hub, mathjaxdivs]); @@ -531,16 +528,16 @@ function finishView(view) { } //only static transform should be here -function postProcess(code) { - var result = $('<div>' + code + '</div>'); +export function postProcess(code) { + const result = $(`<div>${code}</div>`); //link should open in new window or tab result.find('a:not([href^="#"]):not([target])').attr('target', '_blank'); //update continue line numbers - var linenumberdivs = result.find('.gutter.linenumber').toArray(); - for (var i = 0; i < linenumberdivs.length; i++) { + const linenumberdivs = result.find('.gutter.linenumber').toArray(); + for (let i = 0; i < linenumberdivs.length; i++) { if ($(linenumberdivs[i]).hasClass('continue')) { - var startnumber = linenumberdivs[i - 1] ? parseInt($(linenumberdivs[i - 1]).find('> span').last().attr('data-linenumber')) : 0; - $(linenumberdivs[i]).find('> span').each(function(key, value) { + const startnumber = linenumberdivs[i - 1] ? parseInt($(linenumberdivs[i - 1]).find('> span').last().attr('data-linenumber')) : 0; + $(linenumberdivs[i]).find('> span').each((key, value) => { $(value).attr('data-linenumber', startnumber + key + 1); }); } @@ -560,8 +557,8 @@ function postProcess(code) { window.postProcess = postProcess; function generateCleanHTML(view) { - var src = view.clone(); - var eles = src.find('*'); + const src = view.clone(); + const eles = src.find('*'); //remove syncscroll parts eles.removeClass('part'); src.find('*[class=""]').removeAttr('class'); @@ -572,24 +569,24 @@ function generateCleanHTML(view) { //disable todo list src.find("input.task-list-item-checkbox").attr('disabled', ''); //replace emoji image path - src.find("img.emoji").each(function (key, value) { - var name = $(value).attr('alt'); + src.find("img.emoji").each((key, value) => { + let name = $(value).attr('alt'); name = name.substr(1); name = name.slice(0, name.length - 1); - $(value).attr('src', 'https://www.tortue.me/emoji/' + name + '.png'); + $(value).attr('src', `https://www.tortue.me/emoji/${name}.png`); }); //replace video to iframe - src.find("div[data-videoid]").each(function (key, value) { - var id = $(value).attr('data-videoid'); - var style = $(value).attr('style'); - var url = null; + src.find("div[data-videoid]").each((key, value) => { + const id = $(value).attr('data-videoid'); + const style = $(value).attr('style'); + let url = null; if ($(value).hasClass('youtube')) { url = 'https://www.youtube.com/embed/'; } else if ($(value).hasClass('vimeo')) { url = 'https://player.vimeo.com/video/'; } if (url) { - var iframe = $('<iframe frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'); + const iframe = $('<iframe frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>'); iframe.attr('src', url + id); iframe.attr('style', style); $(value).html(iframe); @@ -598,65 +595,63 @@ function generateCleanHTML(view) { return src; } -function exportToRawHTML(view) { - var filename = renderFilename(ui.area.markdown) + '.html'; - var src = generateCleanHTML(view); +export function exportToRawHTML(view) { + const filename = `${renderFilename(ui.area.markdown)}.html`; + const src = generateCleanHTML(view); $(src).find('a.anchor').remove(); - var html = src[0].outerHTML; - var blob = new Blob([html], { + const html = src[0].outerHTML; + const blob = new Blob([html], { type: "text/html;charset=utf-8" }); - saveAs(blob, filename); + saveAs(blob, filename, true); } -var common = require('./common.js'); //extract markdown body to html and compile to template -function exportToHTML(view) { - var title = renderTitle(ui.area.markdown); - var filename = renderFilename(ui.area.markdown) + '.html'; - var src = generateCleanHTML(view); +export function exportToHTML(view) { + const title = renderTitle(ui.area.markdown); + const filename = `${renderFilename(ui.area.markdown)}.html`; + const src = generateCleanHTML(view); //generate toc - var toc = $('#ui-toc').clone(); + const toc = $('#ui-toc').clone(); toc.find('*').removeClass('active').find("a[href^='#'][smoothhashscroll]").removeAttr('smoothhashscroll'); - var tocAffix = $('#ui-toc-affix').clone(); + const tocAffix = $('#ui-toc-affix').clone(); tocAffix.find('*').removeClass('active').find("a[href^='#'][smoothhashscroll]").removeAttr('smoothhashscroll'); //generate html via template - $.get(serverurl + '/build/html.min.css', function (css) { - $.get(serverurl + '/views/html.hbs', function (data) { - var template = Handlebars.compile(data); - var context = { + $.get(`${serverurl}/build/html.min.css`, css => { + $.get(`${serverurl}/views/html.hbs`, data => { + const template = Handlebars.compile(data); + const context = { url: serverurl, - title: title, - css: css, + title, + css, html: src[0].outerHTML, 'ui-toc': toc.html(), 'ui-toc-affix': tocAffix.html(), - lang: (md && md.meta && md.meta.lang) ? 'lang="' + md.meta.lang + '"' : null, - dir: (md && md.meta && md.meta.dir) ? 'dir="' + md.meta.dir + '"' : null + lang: (md && md.meta && md.meta.lang) ? `lang="${md.meta.lang}"` : null, + dir: (md && md.meta && md.meta.dir) ? `dir="${md.meta.dir}"` : null }; - var html = template(context); + const html = template(context); // console.log(html); - var blob = new Blob([html], { + const blob = new Blob([html], { type: "text/html;charset=utf-8" }); - saveAs(blob, filename); + saveAs(blob, filename, true); }); }); } //jQuery sortByDepth $.fn.sortByDepth = function () { - var ar = this.map(function () { + const ar = this.map(function () { return { length: $(this).parents().length, elt: this } - }).get(), - result = [], - i = ar.length; - ar.sort(function (a, b) { - return a.length - b.length; - }); + }).get(); + + const result = []; + let i = ar.length; + ar.sort((a, b) => a.length - b.length); while (i--) { result.push(ar[i].elt); } @@ -664,16 +659,16 @@ $.fn.sortByDepth = function () { }; function toggleTodoEvent(e) { - var startline = $(this).closest('li').attr('data-startline') - 1; - var line = editor.getLine(startline); - var matches = line.match(/^[>\s]*[\-\+\*]\s\[([x ])\]/); + const startline = $(this).closest('li').attr('data-startline') - 1; + const line = editor.getLine(startline); + const matches = line.match(/^[>\s]*[\-\+\*]\s\[([x ])\]/); if (matches && matches.length >= 2) { - var checked = null; + let checked = null; if (matches[1] == 'x') checked = true; else if (matches[1] == ' ') checked = false; - var replacements = matches[0].match(/(^[>\s]*[\-\+\*]\s\[)([x ])(\])/); + const replacements = matches[0].match(/(^[>\s]*[\-\+\*]\s\[)([x ])(\])/); editor.replaceRange(checked ? ' ' : 'x', { line: startline, ch: replacements[1].length @@ -689,11 +684,11 @@ function removeHash() { history.pushState("", document.title, window.location.pathname + window.location.search); } -var tocExpand = false; +let tocExpand = false; function checkExpandToggle() { - var toc = $('.ui-toc-dropdown .toc'); - var toggle = $('.expand-toggle'); + const toc = $('.ui-toc-dropdown .toc'); + const toggle = $('.expand-toggle'); if (!tocExpand) { toc.removeClass('expand'); toggle.text('Expand all'); @@ -704,8 +699,8 @@ function checkExpandToggle() { } //toc -function generateToc(id) { - var target = $('#' + id); +export function generateToc(id) { + const target = $(`#${id}`); target.html(''); new Toc('doc', { 'level': 3, @@ -717,25 +712,25 @@ function generateToc(id) { }); if (target.text() == 'undefined') target.html(''); - var tocMenu = $('<div class="toc-menu"></div'); - var toggle = $('<a class="expand-toggle" href="#">Expand all</a>'); - var backtotop = $('<a class="back-to-top" href="#">Back to top</a>'); - var gotobottom = $('<a class="go-to-bottom" href="#">Go to bottom</a>'); + const tocMenu = $('<div class="toc-menu"></div'); + const toggle = $('<a class="expand-toggle" href="#">Expand all</a>'); + const backtotop = $('<a class="back-to-top" href="#">Back to top</a>'); + const gotobottom = $('<a class="go-to-bottom" href="#">Go to bottom</a>'); checkExpandToggle(); - toggle.click(function (e) { + toggle.click(e => { e.preventDefault(); e.stopPropagation(); tocExpand = !tocExpand; checkExpandToggle(); }); - backtotop.click(function (e) { + backtotop.click(e => { e.preventDefault(); e.stopPropagation(); if (scrollToTop) scrollToTop(); removeHash(); }); - gotobottom.click(function (e) { + gotobottom.click(e => { e.preventDefault(); e.stopPropagation(); if (scrollToBottom) @@ -747,18 +742,18 @@ function generateToc(id) { } //smooth all hash trigger scrolling -function smoothHashScroll() { - var hashElements = $("a[href^='#']:not([smoothhashscroll])").toArray(); - for (var i = 0; i < hashElements.length; i++) { - var element = hashElements[i]; - var $element = $(element); - var hash = element.hash; +export function smoothHashScroll() { + const hashElements = $("a[href^='#']:not([smoothhashscroll])").toArray(); + + for (const element of hashElements) { + const $element = $(element); + const hash = element.hash; if (hash) { $element.on('click', function (e) { // store hash - var hash = decodeURIComponent(this.hash); + const hash = decodeURIComponent(this.hash); // escape special characters in jquery selector - var $hash = $(hash.replace(/(:|\.|\[|\]|,)/g, "\\$1")); + const $hash = $(hash.replace(/(:|\.|\[|\]|,)/g, "\\$1")); // return if no element been selected if ($hash.length <= 0) return; // prevent default anchor click behavior @@ -766,7 +761,7 @@ function smoothHashScroll() { // animate $('body, html').stop(true, true).animate({ scrollTop: $hash.offset().top - }, 100, "linear", function () { + }, 100, "linear", () => { // when done, add hash to url // (default click behaviour) window.location.hash = hash; @@ -779,29 +774,30 @@ function smoothHashScroll() { function imgPlayiframe(element, src) { if (!$(element).attr("data-videoid")) return; - var iframe = $("<iframe frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>"); - $(iframe).attr("src", src + $(element).attr("data-videoid") + '?autoplay=1'); + const iframe = $("<iframe frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>"); + $(iframe).attr("src", `${src + $(element).attr("data-videoid")}?autoplay=1`); $(element).find('img').css('visibility', 'hidden'); $(element).append(iframe); } -var anchorForId = function (id) { - var anchor = document.createElement("a"); +const anchorForId = id => { + const anchor = document.createElement("a"); anchor.className = "anchor hidden-xs"; - anchor.href = "#" + id; + anchor.href = `#${id}`; anchor.innerHTML = "<span class=\"octicon octicon-link\"></span>"; anchor.title = id; return anchor; }; -var linkifyAnchors = function (level, containingElement) { - var headers = containingElement.getElementsByTagName("h" + level); - for (var h = 0; h < headers.length; h++) { - var header = headers[h]; +const linkifyAnchors = (level, containingElement) => { + const headers = containingElement.getElementsByTagName(`h${level}`); + + for (let i = 0, l = headers.length; i < l; i++) { + let header = headers[i]; if (header.getElementsByClassName("anchor").length == 0) { if (typeof header.id == "undefined" || header.id == "") { //to escape characters not allow in css and humanize - var id = slugifyWithUTF8(getHeaderContent(header)); + const id = slugifyWithUTF8(getHeaderContent(header)); header.id = id; } header.insertBefore(anchorForId(header.id), header.firstChild); @@ -809,49 +805,49 @@ var linkifyAnchors = function (level, containingElement) { } }; -function autoLinkify(view) { - var contentBlock = view[0]; +export function autoLinkify(view) { + const contentBlock = view[0]; if (!contentBlock) { return; } - for (var level = 1; level <= 6; level++) { + for (let level = 1; level <= 6; level++) { linkifyAnchors(level, contentBlock); } } function getHeaderContent(header) { - var headerHTML = $(header).clone(); + const headerHTML = $(header).clone(); headerHTML.find('.MathJax_Preview').remove(); headerHTML.find('.MathJax').remove(); return headerHTML[0].innerHTML; } -function deduplicatedHeaderId(view) { - var headers = view.find(':header.raw').removeClass('raw').toArray(); - for (var i = 0; i < headers.length; i++) { - var id = $(headers[i]).attr('id'); +export function deduplicatedHeaderId(view) { + const headers = view.find(':header.raw').removeClass('raw').toArray(); + for (let i = 0; i < headers.length; i++) { + const id = $(headers[i]).attr('id'); if (!id) continue; - var duplicatedHeaders = view.find(':header[id="' + id + '"]').toArray(); - for (var j = 0; j < duplicatedHeaders.length; j++) { + const duplicatedHeaders = view.find(`:header[id="${id}"]`).toArray(); + for (let j = 0; j < duplicatedHeaders.length; j++) { if (duplicatedHeaders[j] != headers[i]) { - var newId = id + j; - var $duplicatedHeader = $(duplicatedHeaders[j]); + const newId = id + j; + const $duplicatedHeader = $(duplicatedHeaders[j]); $duplicatedHeader.attr('id', newId); - var $headerLink = $duplicatedHeader.find('> .header-link'); - $headerLink.attr('href', '#' + newId); + const $headerLink = $duplicatedHeader.find(`> a.anchor[href="#${id}"]`); + $headerLink.attr('href', `#${newId}`); $headerLink.attr('title', newId); } } } } -function renderTOC(view) { - var tocs = view.find('.toc').toArray(); - for (var i = 0; i < tocs.length; i++) { - var toc = $(tocs[i]); - var id = 'toc' + i; +export function renderTOC(view) { + const tocs = view.find('.toc').toArray(); + for (let i = 0; i < tocs.length; i++) { + const toc = $(tocs[i]); + const id = `toc${i}`; toc.attr('id', id); - var target = $('#' + id); + const target = $(`#${id}`); target.html(''); new Toc('doc', { 'level': 3, @@ -866,8 +862,8 @@ function renderTOC(view) { } } -function scrollToHash() { - var hash = location.hash; +export function scrollToHash() { + const hash = location.hash; location.hash = ""; location.hash = hash; } @@ -877,39 +873,39 @@ function highlightRender(code, lang) { return; code = S(code).escapeHTML().s if (lang == 'sequence') { - return '<div class="sequence-diagram raw">' + code + '</div>'; + return `<div class="sequence-diagram raw">${code}</div>`; } else if (lang == 'flow') { - return '<div class="flow-chart raw">' + code + '</div>'; + return `<div class="flow-chart raw">${code}</div>`; } else if (lang == 'graphviz') { - return '<div class="graphviz raw">' + code + '</div>'; + return `<div class="graphviz raw">${code}</div>`; } else if (lang == 'mermaid') { - return '<div class="mermaid raw">' + code + '</div>'; + return `<div class="mermaid raw">${code}</div>`; } - var result = { + const result = { value: code }; - var showlinenumbers = /\=$|\=\d+$|\=\+$/.test(lang); + const showlinenumbers = /\=$|\=\d+$|\=\+$/.test(lang); if (showlinenumbers) { - var startnumber = 1; - var matches = lang.match(/\=(\d+)$/); + let startnumber = 1; + const matches = lang.match(/\=(\d+)$/); if (matches) startnumber = parseInt(matches[1]); - var lines = result.value.split('\n'); - var linenumbers = []; - for (var i = 0; i < lines.length - 1; i++) { - linenumbers[i] = "<span data-linenumber='" + (startnumber + i) + "'></span>"; + const lines = result.value.split('\n'); + const linenumbers = []; + for (let i = 0; i < lines.length - 1; i++) { + linenumbers[i] = `<span data-linenumber='${startnumber + i}'></span>`; } - var continuelinenumber = /\=\+$/.test(lang); - var linegutter = "<div class='gutter linenumber" + (continuelinenumber ? " continue" : "") + "'>" + linenumbers.join('\n') + "</div>"; - result.value = "<div class='wrapper'>" + linegutter + "<div class='code'>" + result.value + "</div></div>"; + const continuelinenumber = /\=\+$/.test(lang); + const linegutter = `<div class='gutter linenumber${continuelinenumber ? " continue" : ""}'>${linenumbers.join('\n')}</div>`; + result.value = `<div class='wrapper'>${linegutter}<div class='code'>${result.value}</div></div>`; } return result.value; } -var markdownit = require('markdown-it'); -var markdownitContainer = require('markdown-it-container'); +import markdownit from 'markdown-it'; +import markdownitContainer from 'markdown-it-container'; -var md = markdownit('default', { +export let md = markdownit('default', { html: true, breaks: true, langPrefix: "", @@ -945,19 +941,17 @@ emojify.setConfig({ elements: ['script', 'textarea', 'a', 'pre', 'code', 'svg'], classes: ['no-emojify'] }, - img_dir: serverurl + '/build/emojify.js/dist/images/basic', + img_dir: `${serverurl}/build/emojify.js/dist/images/basic`, ignore_emoticons: true }); -md.renderer.rules.emoji = function(token, idx) { - return emojify.replace(':' + token[idx].markup + ':'); -}; +md.renderer.rules.emoji = (token, idx) => emojify.replace(`:${token[idx].markup}:`); 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()); - return self.renderToken.apply(self, arguments); + tokens[idx].attrJoin('class', `alert-${tokens[idx].info.trim()}`); + return self.renderToken(...arguments); } md.use(markdownitContainer, 'success', { render: renderContainer }); md.use(markdownitContainer, 'info', { render: renderContainer }); @@ -966,25 +960,25 @@ md.use(markdownitContainer, 'danger', { render: renderContainer }); md.renderer.rules.image = function (tokens, idx, options, env, self) { tokens[idx].attrJoin('class', 'raw'); - return self.renderToken.apply(self, arguments); + return self.renderToken(...arguments); }; md.renderer.rules.list_item_open = function (tokens, idx, options, env, self) { tokens[idx].attrJoin('class', 'raw'); - return self.renderToken.apply(self, arguments); + return self.renderToken(...arguments); }; md.renderer.rules.blockquote_open = function (tokens, idx, options, env, self) { tokens[idx].attrJoin('class', 'raw'); - return self.renderToken.apply(self, arguments); + return self.renderToken(...arguments); }; md.renderer.rules.heading_open = function (tokens, idx, options, env, self) { tokens[idx].attrJoin('class', 'raw'); - return self.renderToken.apply(self, arguments); + return self.renderToken(...arguments); }; -md.renderer.rules.fence = function (tokens, idx, options, env, self) { - var token = tokens[idx], - info = token.info ? md.utils.unescapeAll(token.info).trim() : '', - langName = '', - highlighted; +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; if (info) { langName = info.split(/\s+/g)[0]; @@ -1001,110 +995,99 @@ md.renderer.rules.fence = function (tokens, idx, options, env, self) { } if (highlighted.indexOf('<pre') === 0) { - return highlighted + '\n'; + return `${highlighted}\n`; } - return '<pre><code' + self.renderAttrs(token) + '>' - + highlighted - + '</code></pre>\n'; + return `<pre><code${self.renderAttrs(token)}>${highlighted}</code></pre>\n`; }; /* Defined regex markdown it plugins */ -var Plugin = require('markdown-it-regexp'); +import Plugin from 'markdown-it-regexp'; //youtube -var youtubePlugin = new Plugin( +const youtubePlugin = new Plugin( // regexp to match /{%youtube\s*([\d\D]*?)\s*%}/, - // this function will be called when something matches - function (match, utils) { - var videoid = match[1]; + (match, utils) => { + const videoid = match[1]; if (!videoid) return; - var div = $('<div class="youtube raw"></div>'); + const div = $('<div class="youtube raw"></div>'); div.attr('data-videoid', videoid); - var thumbnail_src = '//img.youtube.com/vi/' + videoid + '/hqdefault.jpg'; - var image = '<img src="' + thumbnail_src + '" />'; + const thumbnail_src = `//img.youtube.com/vi/${videoid}/hqdefault.jpg`; + const image = `<img src="${thumbnail_src}" />`; div.append(image); - var icon = '<i class="icon fa fa-youtube-play fa-5x"></i>'; + const icon = '<i class="icon fa fa-youtube-play fa-5x"></i>'; div.append(icon); return div[0].outerHTML; } ); //vimeo -var vimeoPlugin = new Plugin( +const vimeoPlugin = new Plugin( // regexp to match /{%vimeo\s*([\d\D]*?)\s*%}/, - // this function will be called when something matches - function (match, utils) { - var videoid = match[1]; + (match, utils) => { + const videoid = match[1]; if (!videoid) return; - var div = $('<div class="vimeo raw"></div>'); + const div = $('<div class="vimeo raw"></div>'); div.attr('data-videoid', videoid); - var icon = '<i class="icon fa fa-vimeo-square fa-5x"></i>'; + const icon = '<i class="icon fa fa-vimeo-square fa-5x"></i>'; div.append(icon); return div[0].outerHTML; } ); //gist -var gistPlugin = new Plugin( +const gistPlugin = new Plugin( // regexp to match /{%gist\s*([\d\D]*?)\s*%}/, - // this function will be called when something matches - function (match, utils) { - var gistid = match[1]; - var code = '<code data-gist-id="' + gistid + '"/>'; + (match, utils) => { + const gistid = match[1]; + const code = `<code data-gist-id="${gistid}"/>`; return code; } ); //TOC -var tocPlugin = new Plugin( +const tocPlugin = new Plugin( // regexp to match /^\[TOC\]$/i, - // this function will be called when something matches - function (match, utils) { - return '<div class="toc"></div>'; - } + (match, utils) => '<div class="toc"></div>' ); //slideshare -var slidesharePlugin = new Plugin( +const slidesharePlugin = new Plugin( // regexp to match /{%slideshare\s*([\d\D]*?)\s*%}/, - // this function will be called when something matches - function (match, utils) { - var slideshareid = match[1]; - var div = $('<div class="slideshare raw"></div>'); + (match, utils) => { + const slideshareid = match[1]; + const div = $('<div class="slideshare raw"></div>'); div.attr('data-slideshareid', slideshareid); return div[0].outerHTML; } ); //speakerdeck -var speakerdeckPlugin = new Plugin( +const speakerdeckPlugin = new Plugin( // regexp to match /{%speakerdeck\s*([\d\D]*?)\s*%}/, - // this function will be called when something matches - function (match, utils) { - var speakerdeckid = match[1]; - var div = $('<div class="speakerdeck raw"></div>'); + (match, utils) => { + const speakerdeckid = match[1]; + const div = $('<div class="speakerdeck raw"></div>'); div.attr('data-speakerdeckid', speakerdeckid); return div[0].outerHTML; } ); //pdf -var pdfPlugin = new Plugin( +const pdfPlugin = new Plugin( // regexp to match /{%pdf\s*([\d\D]*?)\s*%}/, - // this function will be called when something matches - function (match, utils) { - var pdfurl = match[1]; + (match, utils) => { + const pdfurl = match[1]; if (!isValidURL(pdfurl)) return match[0]; - var div = $('<div class="pdf raw"></div>'); + const div = $('<div class="pdf raw"></div>'); div.attr('data-pdfurl', pdfurl); return div[0].outerHTML; } @@ -1112,8 +1095,8 @@ var pdfPlugin = new Plugin( //yaml meta, from https://github.com/eugeneware/remarkable-meta function get(state, line) { - var pos = state.bMarks[line]; - var max = state.eMarks[line]; + const pos = state.bMarks[line]; + const max = state.eMarks[line]; return state.src.substr(pos, max - pos); } @@ -1122,9 +1105,9 @@ function meta(state, start, end, silent) { if (state.tShift[start] < 0) return false; if (!get(state, start).match(/^---$/)) return false; - var data = []; + const data = []; for (var line = start + 1; line < end; line++) { - var str = get(state, line); + const str = get(state, line); if (str.match(/^(\.{3}|-{3})$/)) break; if (state.tShift[line] < 0) break; data.push(str); @@ -1162,24 +1145,6 @@ md.use(slidesharePlugin); md.use(speakerdeckPlugin); md.use(pdfPlugin); -module.exports = { - md: md, - updateLastChange: updateLastChange, - postProcess: postProcess, - finishView: finishView, - autoLinkify: autoLinkify, - deduplicatedHeaderId: deduplicatedHeaderId, - renderTOC: renderTOC, - renderTitle: renderTitle, - renderFilename: renderFilename, - renderTags: renderTags, - isValidURL: isValidURL, - generateToc: generateToc, - smoothHashScroll: smoothHashScroll, - scrollToHash: scrollToHash, - updateLastChangeUser: updateLastChangeUser, - updateOwner: updateOwner, - parseMeta: parseMeta, - exportToHTML: exportToHTML, - exportToRawHTML: exportToRawHTML +export default { + md }; diff --git a/public/js/google-drive-picker.js b/public/js/google-drive-picker.js index e653653c..94aa77ff 100644 --- a/public/js/google-drive-picker.js +++ b/public/js/google-drive-picker.js @@ -52,6 +52,7 @@ 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). @@ -115,4 +116,4 @@ }, callback ? callback : function() {}); } }; -}());
\ No newline at end of file +}()); diff --git a/public/js/history.js b/public/js/history.js index 6972f24c..34b2cba7 100644 --- a/public/js/history.js +++ b/public/js/history.js @@ -1,10 +1,13 @@ -var store = require('store'); -var S = require('string'); +import store from 'store'; +import S from 'string'; -var common = require('./common'); -var checkIfAuth = common.checkIfAuth; -var urlpath = common.urlpath; -var getLoginState = common.getLoginState; +import { + checkIfAuth +} from './lib/common/login'; + +import { + urlpath +} from './lib/config'; window.migrateHistoryFromTempCallback = null; @@ -12,22 +15,22 @@ migrateHistoryFromTemp(); function migrateHistoryFromTemp() { if (url('#tempid')) { - $.get(serverurl + '/temp', { + $.get(`${serverurl}/temp`, { tempid: url('#tempid') }) - .done(function (data) { + .done(data => { if (data && data.temp) { - getStorageHistory(function (olddata) { + getStorageHistory(olddata => { if (!olddata || olddata.length == 0) { saveHistoryToStorage(JSON.parse(data.temp)); } }); } }) - .always(function () { - var hash = location.hash.split('#')[1]; + .always(() => { + let hash = location.hash.split('#')[1]; hash = hash.split('&'); - for (var i = 0; i < hash.length; i++) + for (let i = 0; i < hash.length; i++) if (hash[i].indexOf('tempid') == 0) { hash.splice(i, 1); i--; @@ -40,12 +43,12 @@ function migrateHistoryFromTemp() { } } -function saveHistory(notehistory) { +export function saveHistory(notehistory) { checkIfAuth( - function () { + () => { saveHistoryToServer(notehistory); }, - function () { + () => { saveHistoryToStorage(notehistory); } ); @@ -65,7 +68,7 @@ function saveHistoryToCookie(notehistory) { } function saveHistoryToServer(notehistory) { - $.post(serverurl + '/history', { + $.post(`${serverurl}/history`, { history: JSON.stringify(notehistory) }); } @@ -75,37 +78,37 @@ function saveCookieHistoryToStorage(callback) { callback(); } -function saveStorageHistoryToServer(callback) { - var data = store.get('notehistory'); +export function saveStorageHistoryToServer(callback) { + const data = store.get('notehistory'); if (data) { - $.post(serverurl + '/history', { + $.post(`${serverurl}/history`, { history: data }) - .done(function (data) { + .done(data => { callback(data); }); } } function saveCookieHistoryToServer(callback) { - $.post(serverurl + '/history', { + $.post(`${serverurl}/history`, { history: Cookies.get('notehistory') }) - .done(function (data) { + .done(data => { callback(data); }); } -function clearDuplicatedHistory(notehistory) { - var newnotehistory = []; - for (var i = 0; i < notehistory.length; i++) { - var found = false; - for (var j = 0; j < newnotehistory.length; j++) { - var id = notehistory[i].id.replace(/\=+$/, ''); - var newId = newnotehistory[j].id.replace(/\=+$/, ''); +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) { - var time = (typeof notehistory[i].time === 'number' ? moment(notehistory[i].time) : moment(notehistory[i].time, 'MMMM Do YYYY, h:mm:ss a')); - var newTime = (typeof newnotehistory[i].time === 'number' ? moment(newnotehistory[i].time) : moment(newnotehistory[i].time, 'MMMM Do YYYY, h:mm:ss a')); + 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]; } @@ -123,42 +126,42 @@ function addHistory(id, text, time, tags, pinned, notehistory) { // only add when note id exists if (id) { notehistory.push({ - id: id, - text: text, - time: time, - tags: tags, - pinned: pinned + id, + text, + time, + tags, + pinned }); } return notehistory; } -function removeHistory(id, notehistory) { - for (var i = 0; i < notehistory.length; i++) { +export function removeHistory(id, notehistory) { + for (let i = 0; i < notehistory.length; i++) { if (notehistory[i].id == id) { notehistory.splice(i, 1); - i--; - } + i -= 1; + } } return notehistory; } //used for inner -function writeHistory(title, tags) { +export function writeHistory(title, tags) { checkIfAuth( - function () { + () => { // no need to do this anymore, this will count from server-side // writeHistoryToServer(title, tags); }, - function () { + () => { writeHistoryToStorage(title, tags); } ); } function writeHistoryToServer(title, tags) { - $.get(serverurl + '/history') - .done(function (data) { + $.get(`${serverurl}/history`) + .done(data => { try { if (data.history) { var notehistory = data.history; @@ -171,10 +174,10 @@ function writeHistoryToServer(title, tags) { if (!notehistory) notehistory = []; - var newnotehistory = generateHistory(title, tags, notehistory); + const newnotehistory = generateHistory(title, tags, notehistory); saveHistoryToServer(newnotehistory); }) - .fail(function (xhr, status, error) { + .fail((xhr, status, error) => { console.error(xhr.responseText); }); } @@ -188,13 +191,13 @@ function writeHistoryToCookie(title, tags) { if (!notehistory) notehistory = []; - var newnotehistory = generateHistory(title, tags, notehistory); + const newnotehistory = generateHistory(title, tags, notehistory); saveHistoryToCookie(newnotehistory); } function writeHistoryToStorage(title, tags) { if (store.enabled) { - var data = store.get('notehistory'); + let data = store.get('notehistory'); if (data) { if (typeof data == "string") data = JSON.parse(data); @@ -204,7 +207,7 @@ function writeHistoryToStorage(title, tags) { if (!notehistory) notehistory = []; - var newnotehistory = generateHistory(title, tags, notehistory); + const newnotehistory = generateHistory(title, tags, notehistory); saveHistoryToStorage(newnotehistory); } else { writeHistoryToCookie(title, tags); @@ -212,32 +215,30 @@ function writeHistoryToStorage(title, tags) { } if (!Array.isArray) { - Array.isArray = function(arg) { - return Object.prototype.toString.call(arg) === '[object Array]'; - }; + Array.isArray = arg => Object.prototype.toString.call(arg) === '[object Array]'; } function renderHistory(title, tags) { //console.debug(tags); - var id = urlpath ? location.pathname.slice(urlpath.length + 1, location.pathname.length).split('/')[1] : location.pathname.split('/')[1]; + const id = urlpath ? location.pathname.slice(urlpath.length + 1, location.pathname.length).split('/')[1] : location.pathname.split('/')[1]; return { - id: id, + id, text: title, time: moment().valueOf(), - tags: tags + tags }; } function generateHistory(title, tags, notehistory) { - var info = renderHistory(title, tags); - //keep any pinned data - var pinned = false; - for (var i = 0; i < notehistory.length; i++) { - if (notehistory[i].id == info.id && notehistory[i].pinned) { - pinned = true; - break; - } - } + 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); @@ -245,25 +246,25 @@ function generateHistory(title, tags, notehistory) { } //used for outer -function getHistory(callback) { +export function getHistory(callback) { checkIfAuth( - function () { + () => { getServerHistory(callback); }, - function () { + () => { getStorageHistory(callback); } ); } function getServerHistory(callback) { - $.get(serverurl + '/history') - .done(function (data) { + $.get(`${serverurl}/history`) + .done(data => { if (data.history) { callback(data.history); } }) - .fail(function (xhr, status, error) { + .fail((xhr, status, error) => { console.error(xhr.responseText); }); } @@ -272,9 +273,9 @@ function getCookieHistory(callback) { callback(Cookies.getJSON('notehistory')); } -function getStorageHistory(callback) { +export function getStorageHistory(callback) { if (store.enabled) { - var data = store.get('notehistory'); + let data = store.get('notehistory'); if (data) { if (typeof data == "string") data = JSON.parse(data); @@ -286,37 +287,37 @@ function getStorageHistory(callback) { } } -function parseHistory(list, callback) { +export function parseHistory(list, callback) { checkIfAuth( - function () { + () => { parseServerToHistory(list, callback); }, - function () { + () => { parseStorageToHistory(list, callback); } ); } -function parseServerToHistory(list, callback) { - $.get(serverurl + '/history') - .done(function (data) { +export function parseServerToHistory(list, callback) { + $.get(`${serverurl}/history`) + .done(data => { if (data.history) { parseToHistory(list, data.history, callback); } }) - .fail(function (xhr, status, error) { + .fail((xhr, status, error) => { console.error(xhr.responseText); }); } function parseCookieToHistory(list, callback) { - var notehistory = Cookies.getJSON('notehistory'); + const notehistory = Cookies.getJSON('notehistory'); parseToHistory(list, notehistory, callback); } -function parseStorageToHistory(list, callback) { +export function parseStorageToHistory(list, callback) { if (store.enabled) { - var data = store.get('notehistory'); + let data = store.get('notehistory'); if (data) { if (typeof data == "string") data = JSON.parse(data); @@ -332,9 +333,9 @@ function parseToHistory(list, notehistory, callback) { if (!callback) return; else if (!list || !notehistory) callback(list, notehistory); else if (notehistory && notehistory.length > 0) { - for (var i = 0; i < notehistory.length; i++) { + for (let i = 0; i < notehistory.length; i++) { //parse time to timestamp and fromNow - var timestamp = (typeof notehistory[i].time === 'number' ? moment(notehistory[i].time) : moment(notehistory[i].time, 'MMMM Do YYYY, h:mm:ss a')); + 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'); @@ -349,42 +350,23 @@ function parseToHistory(list, notehistory, callback) { callback(list, notehistory); } -function postHistoryToServer(noteId, data, callback) { - $.post(serverurl + '/history/' + noteId, data) - .done(function (result) { - return callback(null, result); - }) - .fail(function (xhr, status, error) { +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); }); } -function deleteServerHistory(noteId, callback) { +export function deleteServerHistory(noteId, callback) { $.ajax({ - url: serverurl + '/history' + (noteId ? '/' + noteId : ""), + url: `${serverurl}/history${noteId ? '/' + noteId : ""}`, type: 'DELETE' }) - .done(function (result) { - return callback(null, result); - }) - .fail(function (xhr, status, error) { + .done(result => callback(null, result)) + .fail((xhr, status, error) => { console.error(xhr.responseText); return callback(error, null); }); } - -module.exports = { - writeHistory: writeHistory, - parseHistory: parseHistory, - getStorageHistory: getStorageHistory, - getHistory: getHistory, - saveHistory: saveHistory, - removeHistory: removeHistory, - parseStorageToHistory: parseStorageToHistory, - postHistoryToServer: postHistoryToServer, - deleteServerHistory: deleteServerHistory, - parseServerToHistory: parseServerToHistory, - saveStorageHistoryToServer: saveStorageHistoryToServer, - clearDuplicatedHistory: clearDuplicatedHistory -} diff --git a/public/js/index.js b/public/js/index.js index a018e513..f0c476ef 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -17,51 +17,58 @@ var _ = require("lodash"); var List = require('list.js'); -var common = require('./common.js'); -var urlpath = common.urlpath; -var noteid = common.noteid; -var debug = common.debug; -var version = common.version; -var GOOGLE_API_KEY = common.GOOGLE_API_KEY; -var GOOGLE_CLIENT_ID = common.GOOGLE_CLIENT_ID; -var DROPBOX_APP_KEY = common.DROPBOX_APP_KEY; -var noteurl = common.noteurl; - -var checkLoginStateChanged = common.checkLoginStateChanged; - -var extra = require('./extra'); -var md = extra.md; -var updateLastChange = extra.updateLastChange; -var postProcess = extra.postProcess; -var finishView = extra.finishView; -var autoLinkify = extra.autoLinkify; -var generateToc = extra.generateToc; -var smoothHashScroll = extra.smoothHashScroll; -var deduplicatedHeaderId = extra.deduplicatedHeaderId; -var renderTOC = extra.renderTOC; -var renderTitle = extra.renderTitle; -var renderFilename = extra.renderFilename; -var renderTags = extra.renderTags; -var isValidURL = extra.isValidURL; -var scrollToHash = extra.scrollToHash; -var updateLastChangeUser = extra.updateLastChangeUser; -var updateOwner = extra.updateOwner; -var parseMeta = extra.parseMeta; -var exportToHTML = extra.exportToHTML; -var exportToRawHTML = extra.exportToRawHTML; - -var syncScroll = require('./syncscroll'); -var setupSyncAreas = syncScroll.setupSyncAreas; -var clearMap = syncScroll.clearMap; -var syncScrollToEdit = syncScroll.syncScrollToEdit; -var syncScrollToView = syncScroll.syncScrollToView; - -var historyModule = require('./history'); -var writeHistory = historyModule.writeHistory; -var deleteServerHistory = historyModule.deleteServerHistory; -var getHistory = historyModule.getHistory; -var saveHistory = historyModule.saveHistory; -var removeHistory = historyModule.removeHistory; +import { + checkLoginStateChanged, + setloginStateChangeEvent +} from './lib/common/login'; + +import { + debug, + DROPBOX_APP_KEY, + GOOGLE_API_KEY, + GOOGLE_CLIENT_ID, + noteid, + noteurl, + urlpath, + version +} from './lib/config'; + +import { + autoLinkify, + deduplicatedHeaderId, + exportToHTML, + exportToRawHTML, + finishView, + generateToc, + isValidURL, + md, + parseMeta, + postProcess, + renderFilename, + renderTOC, + renderTags, + renderTitle, + scrollToHash, + smoothHashScroll, + updateLastChange, + updateLastChangeUser, + updateOwner +} from './extra'; + +import { + clearMap, + setupSyncAreas, + syncScrollToEdit, + syncScrollToView +} from './syncscroll'; + +import { + writeHistory, + deleteServerHistory, + getHistory, + saveHistory, + removeHistory +} from './history'; var renderer = require('./render'); var preventXSS = renderer.preventXSS; @@ -401,7 +408,8 @@ window.lastInfo = { cursor: { line: null, ch: null - } + }, + selections: null }, view: { scroll: { @@ -963,10 +971,10 @@ function setNeedRefresh() { showStatus(statusType.offline); } -loginStateChangeEvent = function () { +setloginStateChangeEvent(function () { setRefreshModal('user-state-changed'); setNeedRefresh(); -}; +}); //visibility var wasFocus = false; @@ -1535,7 +1543,7 @@ ui.toolbar.download.markdown.click(function (e) { var blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" }); - saveAs(blob, filename); + saveAs(blob, filename, true); }); //html ui.toolbar.download.html.click(function (e) { @@ -1915,7 +1923,7 @@ $('#revisionModalDownload').click(function () { var blob = new Blob([revision.content], { type: "text/markdown;charset=utf-8" }); - saveAs(blob, filename); + saveAs(blob, filename, true); }); $('#revisionModalRevert').click(function () { if (!revision) return; @@ -2511,7 +2519,7 @@ var addStyleRule = (function () { }()); function updateAuthorshipInner() { // ignore when ot not synced yet - if (cmClient && Object.keys(cmClient.state).length > 0) return; + if (havePendingOperation()) return; authorMarks = {}; for (var i = 0; i < authorship.length; i++) { var atom = authorship[i]; @@ -2668,7 +2676,7 @@ editor.on('update', function () { }); // clear tooltip which described element has been removed $('[id^="tooltip"]').each(function (index, element) { - $ele = $(element); + var $ele = $(element); if ($('[aria-describedby="' + $ele.attr('id') + '"]').length <= 0) $ele.remove(); }); }); @@ -2726,12 +2734,16 @@ var EditorClient = ot.EditorClient; var SocketIOAdapter = ot.SocketIOAdapter; var CodeMirrorAdapter = ot.CodeMirrorAdapter; var cmClient = null; +var synchronized_ = null; + +function havePendingOperation() { + return (cmClient && cmClient.state && cmClient.state.hasOwnProperty('outstanding')) ? true : false; +} socket.on('doc', function (obj) { var body = obj.str; var bodyMismatch = editor.getValue() !== body; - var havePendingOperation = cmClient && Object.keys(cmClient.state).length > 0; - var setDoc = !cmClient || (cmClient && (cmClient.revision === -1 || (cmClient.revision !== obj.revision && !havePendingOperation))) || obj.force; + var setDoc = !cmClient || (cmClient && (cmClient.revision === -1 || (cmClient.revision !== obj.revision && !havePendingOperation()))) || obj.force; saveInfo(); if (setDoc && bodyMismatch) { @@ -2756,16 +2768,17 @@ socket.on('doc', function (obj) { obj.revision, obj.clients, new SocketIOAdapter(socket), new CodeMirrorAdapter(editor) ); + synchronized_ = cmClient.state; } else if (setDoc) { if (bodyMismatch) { cmClient.undoManager.undoStack.length = 0; cmClient.undoManager.redoStack.length = 0; } cmClient.revision = obj.revision; - cmClient.setState(new ot.Client.Synchronized()); + cmClient.setState(synchronized_); cmClient.initializeClientList(); cmClient.initializeClients(obj.clients); - } else if (havePendingOperation) { + } else if (havePendingOperation()) { cmClient.serverReconnect(); } @@ -3387,6 +3400,7 @@ function saveInfo() { break; } lastInfo.edit.cursor = editor.getCursor(); + lastInfo.edit.selections = editor.listSelections(); lastInfo.needRestore = true; } @@ -3396,6 +3410,7 @@ function restoreInfo() { var line = lastInfo.edit.cursor.line; var ch = lastInfo.edit.cursor.ch; editor.setCursor(line, ch); + editor.setSelections(lastInfo.edit.selections); switch (currentMode) { case modeType.edit: if (scrollbarStyle == 'native') { @@ -3445,6 +3460,7 @@ function updateViewInner() { var value = editor.getValue(); var lastMeta = md.meta; md.meta = {}; + delete md.metaError; var rendered = md.render(value); if (md.meta.type && md.meta.type === 'slide') { var slideOptions = { @@ -3716,6 +3732,7 @@ function checkCursorMenuInner() { var offsetLeft = 0; var offsetTop = defaultTextHeight; // set up side down + window.upSideDown = false; var lastUpSideDown = upSideDown = false; // only do when have width and height if (width > 0 && height > 0) { @@ -3944,7 +3961,7 @@ $(editor.getInputField()) match: /(?:^|\n|\s)(\>.*|\s|)((\^|)\[(\^|)\](\[\]|\(\)|\:|)\s*\w*)$/, search: function (term, callback) { var line = editor.getLine(editor.getCursor().line); - quote = line.match(this.match)[1].trim(); + var quote = line.match(this.match)[1].trim(); var list = []; if (quote.indexOf('>') == 0) { $.map(supportExtraTags, function (extratag) { diff --git a/public/js/lib/common/login.js b/public/js/lib/common/login.js new file mode 100644 index 00000000..58fa55c6 --- /dev/null +++ b/public/js/lib/common/login.js @@ -0,0 +1,89 @@ +import { serverurl } from '../config'; + +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 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 getLoginState() { + const state = Cookies.get('loginstate'); + return state === "true" || state === true; +} + +export function getUserId() { + return Cookies.get('userid'); +} + +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`) + .done(data => { + if (data && data.status == 'ok') { + profile = data; + yesCallback(profile); + setLoginState(true, data.id); + } else { + noCallback(); + setLoginState(false); + } + }) + .fail(() => { + noCallback(); + }) + .always(() => { + checkAuth = true; + }); + } else if (cookieLoginState) { + yesCallback(profile); + } else { + noCallback(); + } +} + +export default { + checkAuth, + profile, + lastLoginState, + lastUserId, + loginStateChangeEvent +}; diff --git a/public/js/lib/config/index.js b/public/js/lib/config/index.js new file mode 100644 index 00000000..2b73679f --- /dev/null +++ b/public/js/lib/config/index.js @@ -0,0 +1,19 @@ +import configJson from '../../../../config.json'; // root path json config + +const config = 'production' === process.env.NODE_ENV ? 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 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 version = '0.5.0'; diff --git a/public/js/pretty.js b/public/js/pretty.js index c1a471a1..18d0dc0d 100644 --- a/public/js/pretty.js +++ b/public/js/pretty.js @@ -4,31 +4,34 @@ require('../css/site.css'); require('highlight.js/styles/github-gist.css'); -var extra = require('./extra'); -var md = extra.md; -var finishView = extra.finishView; -var autoLinkify = extra.autoLinkify; -var deduplicatedHeaderId = extra.deduplicatedHeaderId; -var renderTOC = extra.renderTOC; -var generateToc = extra.generateToc; -var smoothHashScroll = extra.smoothHashScroll; -var postProcess = extra.postProcess; -var updateLastChange = extra.updateLastChange; -var parseMeta = extra.parseMeta; -var scrollToHash = extra.scrollToHash; -var preventXSS = require('./render').preventXSS; +import { + autoLinkify, + deduplicatedHeaderId, + finishView, + generateToc, + md, + parseMeta, + postProcess, + renderTOC, + scrollToHash, + smoothHashScroll, + updateLastChange +} from './extra'; -var markdown = $("#doc.markdown-body"); -var text = markdown.text(); -var lastMeta = md.meta; +import { preventXSS } from './render'; + +const markdown = $("#doc.markdown-body"); +const text = markdown.text(); +const lastMeta = md.meta; md.meta = {}; -var rendered = md.render(text); +delete md.metaError; +let rendered = md.render(text); if (md.meta.type && md.meta.type === 'slide') { - var slideOptions = { + const slideOptions = { separator: '^(\r\n?|\n)---(\r\n?|\n)$', verticalSeparator: '^(\r\n?|\n)----(\r\n?|\n)$' }; - var slides = RevealMarkdown.slidify(text, slideOptions); + const slides = RevealMarkdown.slidify(text, slideOptions); markdown.html(slides); RevealMarkdown.initialize(); // prevent XSS @@ -46,10 +49,11 @@ if (md.meta.type && md.meta.type === 'slide') { } // prevent XSS rendered = preventXSS(rendered); - var result = postProcess(rendered); + const result = postProcess(rendered); markdown.html(result.html()); } $(document.body).show(); + finishView(markdown); autoLinkify(markdown); deduplicatedHeaderId(markdown); @@ -60,17 +64,18 @@ smoothHashScroll(); createtime = lastchangeui.time.attr('data-createtime'); lastchangetime = lastchangeui.time.attr('data-updatetime'); updateLastChange(); -var url = window.location.pathname; -$('.ui-edit').attr('href', url + '/edit'); -var toc = $('.ui-toc'); -var tocAffix = $('.ui-affix-toc'); -var tocDropdown = $('.ui-toc-dropdown'); + +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(function (e) { +tocDropdown.click(e => { e.stopPropagation(); }); -var enoughForAffixToc = true; +let enoughForAffixToc = true; function generateScrollspy() { $(document.body).scrollspy({ @@ -89,18 +94,18 @@ function generateScrollspy() { function windowResize() { //toc right - var paddingRight = parseFloat(markdown.css('padding-right')); - var right = ($(window).width() - (markdown.offset().left + markdown.outerWidth() - paddingRight)); - toc.css('right', right + 'px'); + 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 - var newbool; - var rightMargin = (markdown.parent().outerWidth() - markdown.outerWidth()) / 2; + let newbool; + const rightMargin = (markdown.parent().outerWidth() - markdown.outerWidth()) / 2; //for ipad or wider device if (rightMargin >= 133) { newbool = true; - var affixLeftMargin = (tocAffix.outerWidth() - tocAffix.width()) / 2; - var left = markdown.offset().left + markdown.outerWidth() - affixLeftMargin; - tocAffix.css('left', left + 'px'); + const affixLeftMargin = (tocAffix.outerWidth() - tocAffix.width()) / 2; + const left = markdown.offset().left + markdown.outerWidth() - affixLeftMargin; + tocAffix.css('left', `${left}px`); } else { newbool = false; } @@ -109,10 +114,10 @@ function windowResize() { generateScrollspy(); } } -$(window).resize(function () { +$(window).resize(() => { windowResize(); }); -$(document).ready(function () { +$(document).ready(() => { windowResize(); generateScrollspy(); setTimeout(scrollToHash, 0); @@ -120,13 +125,13 @@ $(document).ready(function () { $('[data-toggle="tooltip"]').tooltip(); }); -function scrollToTop() { +export function scrollToTop() { $('body, html').stop(true, true).animate({ scrollTop: 0 }, 100, "linear"); } -function scrollToBottom() { +export function scrollToBottom() { $('body, html').stop(true, true).animate({ scrollTop: $(document.body)[0].scrollHeight }, 100, "linear"); @@ -134,8 +139,3 @@ function scrollToBottom() { window.scrollToTop = scrollToTop; window.scrollToBottom = scrollToBottom; - -module.exports = { - scrollToBottom: scrollToBottom, - scrollToTop: scrollToTop -} diff --git a/public/js/render.js b/public/js/render.js index a61fc8fb..5d6d0aa2 100644 --- a/public/js/render.js +++ b/public/js/render.js @@ -9,6 +9,8 @@ var dataUriRegex = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base var whiteList = filterXSS.whiteList; // allow ol specify start number whiteList['ol'] = ['start']; +// allow li specify value number +whiteList['li'] = ['value']; // allow style tag whiteList['style'] = []; // allow kbd tag diff --git a/public/js/slide.js b/public/js/slide.js index 1ff388a5..63cf64c6 100644 --- a/public/js/slide.js +++ b/public/js/slide.js @@ -1,67 +1,65 @@ require('../css/extra.css'); require('../css/site.css'); -var extraModule = require('./extra'); -var md = extraModule.md; -var updateLastChange = extraModule.updateLastChange; -var finishView = extraModule.finishView; +import { md, updateLastChange, finishView } from './extra'; -var preventXSS = require('./render').preventXSS; +import { preventXSS } from './render'; -var body = $(".slides").text(); +const body = $(".slides").text(); createtime = lastchangeui.time.attr('data-createtime'); lastchangetime = lastchangeui.time.attr('data-updatetime'); updateLastChange(); -var url = window.location.pathname; -$('.ui-edit').attr('href', url + '/edit'); +const url = window.location.pathname; +$('.ui-edit').attr('href', `${url}/edit`); -$(document).ready(function () { +$(document).ready(() => { //tooltip $('[data-toggle="tooltip"]').tooltip(); }); function extend() { - var target = {}; - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { + const target = {}; + + for (const source of arguments) { + for (const key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } } + return target; } // Optional libraries used to extend on reveal.js -var deps = [{ - src: serverurl + '/build/reveal.js/lib/js/classList.js', - condition: function() { +const deps = [{ + src: `${serverurl}/build/reveal.js/lib/js/classList.js`, + condition() { return !document.body.classList; } }, { - src: serverurl + '/js/reveal-markdown.js', - callback: function () { - var slideOptions = { + src: `${serverurl}/js/reveal-markdown.js`, + callback() { + const slideOptions = { separator: '^(\r\n?|\n)---(\r\n?|\n)$', verticalSeparator: '^(\r\n?|\n)----(\r\n?|\n)$' }; - var slides = RevealMarkdown.slidify(body, slideOptions); + const slides = RevealMarkdown.slidify(body, slideOptions); $(".slides").html(slides); RevealMarkdown.initialize(); $(".slides").show(); } }, { - src: serverurl + '/build/reveal.js/plugin/notes/notes.js', + src: `${serverurl}/build/reveal.js/plugin/notes/notes.js`, async: true, - condition: function() { + condition() { return !!document.body.classList; } }]; // default options to init reveal.js -var defaultOptions = { +const defaultOptions = { controls: true, progress: true, slideNumber: true, @@ -72,10 +70,10 @@ var defaultOptions = { }; // options from yaml meta -var meta = JSON.parse($("#meta").text()); +const meta = JSON.parse($("#meta").text()); var options = meta.slideOptions || {}; -var view = $('.reveal'); +const view = $('.reveal'); //text language if (meta.lang && typeof meta.lang == "string") { @@ -97,24 +95,24 @@ if (typeof meta.breaks === 'boolean' && !meta.breaks) { } // options from URL query string -var queryOptions = Reveal.getQueryHash() || {}; +const queryOptions = Reveal.getQueryHash() || {}; var options = extend(defaultOptions, options, queryOptions); Reveal.initialize(options); -window.viewAjaxCallback = function () { +window.viewAjaxCallback = () => { Reveal.layout(); }; function renderSlide(event) { if (window.location.search.match( /print-pdf/gi )) { - var slides = $('.slides'); + const slides = $('.slides'); var title = document.title; finishView(slides); document.title = title; Reveal.layout(); } else { - var markdown = $(event.currentSlide); + const markdown = $(event.currentSlide); if (!markdown.attr('data-rendered')) { var title = document.title; finishView(markdown); @@ -125,16 +123,16 @@ function renderSlide(event) { } } -Reveal.addEventListener('ready', function (event) { +Reveal.addEventListener('ready', event => { renderSlide(event); - var markdown = $(event.currentSlide); + const markdown = $(event.currentSlide); // force browser redraw - setTimeout(function () { + setTimeout(() => { markdown.hide().show(0); }, 0); }); Reveal.addEventListener('slidechanged', renderSlide); -var isMacLike = navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) ? true : false; +const isMacLike = navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) ? true : false; if (!isMacLike) $('.container').addClass('hidescrollbar'); diff --git a/public/js/syncscroll.js b/public/js/syncscroll.js index 47d0e1c4..c9693176 100644 --- a/public/js/syncscroll.js +++ b/public/js/syncscroll.js @@ -1,12 +1,13 @@ // Inject line numbers for sync scroll. -var extra = require('./extra'); -var md = extra.md; +import markdownitContainer from 'markdown-it-container'; + +import { md } from './extra'; function addPart(tokens, idx) { if (tokens[idx].map && tokens[idx].level === 0) { - var startline = tokens[idx].map[0] + 1; - var endline = tokens[idx].map[1]; + 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); @@ -16,48 +17,48 @@ function addPart(tokens, idx) { md.renderer.rules.blockquote_open = function (tokens, idx, options, env, self) { tokens[idx].attrJoin('class', 'raw'); addPart(tokens, idx); - return self.renderToken.apply(self, arguments); + return self.renderToken(...arguments); }; md.renderer.rules.table_open = function (tokens, idx, options, env, self) { addPart(tokens, idx); - return self.renderToken.apply(self, arguments); + return self.renderToken(...arguments); }; md.renderer.rules.bullet_list_open = function (tokens, idx, options, env, self) { addPart(tokens, idx); - return self.renderToken.apply(self, arguments); + 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) { - var startline = tokens[idx].map[0] + 1; - var endline = tokens[idx].map[1]; + 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.apply(self, arguments); + return self.renderToken(...arguments); }; md.renderer.rules.ordered_list_open = function (tokens, idx, options, env, self) { addPart(tokens, idx); - return self.renderToken.apply(self, arguments); + return self.renderToken(...arguments); }; md.renderer.rules.link_open = function (tokens, idx, options, env, self) { addPart(tokens, idx); - return self.renderToken.apply(self, arguments); + return self.renderToken(...arguments); }; md.renderer.rules.paragraph_open = function (tokens, idx, options, env, self) { addPart(tokens, idx); - return self.renderToken.apply(self, arguments); + 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.apply(self, arguments); + return self.renderToken(...arguments); }; -md.renderer.rules.fence = function (tokens, idx, options, env, self) { - var token = tokens[idx], - info = token.info ? md.utils.unescapeAll(token.info).trim() : '', - langName = '', - highlighted; +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; if (info) { langName = info.split(/\s+/g)[0]; @@ -74,38 +75,33 @@ md.renderer.rules.fence = function (tokens, idx, options, env, self) { } if (highlighted.indexOf('<pre') === 0) { - return highlighted + '\n'; + return `${highlighted}\n`; } if (tokens[idx].map && tokens[idx].level === 0) { - var startline = tokens[idx].map[0] + 1; - var endline = tokens[idx].map[1]; - return '<pre class="part" data-startline="' + startline + '" data-endline="' + endline + '"><code' + self.renderAttrs(token) + '>' - + highlighted - + '</code></pre>\n'; + 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 = function (tokens, idx, options, env, self) { +md.renderer.rules.code_block = (tokens, idx, options, env, self) => { if (tokens[idx].map && tokens[idx].level === 0) { - var startline = tokens[idx].map[0] + 1; - var 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'; + 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'; + 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()); + tokens[idx].attrJoin('class', `alert-${tokens[idx].info.trim()}`); addPart(tokens, idx); - return self.renderToken.apply(self, arguments); + return self.renderToken(...arguments); } -var markdownitContainer = require('markdown-it-container'); md.use(markdownitContainer, 'success', { render: renderContainer }); md.use(markdownitContainer, 'info', { render: renderContainer }); md.use(markdownitContainer, 'warning', { render: renderContainer }); @@ -117,18 +113,18 @@ window.syncscroll = true; window.preventSyncScrollToEdit = false; window.preventSyncScrollToView = false; -var editScrollThrottle = 5; -var viewScrollThrottle = 5; -var buildMapThrottle = 100; +const editScrollThrottle = 5; +const viewScrollThrottle = 5; +const buildMapThrottle = 100; -var viewScrolling = false; -var editScrolling = false; +let viewScrolling = false; +let editScrolling = false; -var editArea = null; -var viewArea = null; -var markdownArea = null; +let editArea = null; +let viewArea = null; +let markdownArea = null; -function setupSyncAreas(edit, view, markdown) { +export function setupSyncAreas(edit, view, markdown) { editArea = edit; viewArea = view; markdownArea = markdown; @@ -136,26 +132,24 @@ function setupSyncAreas(edit, view, markdown) { viewArea.on('scroll', _.throttle(syncScrollToEdit, viewScrollThrottle)); } -var scrollMap, lineHeightMap, viewTop, viewBottom; - -window.viewAjaxCallback = clearMap; +let scrollMap, lineHeightMap, viewTop, viewBottom; -function clearMap() { +export function clearMap() { scrollMap = null; lineHeightMap = null; viewTop = null; viewBottom = null; } +window.viewAjaxCallback = clearMap; -var 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; - var i, offset, nonEmptyList, pos, a, b, _lineHeightMap, linesCount, - acc, _scrollMap; + let i, offset, nonEmptyList, pos, a, b, _lineHeightMap, linesCount, acc, _scrollMap; offset = viewArea.scrollTop() - viewArea.offset().top; _scrollMap = []; @@ -165,10 +159,10 @@ function buildMapInner(callback) { viewBottom = viewArea[0].scrollHeight - viewArea.height(); acc = 0; - var lines = editor.getValue().split('\n'); - var lineHeight = editor.defaultTextHeight(); + const lines = editor.getValue().split('\n'); + const lineHeight = editor.defaultTextHeight(); for (i = 0; i < lines.length; i++) { - var str = lines[i]; + const str = lines[i]; _lineHeightMap.push(acc); @@ -177,7 +171,7 @@ function buildMapInner(callback) { continue; } - var h = editor.heightAtLine(i + 1) - editor.heightAtLine(i); + const h = editor.heightAtLine(i + 1) - editor.heightAtLine(i); acc += Math.round(h / lineHeight); } _lineHeightMap.push(acc); @@ -191,10 +185,10 @@ function buildMapInner(callback) { // make the first line go top _scrollMap[0] = viewTop; - var parts = markdownArea.find('.part').toArray(); + const parts = markdownArea.find('.part').toArray(); for (i = 0; i < parts.length; i++) { - var $el = $(parts[i]), - t = $el.attr('data-startline') - 1; + const $el = $(parts[i]); + let t = $el.attr('data-startline') - 1; if (t === '') { return; } @@ -229,9 +223,9 @@ function buildMapInner(callback) { } // sync view scroll progress to edit -var viewScrollingTimer = null; +let viewScrollingTimer = null; -function syncScrollToEdit(event, preventAnimate) { +export function syncScrollToEdit(event, preventAnimate) { if (currentMode != modeType.both || !syncscroll || !editArea) return; if (preventSyncScrollToEdit) { if (typeof preventSyncScrollToEdit === 'number') { @@ -242,15 +236,15 @@ function syncScrollToEdit(event, preventAnimate) { return; } if (!scrollMap || !lineHeightMap) { - buildMap(function () { + buildMap(() => { syncScrollToEdit(event, preventAnimate); }); return; } if (editScrolling) return; - var scrollTop = viewArea[0].scrollTop; - var lineIndex = 0; + const scrollTop = viewArea[0].scrollTop; + let lineIndex = 0; for (var i = 0, l = scrollMap.length; i < l; i++) { if (scrollMap[i] > scrollTop) { break; @@ -258,8 +252,8 @@ function syncScrollToEdit(event, preventAnimate) { lineIndex = i; } } - var lineNo = 0; - var lineDiff = 0; + let lineNo = 0; + let lineDiff = 0; for (var i = 0, l = lineHeightMap.length; i < l; i++) { if (lineHeightMap[i] > lineIndex) { break; @@ -269,14 +263,14 @@ function syncScrollToEdit(event, preventAnimate) { } } - var posTo = 0; - var topDiffPercent = 0; - var posToNextDiff = 0; - var scrollInfo = editor.getScrollInfo(); - var textHeight = editor.defaultTextHeight(); - var preLastLineHeight = scrollInfo.height - scrollInfo.clientHeight - textHeight; - var preLastLineNo = Math.round(preLastLineHeight / textHeight); - var preLastLinePos = scrollMap[preLastLineNo]; + 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; @@ -293,7 +287,7 @@ function syncScrollToEdit(event, preventAnimate) { if (preventAnimate) { editArea.scrollTop(posTo); } else { - var posDiff = Math.abs(scrollInfo.top - posTo); + const posDiff = Math.abs(scrollInfo.top - posTo); var duration = posDiff / 50; duration = duration >= 100 ? duration : 100; editArea.stop(true, true).animate({ @@ -311,9 +305,9 @@ function viewScrollingTimeoutInner() { } // sync edit scroll progress to view -var editScrollingTimer = null; +let editScrollingTimer = null; -function syncScrollToView(event, preventAnimate) { +export function syncScrollToView(event, preventAnimate) { if (currentMode != modeType.both || !syncscroll || !viewArea) return; if (preventSyncScrollToView) { if (typeof preventSyncScrollToView === 'number') { @@ -324,20 +318,20 @@ function syncScrollToView(event, preventAnimate) { return; } if (!scrollMap || !lineHeightMap) { - buildMap(function () { + buildMap(() => { syncScrollToView(event, preventAnimate); }); return; } if (viewScrolling) return; - var lineNo, posTo; - var topDiffPercent, posToNextDiff; - var scrollInfo = editor.getScrollInfo(); - var textHeight = editor.defaultTextHeight(); + let lineNo, posTo; + let topDiffPercent, posToNextDiff; + const scrollInfo = editor.getScrollInfo(); + const textHeight = editor.defaultTextHeight(); lineNo = Math.floor(scrollInfo.top / textHeight); // if reach the last line, will start lerp to the bottom - var diffToBottom = (scrollInfo.top + scrollInfo.clientHeight) - (scrollInfo.height - textHeight); + const diffToBottom = (scrollInfo.top + scrollInfo.clientHeight) - (scrollInfo.height - textHeight); if (scrollInfo.height > scrollInfo.clientHeight && diffToBottom > 0) { topDiffPercent = diffToBottom / textHeight; posTo = scrollMap[lineNo + 1]; @@ -353,7 +347,7 @@ function syncScrollToView(event, preventAnimate) { if (preventAnimate) { viewArea.scrollTop(posTo); } else { - var posDiff = Math.abs(viewArea.scrollTop() - posTo); + const posDiff = Math.abs(viewArea.scrollTop() - posTo); var duration = posDiff / 50; duration = duration >= 100 ? duration : 100; viewArea.stop(true, true).animate({ @@ -369,10 +363,3 @@ function syncScrollToView(event, preventAnimate) { function editScrollingTimeoutInner() { editScrolling = false; } - -module.exports = { - setupSyncAreas: setupSyncAreas, - clearMap: clearMap, - syncScrollToEdit: syncScrollToEdit, - syncScrollToView: syncScrollToView -}; |