From d6ae7a36aeef3b5c261bb521f5e3f48898b65ede Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sat, 24 Dec 2016 11:09:07 +0800 Subject: Fix module variable require --- public/js/cover.js | 1 + public/js/index.js | 1 + 2 files changed, 2 insertions(+) diff --git a/public/js/cover.js b/public/js/cover.js index 2f35bd28..ee7d75e4 100644 --- a/public/js/cover.js +++ b/public/js/cover.js @@ -9,6 +9,7 @@ var urlpath = common.urlpath; var resetCheckAuth = common.resetCheckAuth; var getLoginState = common.getLoginState; var clearLoginState = common.clearLoginState; +var loginStateChangeEvent = common.loginStateChangeEvent; var historyModule = require('./history'); var parseStorageToHistory = historyModule.parseStorageToHistory; diff --git a/public/js/index.js b/public/js/index.js index 96580fe3..4a466245 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -29,6 +29,7 @@ var DROPBOX_APP_KEY = common.DROPBOX_APP_KEY; var noteurl = common.noteurl; var checkLoginStateChanged = common.checkLoginStateChanged; +var loginStateChangeEvent = common.loginStateChangeEvent; var extra = require('./extra'); var md = extra.md; -- cgit v1.2.3 From a06fad974e66c8c5854985fe12fbadbb43cc9c7e Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sat, 24 Dec 2016 11:10:18 +0800 Subject: Install vue and babel dependency --- .babelrc | 8 ++++++++ package.json | 7 +++++++ public/js/cover.js | 2 ++ webpackBaseConfig.js | 4 ++++ 4 files changed, 21 insertions(+) create mode 100644 .babelrc diff --git a/.babelrc b/.babelrc new file mode 100644 index 00000000..cbd3ac60 --- /dev/null +++ b/.babelrc @@ -0,0 +1,8 @@ +{ + "presets": [ + "es2015" + ], + "plugins": [ + "transform-runtime" + ] +} diff --git a/package.json b/package.json index 7c2441b9..5ac7f554 100644 --- a/package.json +++ b/package.json @@ -115,6 +115,7 @@ "velocity-animate": "^1.4.0", "visibilityjs": "^1.2.4", "viz.js": "^1.4.1", + "vue": "^2.1.6", "winston": "^2.3.0", "xss": "^0.3.2" }, @@ -139,6 +140,12 @@ "url": "https://github.com/hackmdio/hackmd.git" }, "devDependencies": { + "babel-cli": "^6.18.0", + "babel-core": "^6.21.0", + "babel-loader": "^6.2.10", + "babel-plugin-transform-runtime": "^6.15.0", + "babel-preset-es2015": "^6.18.0", + "babel-runtime": "^6.20.0", "copy-webpack-plugin": "^4.0.1", "css-loader": "^0.26.1", "ejs-loader": "^0.3.0", diff --git a/public/js/cover.js b/public/js/cover.js index ee7d75e4..4696203e 100644 --- a/public/js/cover.js +++ b/public/js/cover.js @@ -28,6 +28,8 @@ var saveAs = require('file-saver').saveAs; var List = require('list.js'); var S = require('string'); +import Vue from 'vue'; + var options = { valueNames: ['id', 'text', 'timestamp', 'fromNow', 'time', 'tags', 'pinned'], item: '
  • \ diff --git a/webpackBaseConfig.js b/webpackBaseConfig.js index 400db14b..5c715cc2 100644 --- a/webpackBaseConfig.js +++ b/webpackBaseConfig.js @@ -372,6 +372,10 @@ module.exports = { loaders: [{ test: /\.json$/, loader: 'json-loader' + }, { + test: /\.js$/, + loader: 'babel', + exclude: [/node_modules/, /public\/vendor/] }, { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') -- cgit v1.2.3 From 99dd10772422b66b7f98f1483b5fa3225e3e86e0 Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sat, 24 Dec 2016 11:50:57 +0800 Subject: Basic setup for Vue app --- .editorconfig | 4 ++++ package.json | 2 ++ public/js/components/HelloWorld.vue | 21 +++++++++++++++++++++ public/js/cover.js | 6 ++++++ public/js/views/Cover.vue | 15 +++++++++++++++ public/views/index.ejs | 1 + webpackBaseConfig.js | 8 +++++++- 7 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 public/js/components/HelloWorld.vue create mode 100644 public/js/views/Cover.vue diff --git a/.editorconfig b/.editorconfig index 619c178d..b3e30251 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,6 +7,10 @@ indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true +[*.vue] +indent_style = space +indent_size = 2 + [*.md] trim_trailing_whitespace = false diff --git a/package.json b/package.json index 5ac7f554..d44313cd 100644 --- a/package.json +++ b/package.json @@ -116,6 +116,7 @@ "visibilityjs": "^1.2.4", "viz.js": "^1.4.1", "vue": "^2.1.6", + "vue-loader": "^10.0.2", "winston": "^2.3.0", "xss": "^0.3.2" }, @@ -162,6 +163,7 @@ "script-loader": "^0.7.0", "style-loader": "^0.13.1", "url-loader": "^0.5.7", + "vue-template-compiler": "^2.1.6", "webpack": "^1.14.0" } } diff --git a/public/js/components/HelloWorld.vue b/public/js/components/HelloWorld.vue new file mode 100644 index 00000000..d8e3007f --- /dev/null +++ b/public/js/components/HelloWorld.vue @@ -0,0 +1,21 @@ + + + + + diff --git a/public/js/cover.js b/public/js/cover.js index 4696203e..b8886849 100644 --- a/public/js/cover.js +++ b/public/js/cover.js @@ -28,8 +28,14 @@ var saveAs = require('file-saver').saveAs; var List = require('list.js'); var S = require('string'); +import Cover from './views/Cover'; import Vue from 'vue'; +new Vue({ + el: '#cover-app', + render: (h) => h(Cover) +}) + var options = { valueNames: ['id', 'text', 'timestamp', 'fromNow', 'time', 'tags', 'pinned'], item: '
  • \ diff --git a/public/js/views/Cover.vue b/public/js/views/Cover.vue new file mode 100644 index 00000000..767d087f --- /dev/null +++ b/public/js/views/Cover.vue @@ -0,0 +1,15 @@ + + + diff --git a/public/views/index.ejs b/public/views/index.ejs index adcdd34d..5b84f4fc 100644 --- a/public/views/index.ejs +++ b/public/views/index.ejs @@ -30,6 +30,7 @@
    +
    diff --git a/webpackBaseConfig.js b/webpackBaseConfig.js index 5c715cc2..6c569c1e 100644 --- a/webpackBaseConfig.js +++ b/webpackBaseConfig.js @@ -338,7 +338,7 @@ module.exports = { path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules') ], - extensions: ["", ".js"], + extensions: ["", ".js", ".vue"], alias: { codemirror: path.join(__dirname, 'node_modules/codemirror/codemirror.min.js'), inlineAttachment: path.join(__dirname, 'public/vendor/inlineAttachment/inline-attachment.js'), @@ -372,6 +372,12 @@ module.exports = { loaders: [{ test: /\.json$/, loader: 'json-loader' + }, { + test: /\.vue$/, + loader: 'vue', + options: { + // vue-loader options go here + } }, { test: /\.js$/, loader: 'babel', -- cgit v1.2.3 From 78c51e5e88bcd4a3d53a87a53f8dc85d9a5a2df4 Mon Sep 17 00:00:00 2001 From: bananaappletw Date: Wed, 4 Jan 2017 14:27:38 +0800 Subject: Revert "Rename npm script" This reverts commit ed83dfc862768572eab0c2aed629b1700ac9e224. --- README.md | 2 +- bin/heroku | 2 +- package.json | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a2980ee4..cc05872d 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ Get started 2. Enter the directory and type `bin/setup`, which will install npm dependencies and create configs. The setup script is written in Bash, you would need bash as a prerequisite. 3. Setup the configs, see more below 4. Setup environment variables which will overwrite the configs -5. Build front-end bundle by `npm run build:prod` (use `npm run build:dev` if you are in development) +5. Build front-end bundle by `npm run build` (use `npm run dev` if you are in development) 6. Run the server as you like (node, forever, pm2) Upgrade guide diff --git a/bin/heroku b/bin/heroku index 6ee7fa41..e8010038 100755 --- a/bin/heroku +++ b/bin/heroku @@ -31,5 +31,5 @@ EOF cp public/js/config.js.example public/js/config.js # build app - npm run build:prod + npm run build fi diff --git a/package.json b/package.json index edf03649..dde6328b 100644 --- a/package.json +++ b/package.json @@ -5,8 +5,8 @@ "main": "app.js", "license": "MIT", "scripts": { - "build:dev": "webpack --config webpack.config.js --progress --colors --watch", - "build:prod": "webpack --config webpack.production.js --progress --colors", + "dev": "webpack --config webpack.config.js --progress --colors --watch", + "build": "webpack --config webpack.production.js --progress --colors", "postinstall": "bin/heroku", "start": "node app.js" }, -- cgit v1.2.3 From 781f495f3e04b863be58226b5af8e6ab94d9355a Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Wed, 4 Jan 2017 23:01:44 +0800 Subject: Convert synscroll to es6 --- public/js/index.js | 12 ++-- public/js/syncscroll.js | 169 ++++++++++++++++++++++-------------------------- 2 files changed, 85 insertions(+), 96 deletions(-) diff --git a/public/js/index.js b/public/js/index.js index 8921eda3..46dfffd9 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -51,11 +51,12 @@ 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; +import { + clearMap, + setupSyncAreas, + syncScrollToEdit, + syncScrollToView +} from './syncscroll'; var historyModule = require('./history'); var writeHistory = historyModule.writeHistory; @@ -3693,6 +3694,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) { 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('' - + highlighted - + '\n'; + const startline = tokens[idx].map[0] + 1; + const endline = tokens[idx].map[1]; + return `
    ${highlighted}
    \n`; } - return '
    '
    -        + highlighted
    -        + '
    \n'; + return `
    ${highlighted}
    \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 '
    ' + md.utils.escapeHtml(tokens[idx].content) + '
    \n'; + const startline = tokens[idx].map[0] + 1; + const endline = tokens[idx].map[1]; + return `
    ${md.utils.escapeHtml(tokens[idx].content)}
    \n`; } - return '
    ' + md.utils.escapeHtml(tokens[idx].content) + '
    \n'; + return `
    ${md.utils.escapeHtml(tokens[idx].content)}
    \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 -}; -- cgit v1.2.3 From eb5e7ba0d10cf559d73335102513b4c5783e239b Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Thu, 5 Jan 2017 16:17:28 +0800 Subject: Convert slide.js to es6 --- public/js/slide.js | 64 ++++++++++++++++++++++++++---------------------------- 1 file changed, 31 insertions(+), 33 deletions(-) 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'); -- cgit v1.2.3 From 45c202172ed293564925d10782ea65d415cb513c Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Thu, 5 Jan 2017 16:19:13 +0800 Subject: Convert pretty.js to es6 --- public/js/pretty.js | 87 ++++++++++++++++++++++++++--------------------------- 1 file changed, 43 insertions(+), 44 deletions(-) diff --git a/public/js/pretty.js b/public/js/pretty.js index c1a471a1..64d41c43 100644 --- a/public/js/pretty.js +++ b/public/js/pretty.js @@ -4,31 +4,33 @@ 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); +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 +48,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 +63,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 +93,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 +113,10 @@ function windowResize() { generateScrollspy(); } } -$(window).resize(function () { +$(window).resize(() => { windowResize(); }); -$(document).ready(function () { +$(document).ready(() => { windowResize(); generateScrollspy(); setTimeout(scrollToHash, 0); @@ -120,13 +124,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 +138,3 @@ function scrollToBottom() { window.scrollToTop = scrollToTop; window.scrollToBottom = scrollToBottom; - -module.exports = { - scrollToBottom: scrollToBottom, - scrollToTop: scrollToTop -} -- cgit v1.2.3 From 6a06c0bb9fea6d499d7fd2f7e6a65e16099cfb05 Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Thu, 5 Jan 2017 16:48:23 +0800 Subject: Convert common.js to es6 --- public/js/common.js | 107 +++++++++++++++++++++++++--------------------------- public/js/index.js | 28 +++++++------- 2 files changed, 65 insertions(+), 70 deletions(-) diff --git a/public/js/common.js b/public/js/common.js index f5bfc8ec..6d54b450 100644 --- a/public/js/common.js +++ b/public/js/common.js @@ -1,30 +1,37 @@ -var config = require('./config'); -var domain = config.domain; // domain name -var urlpath = config.urlpath; // sub url path, like: www.example.com/ -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; +// import config from './config'; + +import { + domain, // domain name + urlpath, // sub url path, like: www.example.com/ + debug, + GOOGLE_API_KEY, + GOOGLE_CLIENT_ID, + DROPBOX_APP_KEY +} from './config'; //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; +export const port = window.location.port; +window.serverurl = `${window.location.protocol}//${domain ? domain : window.location.hostname}${port ? ':' + port : ''}${urlpath ? '/' + urlpath : ''}`; +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'; -var version = '0.5.0'; +let checkAuth = false; +let profile = null; +let lastLoginState = getLoginState(); +let lastUserId = getUserId(); +let loginStateChangeEvent = null; -var checkAuth = false; -var profile = null; -var lastLoginState = getLoginState(); -var lastUserId = getUserId(); -var loginStateChangeEvent = null; +export function setloginStateChangeEvent(func) { + loginStateChangeEvent = func; +} -function resetCheckAuth() { +export function resetCheckAuth() { checkAuth = false; } -function setLoginState(bool, id) { +export function setLoginState(bool, id) { Cookies.set('loginstate', bool, { expires: 365 }); @@ -40,36 +47,37 @@ function setLoginState(bool, id) { checkLoginStateChanged(); } -function checkLoginStateChanged() { +export function checkLoginStateChanged() { if (getLoginState() != lastLoginState || getUserId() != lastUserId) { - if(loginStateChangeEvent) + if(loginStateChangeEvent) { loginStateChangeEvent(); + } return true; } else { return false; } } -function getLoginState() { - var state = Cookies.get('loginstate'); +export function getLoginState() { + const state = Cookies.get('loginstate'); return state === "true" || state === true; } -function getUserId() { +export function getUserId() { return Cookies.get('userid'); } -function clearLoginState() { +export function clearLoginState() { Cookies.remove('loginstate'); } -function checkIfAuth(yesCallback, noCallback) { - var cookieLoginState = getLoginState(); +export function checkIfAuth(yesCallback, noCallback) { + const cookieLoginState = getLoginState(); if (checkLoginStateChanged()) checkAuth = false; if (!checkAuth || typeof cookieLoginState == 'undefined') { - $.get(serverurl + '/me') - .done(function (data) { + $.get(`${serverurl}/me`) + .done(data => { if (data && data.status == 'ok') { profile = data; yesCallback(profile); @@ -79,10 +87,10 @@ function checkIfAuth(yesCallback, noCallback) { setLoginState(false); } }) - .fail(function () { + .fail(() => { noCallback(); }) - .always(function () { + .always(() => { checkAuth = true; }); } else if (cookieLoginState) { @@ -92,29 +100,16 @@ function checkIfAuth(yesCallback, 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, - loginStateChangeEvent: loginStateChangeEvent, - - /* export functions */ - resetCheckAuth: resetCheckAuth, - setLoginState: setLoginState, - checkLoginStateChanged: checkLoginStateChanged, - getLoginState: getLoginState, - getUserId: getUserId, - clearLoginState: clearLoginState, - checkIfAuth: checkIfAuth +export default { + domain, + urlpath, + debug, + GOOGLE_API_KEY, + GOOGLE_CLIENT_ID, + DROPBOX_APP_KEY, + checkAuth, + profile, + lastLoginState, + lastUserId, + loginStateChangeEvent }; diff --git a/public/js/index.js b/public/js/index.js index 46dfffd9..381f051e 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -17,18 +17,18 @@ 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 loginStateChangeEvent = common.loginStateChangeEvent; +import { + checkLoginStateChanged, + setloginStateChangeEvent, + debug, + DROPBOX_APP_KEY, + GOOGLE_API_KEY, + GOOGLE_CLIENT_ID, + noteid, + noteurl, + urlpath, + version +} from './common'; var extra = require('./extra'); var md = extra.md; @@ -963,10 +963,10 @@ function setNeedRefresh() { showStatus(statusType.offline); } -loginStateChangeEvent = function () { +setloginStateChangeEvent(function () { setRefreshModal('user-state-changed'); setNeedRefresh(); -}; +}); //visibility var wasFocus = false; -- cgit v1.2.3 From 47d7ff25617ba60790dd2018df56778eaa9bffdb Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Thu, 5 Jan 2017 17:52:32 +0800 Subject: Convert extra.js to es6 --- public/js/extra.js | 637 +++++++++++++++++++++++++---------------------------- public/js/index.js | 41 ++-- 2 files changed, 326 insertions(+), 352 deletions(-) diff --git a/public/js/extra.js b/public/js/extra.js index ba61a669..f1681b2e 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('./common'); require('../vendor/md-toc'); //auto update last change @@ -21,9 +23,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) { @@ -31,7 +34,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')); } @@ -40,13 +43,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 { @@ -58,12 +62,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(); @@ -75,11 +80,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 { @@ -90,8 +95,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 { @@ -101,8 +106,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'; } @@ -110,29 +115,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; @@ -145,13 +150,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 @@ -165,12 +170,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; @@ -210,13 +215,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"); @@ -231,35 +236,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*/, '') - .replace(/^\s*\[x\]\s*/, ''); - lis[i].setAttribute('class', 'task-list-item'); + li.innerHTML = html.replace(/^\s*\[ \]\s*/, ``) + .replace(/^\s*\[x\]\s*/, ``); + 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 () { @@ -270,41 +276,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 = ''; + success(data) { + const thumbnail_src = data[0].thumbnail_large; + const image = ``; $(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(); @@ -312,13 +318,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, @@ -335,14 +341,14 @@ function finishView(view) { } }); //graphviz - var Viz = require("viz.js"); - var graphvizs = view.find("div.graphviz.raw").removeClass("raw"); - graphvizs.each(function (key, value) { + const Viz = require("viz.js"); + const graphvizs = view.find("div.graphviz.raw").removeClass("raw"); + graphvizs.each((key, value) => { try { var $value = $(value); - var $ele = $(value).parent().parent(); + const $ele = $(value).parent().parent(); - var graphviz = Viz($value.text()); + const graphviz = Viz($value.text()); if (!graphviz) throw Error('viz.js output empty graph'); $value.html(graphviz); @@ -354,14 +360,14 @@ function finishView(view) { } }); //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; }; @@ -379,44 +385,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 = $('
    ').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 = $('
    ').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(); } @@ -424,31 +430,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 = $('
    ').append(iframe); - var height = iframe.attr('height'); - var width = iframe.attr('width'); + iframe.attr('src', `https:${src}`); + const inner = $('
    ').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(); } @@ -457,8 +463,8 @@ function finishView(view) { //pdf view.find("div.pdf.raw").removeClass("raw") .each(function (key, value) { - var url = $(value).attr('data-pdfurl'); - var inner = $('
    '); + const url = $(value).attr('data-pdfurl'); + const inner = $('
    '); $(this).append(inner); PDFObject.embed(url, inner, { height: '400px' @@ -466,12 +472,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) { @@ -490,8 +496,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); @@ -502,7 +508,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]); @@ -519,16 +525,16 @@ function finishView(view) { } //only static transform should be here -function postProcess(code) { - var result = $('
    ' + code + '
    '); +export function postProcess(code) { + const result = $(`
    ${code}
    `); //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); }); } @@ -538,8 +544,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'); @@ -550,24 +556,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 = $(''); + const iframe = $(''); iframe.attr('src', url + id); iframe.attr('style', style); $(value).html(iframe); @@ -576,45 +582,44 @@ 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); } -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); @@ -624,17 +629,16 @@ function exportToHTML(view) { //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); } @@ -642,16 +646,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 @@ -667,11 +671,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'); @@ -682,8 +686,8 @@ function checkExpandToggle() { } //toc -function generateToc(id) { - var target = $('#' + id); +export function generateToc(id) { + const target = $(`#${id}`); target.html(''); new Toc('doc', { 'level': 3, @@ -695,25 +699,25 @@ function generateToc(id) { }); if (target.text() == 'undefined') target.html(''); - var tocMenu = $('
    Expand all'); - var backtotop = $('Back to top'); - var gotobottom = $('Go to bottom'); + const tocMenu = $('
    Expand all'); + const backtotop = $('Back to top'); + const gotobottom = $('Go to bottom'); 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) @@ -725,18 +729,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 @@ -744,7 +748,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; @@ -757,29 +761,29 @@ function smoothHashScroll() { function imgPlayiframe(element, src) { if (!$(element).attr("data-videoid")) return; - var iframe = $(""); - $(iframe).attr("src", src + $(element).attr("data-videoid") + '?autoplay=1'); + const 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 = ""; 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 (const header of headers) { 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); @@ -787,49 +791,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('> .header-link'); + $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, @@ -844,8 +848,8 @@ function renderTOC(view) { } } -function scrollToHash() { - var hash = location.hash; +export function scrollToHash() { + const hash = location.hash; location.hash = ""; location.hash = hash; } @@ -855,39 +859,39 @@ function highlightRender(code, lang) { return; code = S(code).escapeHTML().s if (lang == 'sequence') { - return '
    ' + code + '
    '; + return `
    ${code}
    `; } else if (lang == 'flow') { - return '
    ' + code + '
    '; + return `
    ${code}
    `; } else if (lang == 'graphviz') { - return '
    ' + code + '
    '; + return `
    ${code}
    `; } else if (lang == 'mermaid') { - return '
    ' + code + '
    '; + return `
    ${code}
    `; } - 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] = ""; + const lines = result.value.split('\n'); + const linenumbers = []; + for (let i = 0; i < lines.length - 1; i++) { + linenumbers[i] = ``; } - var continuelinenumber = /\=\+$/.test(lang); - var linegutter = "
    " + linenumbers.join('\n') + "
    "; - result.value = "
    " + linegutter + "
    " + result.value + "
    "; + const continuelinenumber = /\=\+$/.test(lang); + const linegutter = `
    ${linenumbers.join('\n')}
    `; + result.value = `
    ${linegutter}
    ${result.value}
    `; } 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: "", @@ -923,19 +927,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 }); @@ -944,25 +946,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]; @@ -979,110 +981,99 @@ md.renderer.rules.fence = function (tokens, idx, options, env, self) { } if (highlighted.indexOf('' - + highlighted - + '\n'; + return `
    ${highlighted}
    \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 = $('
    '); + const div = $('
    '); div.attr('data-videoid', videoid); - var thumbnail_src = '//img.youtube.com/vi/' + videoid + '/hqdefault.jpg'; - var image = ''; + const thumbnail_src = `//img.youtube.com/vi/${videoid}/hqdefault.jpg`; + const image = ``; div.append(image); - var icon = ''; + const icon = ''; 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 = $('
    '); + const div = $('
    '); div.attr('data-videoid', videoid); - var icon = ''; + const icon = ''; 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 = ''; + (match, utils) => { + const gistid = match[1]; + const code = ``; 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 '
    '; - } + (match, utils) => '
    ' ); //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 = $('
    '); + (match, utils) => { + const slideshareid = match[1]; + const 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 = $('
    '); + (match, utils) => { + const speakerdeckid = match[1]; + const 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 = $('
    '); + const div = $('
    '); div.attr('data-pdfurl', pdfurl); return div[0].outerHTML; } @@ -1090,8 +1081,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); } @@ -1100,9 +1091,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); @@ -1138,24 +1129,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/index.js b/public/js/index.js index 381f051e..7406c9a2 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -30,26 +30,27 @@ import { version } from './common'; -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; +import { + autoLinkify, + deduplicatedHeaderId, + exportToHTML, + exportToRawHTML, + finishView, + generateToc, + isValidURL, + md, + parseMeta, + postProcess, + renderFilename, + renderTOC, + renderTags, + renderTitle, + scrollToHash, + smoothHashScroll, + updateLastChange, + updateLastChangeUser, + updateOwner +} from './extra'; import { clearMap, -- cgit v1.2.3 From 71aece74292e9764e6dc20ebe84f211099d6076d Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Thu, 5 Jan 2017 18:10:55 +0800 Subject: Convert cover.js to es6 --- public/js/cover.js | 253 +++++++++++++++++++++++++++-------------------------- 1 file changed, 127 insertions(+), 126 deletions(-) diff --git a/public/js/cover.js b/public/js/cover.js index b8886849..ecb385ed 100644 --- a/public/js/cover.js +++ b/public/js/cover.js @@ -3,30 +3,30 @@ 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 loginStateChangeEvent = common.loginStateChangeEvent; - -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'); +import { + checkIfAuth, + clearLoginState, + getLoginState, + resetCheckAuth, + setloginStateChangeEvent +} from './common'; + +import historyModule from './history'; +const parseStorageToHistory = historyModule.parseStorageToHistory; +const parseHistory = historyModule.parseHistory; +const getStorageHistory = historyModule.getStorageHistory; +const getHistory = historyModule.getHistory; +const saveHistory = historyModule.saveHistory; +const removeHistory = historyModule.removeHistory; +const postHistoryToServer = historyModule.postHistoryToServer; +const deleteServerHistory = historyModule.deleteServerHistory; +const parseServerToHistory = historyModule.parseServerToHistory; +const saveStorageHistoryToServer = historyModule.saveStorageHistoryToServer; +const clearDuplicatedHistory = historyModule.clearDuplicatedHistory; + +import {saveAs} from 'file-saver'; +import List from 'list.js'; +import S from 'string'; import Cover from './views/Cover'; import Vue from 'vue'; @@ -36,13 +36,13 @@ new Vue({ render: (h) => h(Cover) }) -var options = { +const options = { valueNames: ['id', 'text', 'timestamp', 'fromNow', 'time', 'tags', 'pinned'], item: '
  • \ \ \
    \ -
    \ +
    \
    \
    \

    \ @@ -64,15 +64,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(); @@ -83,7 +84,7 @@ function pageInit() { $(".ui-history").click(); parseServerToHistory(historyList, parseHistoryCallback); }, - function () { + () => { $('.ui-signin').show(); $('.ui-or').show(); $('.ui-welcome').hide(); @@ -100,14 +101,14 @@ $(".masthead-nav li").click(function () { $(this).addClass("active"); }); -$(".ui-home").click(function () { +$(".ui-home").click(() => { if (!$("#home").is(':visible')) { $(".section:visible").hide(); $("#home").fadeIn(); } }); -$(".ui-history").click(function () { +$(".ui-history").click(() => { if (!$("#history").is(':visible')) { $(".section:visible").hide(); $("#history").fadeIn(); @@ -120,7 +121,7 @@ function checkHistoryList() { $(".ui-import-from-browser").hide(); } else if ($("#history-list").children().length == 0) { $(".ui-nohistory").slideDown(); - getStorageHistory(function (data) { + getStorageHistory(data => { if (data && data.length > 0 && getLoginState() && historyList.items.length == 0) { $(".ui-import-from-browser").slideDown(); } @@ -130,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]); @@ -169,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'); @@ -187,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("" + tags[j] + ""); + labels.push(`${tags[j]}`); } tagsEl.html(labels.join(' ')); } @@ -206,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(' ' + value.text + '
    ' + value.time); + $('.ui-delete-modal-item').html(` ${value.text}
    ${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; @@ -228,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'); @@ -239,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; @@ -260,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()); } } @@ -272,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(); @@ -287,7 +288,7 @@ function deleteHistory() { deleteId = null; clearHistory = false; }); - }, function () { + }, () => { if (clearHistory) { saveHistory([]); historyList.clear(); @@ -295,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(); @@ -308,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')}`); }); }); -$(".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); @@ -347,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'); @@ -366,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'); @@ -378,16 +379,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 }; @@ -397,7 +398,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 @@ -405,17 +406,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; } @@ -428,6 +429,6 @@ $(".ui-use-tags").on('change', function () { checkHistoryList(); }); -$('.search').keyup(function () { +$('.search').keyup(() => { checkHistoryList(); }); -- cgit v1.2.3 From fce08cc164bb1ecc6b986fe6630381b630a1508c Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Thu, 5 Jan 2017 20:56:16 +0800 Subject: Convert history.js to es6 --- public/js/cover.js | 29 ++++---- public/js/history.js | 204 +++++++++++++++++++++++---------------------------- public/js/index.js | 13 ++-- 3 files changed, 113 insertions(+), 133 deletions(-) diff --git a/public/js/cover.js b/public/js/cover.js index ecb385ed..677d82eb 100644 --- a/public/js/cover.js +++ b/public/js/cover.js @@ -11,20 +11,21 @@ import { setloginStateChangeEvent } from './common'; -import historyModule from './history'; -const parseStorageToHistory = historyModule.parseStorageToHistory; -const parseHistory = historyModule.parseHistory; -const getStorageHistory = historyModule.getStorageHistory; -const getHistory = historyModule.getHistory; -const saveHistory = historyModule.saveHistory; -const removeHistory = historyModule.removeHistory; -const postHistoryToServer = historyModule.postHistoryToServer; -const deleteServerHistory = historyModule.deleteServerHistory; -const parseServerToHistory = historyModule.parseServerToHistory; -const saveStorageHistoryToServer = historyModule.saveStorageHistoryToServer; -const clearDuplicatedHistory = historyModule.clearDuplicatedHistory; - -import {saveAs} from 'file-saver'; +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'; diff --git a/public/js/history.js b/public/js/history.js index 6972f24c..f1201683 100644 --- a/public/js/history.js +++ b/public/js/history.js @@ -1,10 +1,9 @@ -var store = require('store'); -var S = require('string'); - -var common = require('./common'); -var checkIfAuth = common.checkIfAuth; -var urlpath = common.urlpath; -var getLoginState = common.getLoginState; +import store from 'store'; +import S from 'string'; +import { + checkIfAuth, + urlpath +} from './common'; window.migrateHistoryFromTempCallback = null; @@ -12,22 +11,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 +39,12 @@ function migrateHistoryFromTemp() { } } -function saveHistory(notehistory) { +export function saveHistory(notehistory) { checkIfAuth( - function () { + () => { saveHistoryToServer(notehistory); }, - function () { + () => { saveHistoryToStorage(notehistory); } ); @@ -65,7 +64,7 @@ function saveHistoryToCookie(notehistory) { } function saveHistoryToServer(notehistory) { - $.post(serverurl + '/history', { + $.post(`${serverurl}/history`, { history: JSON.stringify(notehistory) }); } @@ -75,37 +74,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 +122,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 +170,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 +187,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 +203,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 +211,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 +242,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 +269,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 +283,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 +329,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 +346,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 7406c9a2..660f73e4 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -59,12 +59,13 @@ import { syncScrollToView } from './syncscroll'; -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 { + writeHistory, + deleteServerHistory, + getHistory, + saveHistory, + removeHistory +} from './history'; var renderer = require('./render'); var preventXSS = renderer.preventXSS; -- cgit v1.2.3 From c2a8911b9c7872ea0d085020aa17e82162130f3d Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Fri, 13 Jan 2017 22:46:38 +0800 Subject: Move config variable to lib/config --- public/js/common.js | 25 +------------------------ public/js/lib/config/index.js | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 24 deletions(-) create mode 100644 public/js/lib/config/index.js diff --git a/public/js/common.js b/public/js/common.js index 6d54b450..9a60122b 100644 --- a/public/js/common.js +++ b/public/js/common.js @@ -1,21 +1,4 @@ -// import config from './config'; - -import { - domain, // domain name - urlpath, // sub url path, like: www.example.com/ - debug, - GOOGLE_API_KEY, - GOOGLE_CLIENT_ID, - DROPBOX_APP_KEY -} from './config'; - -//common -export const port = window.location.port; -window.serverurl = `${window.location.protocol}//${domain ? domain : window.location.hostname}${port ? ':' + port : ''}${urlpath ? '/' + urlpath : ''}`; -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'; +import { serverurl } from './lib/config'; let checkAuth = false; let profile = null; @@ -101,12 +84,6 @@ export function checkIfAuth(yesCallback, noCallback) { } export default { - domain, - urlpath, - debug, - GOOGLE_API_KEY, - GOOGLE_CLIENT_ID, - DROPBOX_APP_KEY, checkAuth, profile, lastLoginState, diff --git a/public/js/lib/config/index.js b/public/js/lib/config/index.js new file mode 100644 index 00000000..bffbadd9 --- /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; +export const urlpath = config.urlpath; +export const debug = config.debug; + +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'; -- cgit v1.2.3 From 0fca629c34b83617b2d72e42aa0edb66fd2e71f6 Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Fri, 13 Jan 2017 22:51:44 +0800 Subject: Rename common.js to login.js --- public/js/common.js | 92 ------------------------------------------- public/js/cover.js | 2 +- public/js/extra.js | 2 +- public/js/history.js | 8 +++- public/js/index.js | 7 +++- public/js/lib/common/login.js | 92 +++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 105 insertions(+), 98 deletions(-) delete mode 100644 public/js/common.js create mode 100644 public/js/lib/common/login.js diff --git a/public/js/common.js b/public/js/common.js deleted file mode 100644 index 9a60122b..00000000 --- a/public/js/common.js +++ /dev/null @@ -1,92 +0,0 @@ -import { serverurl } from './lib/config'; - -let checkAuth = false; -let profile = null; -let lastLoginState = getLoginState(); -let lastUserId = getUserId(); -let 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) { - loginStateChangeEvent(); - } - 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/cover.js b/public/js/cover.js index 677d82eb..bc04923b 100644 --- a/public/js/cover.js +++ b/public/js/cover.js @@ -9,7 +9,7 @@ import { getLoginState, resetCheckAuth, setloginStateChangeEvent -} from './common'; +} from './lib/common/login'; import { clearDuplicatedHistory, diff --git a/public/js/extra.js b/public/js/extra.js index 6cfb5b0a..b651d9e6 100644 --- a/public/js/extra.js +++ b/public/js/extra.js @@ -11,7 +11,7 @@ import PDFObject from 'pdfobject'; import S from 'string'; import { saveAs } from 'file-saver'; -require('./common'); +require('./lib/common/login'); require('../vendor/md-toc'); var Viz = require("viz.js"); diff --git a/public/js/history.js b/public/js/history.js index f1201683..34b2cba7 100644 --- a/public/js/history.js +++ b/public/js/history.js @@ -1,9 +1,13 @@ import store from 'store'; import S from 'string'; + +import { + checkIfAuth +} from './lib/common/login'; + import { - checkIfAuth, urlpath -} from './common'; +} from './lib/config'; window.migrateHistoryFromTempCallback = null; diff --git a/public/js/index.js b/public/js/index.js index 660f73e4..3bf42ad4 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -19,7 +19,10 @@ var List = require('list.js'); import { checkLoginStateChanged, - setloginStateChangeEvent, + setloginStateChangeEvent +} from './lib/common/login'; + +import { debug, DROPBOX_APP_KEY, GOOGLE_API_KEY, @@ -28,7 +31,7 @@ import { noteurl, urlpath, version -} from './common'; +} from './lib/config'; import { autoLinkify, diff --git a/public/js/lib/common/login.js b/public/js/lib/common/login.js new file mode 100644 index 00000000..12cc41fc --- /dev/null +++ b/public/js/lib/common/login.js @@ -0,0 +1,92 @@ +import { serverurl } from '../config'; + +let checkAuth = false; +let profile = null; +let lastLoginState = getLoginState(); +let lastUserId = getUserId(); +let 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) { + loginStateChangeEvent(); + } + 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 +}; -- cgit v1.2.3 From 2408ff4ba96c929a575b34e85d5cff0a01789ca4 Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Fri, 13 Jan 2017 23:12:17 +0800 Subject: Add default value for config --- public/js/lib/config/index.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/public/js/lib/config/index.js b/public/js/lib/config/index.js index bffbadd9..2b73679f 100644 --- a/public/js/lib/config/index.js +++ b/public/js/lib/config/index.js @@ -2,13 +2,13 @@ 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 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; -export const urlpath = config.urlpath; -export const debug = config.debug; +export const domain = config.domain || ''; // domain name +export const urlpath = config.urlpath || ''; // sub url path, like: www.example.com/ +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 : ''}`; -- cgit v1.2.3 From a541569d7edbe827cae69c666079d5d1ded6790c Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Fri, 13 Jan 2017 23:12:27 +0800 Subject: Remove old config.js.example --- public/js/config.js.example | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 public/js/config.js.example 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/ - - // settings - debug: false, - - GOOGLE_API_KEY: '', - GOOGLE_CLIENT_ID: '', - DROPBOX_APP_KEY: '' -}; -- cgit v1.2.3 From 1ed19966394b9735c348ec0116ec0e939c363ce6 Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Fri, 13 Jan 2017 23:37:16 +0800 Subject: Remove config.js from setup files --- .gitignore | 1 - bin/heroku | 2 -- bin/setup | 4 ---- 3 files changed, 7 deletions(-) diff --git a/.gitignore b/.gitignore index f48b3c6f..ab83c145 100644 --- a/.gitignore +++ b/.gitignore @@ -18,7 +18,6 @@ backups/ # ignore config files config.json -public/js/config.js .sequelizerc # ignore webpack build diff --git a/bin/heroku b/bin/heroku index e8010038..1228b283 100755 --- a/bin/heroku +++ b/bin/heroku @@ -28,8 +28,6 @@ EOF EOF - cp public/js/config.js.example public/js/config.js - # build app npm run build fi diff --git a/bin/setup b/bin/setup index e24d4de7..6724b2d5 100755 --- a/bin/setup +++ b/bin/setup @@ -21,10 +21,6 @@ if [ ! -f config.json ]; then cp config.json.example config.json fi -if [ ! -f publis/js/config.js ]; then - cp public/js/config.js.example public/js/config.js -fi - if [ ! -f .sequelizerc ]; then cp .sequelizerc.example .sequelizerc fi -- cgit v1.2.3 From b4bed37d64d59a70db3f0373894cf6ac611c1630 Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sat, 14 Jan 2017 14:17:20 +0800 Subject: Add google apiKey & dropbox appKey to config.json --- config.json.example | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/config.json.example b/config.json.example index e5e3fc56..e980566f 100644 --- a/config.json.example +++ b/config.json.example @@ -45,11 +45,13 @@ }, "dropbox": { "clientID": "change this", - "clientSecret": "change this" + "clientSecret": "change this", + "appKey": "change this" }, "google": { "clientID": "change this", - "clientSecret": "change this" + "clientSecret": "change this", + "apiKey": "change this" }, "imgur": { "clientID": "change this" -- cgit v1.2.3 From 98c0cfc6a7dbf19a7996ff37968605ec946c97e1 Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sat, 14 Jan 2017 15:24:31 +0800 Subject: Update README --- README.md | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index cc05872d..f6532d5e 100644 --- a/README.md +++ b/README.md @@ -97,19 +97,9 @@ Configuration files There are some configs you need to change in the files below ``` -./config.json --- for server settings -./public/js/config.js --- for client settings +./config.json ----application settings ``` -Client settings `config.js` ---- - -| variables | example values | description | -| --------- | ------ | ----------- | -| debug | `true` or `false` | set debug mode, show more logs | -| domain | `localhost` | domain name | -| urlpath | `hackmd` | sub url path, like: `www.example.com/` | - Environment variables (will overwrite other server configs) --- @@ -148,7 +138,7 @@ Environment variables (will overwrite other server configs) | HMD_S3_REGION | `ap-northeast-1` | AWS S3 region | | HMD_S3_BUCKET | no example | AWS S3 bucket name | -Server settings `config.json` +Application settings `config.json` --- | variables | example values | description | @@ -196,7 +186,7 @@ Third-party integration api key settings | ------- | --------- | ----------- | | facebook, twitter, github, gitlab, dropbox, google | environment variables or `config.json` | for signin | | imgur | environment variables or `config.json` | for image upload | -| google drive, dropbox | `public/js/config.js` | for export and import | +| google drive(`google/apiKey`, `google/clientID`), dropbox(`dropbox/appKey`) | `config.json` | for export and import | Third-party integration oauth callback urls --- -- cgit v1.2.3 From 77994508e66bc9fa1bde547d83e50d92aa5e1d88 Mon Sep 17 00:00:00 2001 From: bananaappletw Date: Sat, 14 Jan 2017 15:27:24 +0800 Subject: Update README.md for npm script --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 92557cf4..e2ab06a7 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ If you are upgrading HackMD from an older version, follow these steps: 1. Fully stop your old server first (important) 2. `git pull` or do whatever that updates the files 3. `npm install` to update dependencies -4. Build front-end bundle by `npm run build:prod` (use `npm run build:dev` if you are in development) +4. Build front-end bundle by `npm run build` (use `npm run dev` if you are in development) 5. Modify the file named `.sequelizerc`, change the value of the variable `url` with your db connection string For example: `postgres://username:password@localhost:5432/hackmd` 6. Run `node_modules/.bin/sequelize db:migrate`, this step will migrate your db to the latest schema -- cgit v1.2.3 From 04292240d6a589c537afb8e9838dcc0f062d0f2c Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sat, 14 Jan 2017 15:47:13 +0800 Subject: Minor style update --- .eslintrc | 5 ++--- public/js/lib/common/login.js | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.eslintrc b/.eslintrc index 53a6dcb0..bd14731c 100644 --- a/.eslintrc +++ b/.eslintrc @@ -16,7 +16,6 @@ ], "array-callback-return": "error", "arrow-body-style": "error", - "arrow-parens": "error", "arrow-spacing": "error", "block-scoped-var": "off", "block-spacing": "error", @@ -123,7 +122,7 @@ "no-extend-native": "error", "no-extra-bind": "error", "no-extra-label": "error", - "no-extra-parens": "error", + "no-extra-parens": "warn", "no-floating-decimal": "error", "no-global-assign": "error", "no-implicit-coercion": "error", @@ -195,7 +194,7 @@ "no-unneeded-ternary": "error", "no-unsafe-negation": "error", "no-unused-expressions": "error", - "no-use-before-define": "error", + "no-use-before-define": "warn", "no-useless-call": "error", "no-useless-computed-key": "error", "no-useless-concat": "error", diff --git a/public/js/lib/common/login.js b/public/js/lib/common/login.js index 12cc41fc..f1a03c72 100644 --- a/public/js/lib/common/login.js +++ b/public/js/lib/common/login.js @@ -32,7 +32,7 @@ export function setLoginState(bool, id) { export function checkLoginStateChanged() { if (getLoginState() != lastLoginState || getUserId() != lastUserId) { - if(loginStateChangeEvent) { + if (loginStateChangeEvent) { loginStateChangeEvent(); } return true; -- cgit v1.2.3 From 0f833f099f61b93e76a5f32175580fc2c0b9dc1a Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sat, 14 Jan 2017 19:05:54 +0800 Subject: Update server google/dropbox config check --- lib/config.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/config.js b/lib/config.js index 53497f1f..c0a7fffe 100644 --- a/lib/config.js +++ b/lib/config.js @@ -90,11 +90,11 @@ var gitlab = (process.env.HMD_GITLAB_CLIENTID && process.env.HMD_GITLAB_CLIENTSE var dropbox = (process.env.HMD_DROPBOX_CLIENTID && process.env.HMD_DROPBOX_CLIENTSECRET) ? { clientID: process.env.HMD_DROPBOX_CLIENTID, clientSecret: process.env.HMD_DROPBOX_CLIENTSECRET -} : config.dropbox || false; +} : (config.dropbox && config.dropbox.clientID && config.dropbox.clientSecret) || false; var google = (process.env.HMD_GOOGLE_CLIENTID && process.env.HMD_GOOGLE_CLIENTSECRET) ? { clientID: process.env.HMD_GOOGLE_CLIENTID, clientSecret: process.env.HMD_GOOGLE_CLIENTSECRET -} : config.google || false; +} : (config.google && config.google.clientID && config.google.clientSecret) || false; var imgur = process.env.HMD_IMGUR_CLIENTID || config.imgur || false; var email = process.env.HMD_EMAIL ? (process.env.HMD_EMAIL === 'true') : !!config.email; -- cgit v1.2.3 From a9a38c3d75b1cf467bb3b4484abfc09dcbcea107 Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sun, 15 Jan 2017 11:58:00 +0800 Subject: Recover config change in 0f833f0 --- lib/config.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/config.js b/lib/config.js index 84f6b3d7..3816017e 100644 --- a/lib/config.js +++ b/lib/config.js @@ -90,11 +90,11 @@ var gitlab = (process.env.HMD_GITLAB_CLIENTID && process.env.HMD_GITLAB_CLIENTSE var dropbox = (process.env.HMD_DROPBOX_CLIENTID && process.env.HMD_DROPBOX_CLIENTSECRET) ? { clientID: process.env.HMD_DROPBOX_CLIENTID, clientSecret: process.env.HMD_DROPBOX_CLIENTSECRET -} : (config.dropbox && config.dropbox.clientID && config.dropbox.clientSecret) || false; +} : (config.dropbox && config.dropbox.clientID && config.dropbox.clientSecret && config.dropbox) || false; var google = (process.env.HMD_GOOGLE_CLIENTID && process.env.HMD_GOOGLE_CLIENTSECRET) ? { clientID: process.env.HMD_GOOGLE_CLIENTID, clientSecret: process.env.HMD_GOOGLE_CLIENTSECRET -} : (config.google && config.google.clientID && config.google.clientSecret) || false; +} : (config.google && config.google.clientID && config.google.clientSecret && config.google) || false; var ldap = config.ldap || ( process.env.HMD_LDAP_URL || process.env.HMD_LDAP_BINDDN || -- cgit v1.2.3 From 26d8942852f8d216d03138a6c3c1d350e6bc903e Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sat, 21 Jan 2017 12:24:58 +0800 Subject: Revert experimental vue for now --- .editorconfig | 4 ---- package.json | 3 --- public/js/components/HelloWorld.vue | 21 --------------------- public/js/cover.js | 8 -------- public/js/views/Cover.vue | 15 --------------- public/views/index.ejs | 2 -- webpackBaseConfig.js | 8 +------- 7 files changed, 1 insertion(+), 60 deletions(-) delete mode 100644 public/js/components/HelloWorld.vue delete mode 100644 public/js/views/Cover.vue diff --git a/.editorconfig b/.editorconfig index b3e30251..619c178d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,10 +7,6 @@ indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true -[*.vue] -indent_style = space -indent_size = 2 - [*.md] trim_trailing_whitespace = false diff --git a/package.json b/package.json index e22f9e73..1ed81c98 100644 --- a/package.json +++ b/package.json @@ -116,8 +116,6 @@ "velocity-animate": "^1.4.0", "visibilityjs": "^1.2.4", "viz.js": "^1.4.1", - "vue": "^2.1.6", - "vue-loader": "^10.0.2", "winston": "^2.3.0", "xss": "^0.3.3" }, @@ -164,7 +162,6 @@ "script-loader": "^0.7.0", "style-loader": "^0.13.1", "url-loader": "^0.5.7", - "vue-template-compiler": "^2.1.6", "webpack": "^1.14.0" } } diff --git a/public/js/components/HelloWorld.vue b/public/js/components/HelloWorld.vue deleted file mode 100644 index d8e3007f..00000000 --- a/public/js/components/HelloWorld.vue +++ /dev/null @@ -1,21 +0,0 @@ - - - - - diff --git a/public/js/cover.js b/public/js/cover.js index 79b168d9..830564e8 100644 --- a/public/js/cover.js +++ b/public/js/cover.js @@ -29,14 +29,6 @@ import { saveAs } from 'file-saver'; import List from 'list.js'; import S from 'string'; -import Cover from './views/Cover'; -import Vue from 'vue'; - -new Vue({ - el: '#cover-app', - render: (h) => h(Cover) -}) - const options = { valueNames: ['id', 'text', 'timestamp', 'fromNow', 'time', 'tags', 'pinned'], item: '
  • \ diff --git a/public/js/views/Cover.vue b/public/js/views/Cover.vue deleted file mode 100644 index 767d087f..00000000 --- a/public/js/views/Cover.vue +++ /dev/null @@ -1,15 +0,0 @@ - - - diff --git a/public/views/index.ejs b/public/views/index.ejs index d258857c..b94daf5b 100644 --- a/public/views/index.ejs +++ b/public/views/index.ejs @@ -30,8 +30,6 @@
    -
    -

    diff --git a/webpackBaseConfig.js b/webpackBaseConfig.js index e618bffd..210001b1 100644 --- a/webpackBaseConfig.js +++ b/webpackBaseConfig.js @@ -338,7 +338,7 @@ module.exports = { path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules') ], - extensions: ["", ".js", ".vue"], + extensions: ["", ".js"], alias: { codemirror: path.join(__dirname, 'node_modules/codemirror/codemirror.min.js'), inlineAttachment: path.join(__dirname, 'public/vendor/inlineAttachment/inline-attachment.js'), @@ -372,12 +372,6 @@ module.exports = { loaders: [{ test: /\.json$/, loader: 'json-loader' - }, { - test: /\.vue$/, - loader: 'vue', - options: { - // vue-loader options go here - } }, { test: /\.js$/, loader: 'babel', -- cgit v1.2.3 From e98278492e3c80816d54e1a6841548409c8a4d80 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 21 Jan 2017 12:50:02 +0800 Subject: Fix meta error not clear on before rendering --- public/js/index.js | 1 + public/js/pretty.js | 1 + 2 files changed, 2 insertions(+) diff --git a/public/js/index.js b/public/js/index.js index a018e513..6e55fa17 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -3445,6 +3445,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 = { diff --git a/public/js/pretty.js b/public/js/pretty.js index c1a471a1..b946d423 100644 --- a/public/js/pretty.js +++ b/public/js/pretty.js @@ -22,6 +22,7 @@ var markdown = $("#doc.markdown-body"); var text = markdown.text(); var lastMeta = md.meta; md.meta = {}; +delete md.metaError; var rendered = md.render(text); if (md.meta.type && md.meta.type === 'slide') { var slideOptions = { -- cgit v1.2.3 From 5e1d022e13a56786f40216c5485554d9e8b13c05 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 21 Jan 2017 12:52:26 +0800 Subject: Add screenshot on index page --- public/css/cover.css | 6 ++++++ public/screenshot.png | Bin 0 -> 238635 bytes public/views/index.ejs | 1 + 3 files changed, 7 insertions(+) create mode 100644 public/screenshot.png diff --git a/public/css/cover.css b/public/css/cover.css index a1527bfa..6e191d2b 100644 --- a/public/css/cover.css +++ b/public/css/cover.css @@ -354,6 +354,12 @@ input { color: white; } +.screenshot { + margin: 30px auto; + width: 100%; + border-radius: 3px; +} + select { color: black; } diff --git a/public/screenshot.png b/public/screenshot.png new file mode 100644 index 00000000..e1e77431 Binary files /dev/null and b/public/screenshot.png differ diff --git a/public/views/index.ejs b/public/views/index.ejs index 25139907..4bcea0eb 100644 --- a/public/views/index.ejs +++ b/public/views/index.ejs @@ -87,6 +87,7 @@
    <%= __('Explore all features') %>

    +
    -- cgit v1.2.3 From 6e8ff3de234471375836ba907e86bf39804c308e Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 21 Jan 2017 12:53:18 +0800 Subject: Fix redundant parameter to removeColumn in db migration scripts --- lib/migrations/20161009040430-support-delete-note.js | 2 +- lib/migrations/20161201050312-support-email-signin.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/migrations/20161009040430-support-delete-note.js b/lib/migrations/20161009040430-support-delete-note.js index f478b6fe..92ff6f7b 100644 --- a/lib/migrations/20161009040430-support-delete-note.js +++ b/lib/migrations/20161009040430-support-delete-note.js @@ -6,6 +6,6 @@ module.exports = { }, down: function (queryInterface, Sequelize) { - queryInterface.removeColumn('Notes', 'deletedAt', Sequelize.DATE); + queryInterface.removeColumn('Notes', 'deletedAt'); } }; diff --git a/lib/migrations/20161201050312-support-email-signin.js b/lib/migrations/20161201050312-support-email-signin.js index bdea7c8c..b5aaf777 100644 --- a/lib/migrations/20161201050312-support-email-signin.js +++ b/lib/migrations/20161201050312-support-email-signin.js @@ -7,7 +7,7 @@ module.exports = { }, down: function (queryInterface, Sequelize) { - queryInterface.removeColumn('Users', 'email', Sequelize.TEXT); - queryInterface.removeColumn('Users', 'password', Sequelize.TEXT); + queryInterface.removeColumn('Users', 'email'); + queryInterface.removeColumn('Users', 'password'); } }; -- cgit v1.2.3 From 93d6fe6d7cf7d49b3dcea8ffaad4d3d51beed965 Mon Sep 17 00:00:00 2001 From: Yukai Huang Date: Sat, 21 Jan 2017 12:53:29 +0800 Subject: Revert useless linebreak --- public/views/index.ejs | 1 + 1 file changed, 1 insertion(+) diff --git a/public/views/index.ejs b/public/views/index.ejs index b94daf5b..25139907 100644 --- a/public/views/index.ejs +++ b/public/views/index.ejs @@ -30,6 +30,7 @@
    +

    -- cgit v1.2.3 From 09a7bcbdef237c1443bbbfc29010e7106cffd739 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 21 Jan 2017 13:08:29 +0800 Subject: Refactor templates and rearrange its path --- public/views/body.ejs | 250 --------------------------------- public/views/disqus.ejs | 14 -- public/views/error.ejs | 6 +- public/views/foot.ejs | 28 ---- public/views/footer.ejs | 0 public/views/ga.ejs | 18 --- public/views/hackmd.ejs | 12 +- public/views/hackmd/body.ejs | 250 +++++++++++++++++++++++++++++++++ public/views/hackmd/foot.ejs | 28 ++++ public/views/hackmd/footer.ejs | 0 public/views/hackmd/head.ejs | 22 +++ public/views/hackmd/header.ejs | 175 +++++++++++++++++++++++ public/views/head.ejs | 22 --- public/views/header.ejs | 175 ----------------------- public/views/help-modal.ejs | 147 ------------------- public/views/index.ejs | 216 +--------------------------- public/views/index/body.ejs | 175 +++++++++++++++++++++++ public/views/index/foot.ejs | 13 ++ public/views/index/footer.ejs | 0 public/views/index/head.ejs | 22 +++ public/views/index/header.ejs | 0 public/views/polyfill.ejs | 7 - public/views/pretty.ejs | 14 +- public/views/refresh-modal.ejs | 31 ---- public/views/revision-modal.ejs | 27 ---- public/views/shared/disqus.ejs | 14 ++ public/views/shared/ga.ejs | 18 +++ public/views/shared/help-modal.ejs | 147 +++++++++++++++++++ public/views/shared/polyfill.ejs | 7 + public/views/shared/refresh-modal.ejs | 31 ++++ public/views/shared/revision-modal.ejs | 27 ++++ public/views/shared/signin-modal.ejs | 95 +++++++++++++ public/views/signin-modal.ejs | 95 ------------- public/views/slide.ejs | 14 +- 34 files changed, 1052 insertions(+), 1048 deletions(-) delete mode 100644 public/views/body.ejs delete mode 100644 public/views/disqus.ejs delete mode 100644 public/views/foot.ejs delete mode 100644 public/views/footer.ejs delete mode 100644 public/views/ga.ejs create mode 100644 public/views/hackmd/body.ejs create mode 100644 public/views/hackmd/foot.ejs create mode 100644 public/views/hackmd/footer.ejs create mode 100644 public/views/hackmd/head.ejs create mode 100644 public/views/hackmd/header.ejs delete mode 100644 public/views/head.ejs delete mode 100644 public/views/header.ejs delete mode 100644 public/views/help-modal.ejs create mode 100644 public/views/index/body.ejs create mode 100644 public/views/index/foot.ejs create mode 100644 public/views/index/footer.ejs create mode 100644 public/views/index/head.ejs create mode 100644 public/views/index/header.ejs delete mode 100644 public/views/polyfill.ejs delete mode 100644 public/views/refresh-modal.ejs delete mode 100644 public/views/revision-modal.ejs create mode 100644 public/views/shared/disqus.ejs create mode 100644 public/views/shared/ga.ejs create mode 100644 public/views/shared/help-modal.ejs create mode 100644 public/views/shared/polyfill.ejs create mode 100644 public/views/shared/refresh-modal.ejs create mode 100644 public/views/shared/revision-modal.ejs create mode 100644 public/views/shared/signin-modal.ejs delete mode 100644 public/views/signin-modal.ejs diff --git a/public/views/body.ejs b/public/views/body.ejs deleted file mode 100644 index 5ad1733e..00000000 --- a/public/views/body.ejs +++ /dev/null @@ -1,250 +0,0 @@ - - - - - - - - - - - - - - - - - -<%- include refresh-modal %> -<%- include signin-modal %> -<%- include help-modal %> -<%- include revision-modal %> diff --git a/public/views/disqus.ejs b/public/views/disqus.ejs deleted file mode 100644 index cceaa85c..00000000 --- a/public/views/disqus.ejs +++ /dev/null @@ -1,14 +0,0 @@ -
    - - - \ No newline at end of file diff --git a/public/views/error.ejs b/public/views/error.ejs index 402b5eb0..a40ed39c 100644 --- a/public/views/error.ejs +++ b/public/views/error.ejs @@ -2,18 +2,18 @@ - <%- include head %> + <%- include hackmd/head %> - <%- include header %> + <%- include hackmd/header %>

    <%- code %> <%- detail %> <%- msg %>

    - <%- include footer %> + <%- include hackmd/footer %> \ No newline at end of file diff --git a/public/views/foot.ejs b/public/views/foot.ejs deleted file mode 100644 index c1df65c2..00000000 --- a/public/views/foot.ejs +++ /dev/null @@ -1,28 +0,0 @@ - -<% if(useCDN) { %> - - - - - - - - - - - - - - - - - - -<%- include build/index-scripts %> -<% } else { %> - - -<%- include build/index-pack-scripts %> -<% } %> diff --git a/public/views/footer.ejs b/public/views/footer.ejs deleted file mode 100644 index e69de29b..00000000 diff --git a/public/views/ga.ejs b/public/views/ga.ejs deleted file mode 100644 index 66d4acd9..00000000 --- a/public/views/ga.ejs +++ /dev/null @@ -1,18 +0,0 @@ -<% if(typeof GA !== 'undefined' && GA) { %> - -<% } %> \ No newline at end of file diff --git a/public/views/hackmd.ejs b/public/views/hackmd.ejs index c5778fc9..49084a63 100644 --- a/public/views/hackmd.ejs +++ b/public/views/hackmd.ejs @@ -2,14 +2,14 @@ - <%- include head %> + <%- include hackmd/head %> - <%- include header %> - <%- include body %> - <%- include footer %> - <%- include foot %> + <%- include hackmd/header %> + <%- include hackmd/body %> + <%- include hackmd/footer %> + <%- include hackmd/foot %> - \ No newline at end of file + diff --git a/public/views/hackmd/body.ejs b/public/views/hackmd/body.ejs new file mode 100644 index 00000000..d8a3f108 --- /dev/null +++ b/public/views/hackmd/body.ejs @@ -0,0 +1,250 @@ + + + + + + + + + + + + + + + + + +<%- include ../shared/refresh-modal %> +<%- include ../shared/signin-modal %> +<%- include ../shared/help-modal %> +<%- include ../shared/revision-modal %> diff --git a/public/views/hackmd/foot.ejs b/public/views/hackmd/foot.ejs new file mode 100644 index 00000000..178b5504 --- /dev/null +++ b/public/views/hackmd/foot.ejs @@ -0,0 +1,28 @@ + +<% if(useCDN) { %> + + + + + + + + + + + + + + + + + + +<%- include ../build/index-scripts %> +<% } else { %> + + +<%- include ../build/index-pack-scripts %> +<% } %> diff --git a/public/views/hackmd/footer.ejs b/public/views/hackmd/footer.ejs new file mode 100644 index 00000000..e69de29b diff --git a/public/views/hackmd/head.ejs b/public/views/hackmd/head.ejs new file mode 100644 index 00000000..d0663993 --- /dev/null +++ b/public/views/hackmd/head.ejs @@ -0,0 +1,22 @@ + + + + + + +<%= title %> + + +<% if(useCDN) { %> + + + + + + +<%- include ../build/index-header %> +<% } else { %> + +<%- include ../build/index-pack-header %> +<% } %> +<%- include ../shared/polyfill %> \ No newline at end of file diff --git a/public/views/hackmd/header.ejs b/public/views/hackmd/header.ejs new file mode 100644 index 00000000..bb4e3174 --- /dev/null +++ b/public/views/hackmd/header.ejs @@ -0,0 +1,175 @@ + +
    diff --git a/public/views/head.ejs b/public/views/head.ejs deleted file mode 100644 index 218847f7..00000000 --- a/public/views/head.ejs +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - -<%= title %> - - -<% if(useCDN) { %> - - - - - - -<%- include build/index-header %> -<% } else { %> - -<%- include build/index-pack-header %> -<% } %> -<%- include polyfill %> \ No newline at end of file diff --git a/public/views/header.ejs b/public/views/header.ejs deleted file mode 100644 index bb4e3174..00000000 --- a/public/views/header.ejs +++ /dev/null @@ -1,175 +0,0 @@ - -
    diff --git a/public/views/help-modal.ejs b/public/views/help-modal.ejs deleted file mode 100644 index b1ea681d..00000000 --- a/public/views/help-modal.ejs +++ /dev/null @@ -1,147 +0,0 @@ - - - \ No newline at end of file diff --git a/public/views/index.ejs b/public/views/index.ejs index 4bcea0eb..5732db4a 100644 --- a/public/views/index.ejs +++ b/public/views/index.ejs @@ -2,220 +2,14 @@ - - - - - - - - - HackMD - <%= __('Collaborative markdown notes') %> - - - <% if(useCDN) { %> - - - - - - <%- include build/cover-header %> - <% } else { %> - <%- include build/cover-pack-header %> - <% } %> - <%- include polyfill %> + <%- include index/head %> -
    -
    -
    - -
    -
    -

    - -
    -
    - -
    style="display:none;"<% } %>> -
    -

    HackMD

    -

    - <%= __('Best way to write and share your knowledge in markdown.') %> -

    - <% if (infoMessage && infoMessage.length > 0) { %> -
    <%= infoMessage %>
    - <% } %> - <% if (errorMessage && errorMessage.length > 0) { %> -
    <%= errorMessage %>
    - <% } %> - <% if(facebook || twitter || github || gitlab || dropbox || google || ldap || email) { %> - - <%= __('or') %> - <% } %> - - -
    -
    - -
    style="display:none;"<% } %>> - -
    -
    -
    - -
    -
    - -
    - - <%= __('Title') %> - - - <%= __('Time') %> - - - -
    - - -
      -
    -
      -
      - -
      -
      - -

      - © 2017 HackMD | <%= __('Releases') %> -

      - -
      -
      -
      -
      -
      - - - <%- include signin-modal %> - - <% if(useCDN) { %> - - - - - - - - - <%- include build/cover-scripts %> - <% } else { %> - <%- include build/cover-pack-scripts %> - <% } %> + <%- include index/header %> + <%- include index/body %> + <%- include index/footer %> + <%- include index/foot %> diff --git a/public/views/index/body.ejs b/public/views/index/body.ejs new file mode 100644 index 00000000..b8072450 --- /dev/null +++ b/public/views/index/body.ejs @@ -0,0 +1,175 @@ +
      +
      +
      + +
      +
      +

      + +
      +
      + +
      style="display:none;"<% } %>> +
      +

      HackMD

      +

      + <%= __('Best way to write and share your knowledge in markdown.') %> +

      + <% if (infoMessage && infoMessage.length > 0) { %> +
      <%= infoMessage %>
      + <% } %> + <% if (errorMessage && errorMessage.length > 0) { %> +
      <%= errorMessage %>
      + <% } %> + <% if(facebook || twitter || github || gitlab || dropbox || google || ldap || email) { %> + + <%= __('or') %> + <% } %> + + +
      +
      + +
      style="display:none;"<% } %>> + +
      +
      +
      + +
      +
      + +
      + + <%= __('Title') %> + + + <%= __('Time') %> + + + +
      + + +
        +
      +
        +
        + +
        +
        + +

        + © 2017 HackMD | <%= __('Releases') %> +

        + +
        +
        +
        +
        +
        + + +<%- include ../shared/signin-modal %> \ No newline at end of file diff --git a/public/views/index/foot.ejs b/public/views/index/foot.ejs new file mode 100644 index 00000000..293c6698 --- /dev/null +++ b/public/views/index/foot.ejs @@ -0,0 +1,13 @@ +<% if(useCDN) { %> + + + + + + + + +<%- include ../build/cover-scripts %> +<% } else { %> +<%- include ../build/cover-pack-scripts %> +<% } %> \ No newline at end of file diff --git a/public/views/index/footer.ejs b/public/views/index/footer.ejs new file mode 100644 index 00000000..e69de29b diff --git a/public/views/index/head.ejs b/public/views/index/head.ejs new file mode 100644 index 00000000..bbd14567 --- /dev/null +++ b/public/views/index/head.ejs @@ -0,0 +1,22 @@ + + + + + + + + +HackMD - <%= __('Collaborative markdown notes') %> + + +<% if(useCDN) { %> + + + + + +<%- include ../build/cover-header %> +<% } else { %> +<%- include ../build/cover-pack-header %> +<% } %> +<%- include ../shared/polyfill %> \ No newline at end of file diff --git a/public/views/index/header.ejs b/public/views/index/header.ejs new file mode 100644 index 00000000..e69de29b diff --git a/public/views/polyfill.ejs b/public/views/polyfill.ejs deleted file mode 100644 index 5c885642..00000000 --- a/public/views/polyfill.ejs +++ /dev/null @@ -1,7 +0,0 @@ - - - \ No newline at end of file diff --git a/public/views/pretty.ejs b/public/views/pretty.ejs index ced65ed8..de5b8ad3 100644 --- a/public/views/pretty.ejs +++ b/public/views/pretty.ejs @@ -23,12 +23,12 @@ - <%- include build/pretty-header %> + <%- include ../build/pretty-header %> <% } else { %> - <%- include build/pretty-pack-header %> + <%- include ../build/pretty-pack-header %> <% } %> - <%- include polyfill %> + <%- include ../shared/polyfill %> @@ -66,7 +66,7 @@ <% if(typeof disqus !== 'undefined' && disqus) { %>
        - <%- include disqus %> + <%- include ../shared/disqus %>
        <% } %> @@ -90,10 +90,10 @@ -<%- include build/pretty-scripts %> +<%- include ../build/pretty-scripts %> <% } else { %> -<%- include build/pretty-pack-scripts %> +<%- include ../build/pretty-pack-scripts %> <% } %> -<%- include ga %> +<%- include ../shared/ga %> diff --git a/public/views/refresh-modal.ejs b/public/views/refresh-modal.ejs deleted file mode 100644 index 5be41b2a..00000000 --- a/public/views/refresh-modal.ejs +++ /dev/null @@ -1,31 +0,0 @@ - - \ No newline at end of file diff --git a/public/views/revision-modal.ejs b/public/views/revision-modal.ejs deleted file mode 100644 index f824cf06..00000000 --- a/public/views/revision-modal.ejs +++ /dev/null @@ -1,27 +0,0 @@ - - \ No newline at end of file diff --git a/public/views/shared/disqus.ejs b/public/views/shared/disqus.ejs new file mode 100644 index 00000000..cceaa85c --- /dev/null +++ b/public/views/shared/disqus.ejs @@ -0,0 +1,14 @@ +
        + + + \ No newline at end of file diff --git a/public/views/shared/ga.ejs b/public/views/shared/ga.ejs new file mode 100644 index 00000000..66d4acd9 --- /dev/null +++ b/public/views/shared/ga.ejs @@ -0,0 +1,18 @@ +<% if(typeof GA !== 'undefined' && GA) { %> + +<% } %> \ No newline at end of file diff --git a/public/views/shared/help-modal.ejs b/public/views/shared/help-modal.ejs new file mode 100644 index 00000000..b1ea681d --- /dev/null +++ b/public/views/shared/help-modal.ejs @@ -0,0 +1,147 @@ + + + \ No newline at end of file diff --git a/public/views/shared/polyfill.ejs b/public/views/shared/polyfill.ejs new file mode 100644 index 00000000..5c885642 --- /dev/null +++ b/public/views/shared/polyfill.ejs @@ -0,0 +1,7 @@ + + + \ No newline at end of file diff --git a/public/views/shared/refresh-modal.ejs b/public/views/shared/refresh-modal.ejs new file mode 100644 index 00000000..5be41b2a --- /dev/null +++ b/public/views/shared/refresh-modal.ejs @@ -0,0 +1,31 @@ + + \ No newline at end of file diff --git a/public/views/shared/revision-modal.ejs b/public/views/shared/revision-modal.ejs new file mode 100644 index 00000000..f824cf06 --- /dev/null +++ b/public/views/shared/revision-modal.ejs @@ -0,0 +1,27 @@ + + \ No newline at end of file diff --git a/public/views/shared/signin-modal.ejs b/public/views/shared/signin-modal.ejs new file mode 100644 index 00000000..a8af62e7 --- /dev/null +++ b/public/views/shared/signin-modal.ejs @@ -0,0 +1,95 @@ + + diff --git a/public/views/signin-modal.ejs b/public/views/signin-modal.ejs deleted file mode 100644 index a8af62e7..00000000 --- a/public/views/signin-modal.ejs +++ /dev/null @@ -1,95 +0,0 @@ - - diff --git a/public/views/slide.ejs b/public/views/slide.ejs index b0323a0e..eb1453f8 100644 --- a/public/views/slide.ejs +++ b/public/views/slide.ejs @@ -23,10 +23,10 @@ - <%- include build/slide-header %> + <%- include ../build/slide-header %> <% } else { %> - <%- include build/slide-pack-header %> + <%- include ../build/slide-pack-header %> <% } %> @@ -45,7 +45,7 @@ document.getElementsByTagName( 'head' )[0].appendChild( link ); - <%- include polyfill %> + <%- include ../shared/polyfill %>
        @@ -79,7 +79,7 @@
        <% if(typeof disqus !== 'undefined' && disqus) { %>
        - <%- include disqus %> + <%- include ../shared/disqus %>
        <% } %>
        @@ -104,13 +104,13 @@ - <%- include build/slide-scripts %> + <%- include ../build/slide-scripts %> <% } else { %> - <%- include build/slide-pack-scripts %> + <%- include ../build/slide-pack-scripts %> <% } %> -<%- include ga %> +<%- include ../shared/ga %> -- cgit v1.2.3 From a669c201beb3755703e87984268cbd08145e9ac6 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 21 Jan 2017 13:40:08 +0800 Subject: Fix template partial path --- public/views/pretty.ejs | 14 +++++++------- public/views/slide.ejs | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/public/views/pretty.ejs b/public/views/pretty.ejs index de5b8ad3..a6913f6c 100644 --- a/public/views/pretty.ejs +++ b/public/views/pretty.ejs @@ -23,12 +23,12 @@ - <%- include ../build/pretty-header %> + <%- include build/pretty-header %> <% } else { %> - <%- include ../build/pretty-pack-header %> + <%- include build/pretty-pack-header %> <% } %> - <%- include ../shared/polyfill %> + <%- include shared/polyfill %> @@ -66,7 +66,7 @@ <% if(typeof disqus !== 'undefined' && disqus) { %>
        - <%- include ../shared/disqus %> + <%- include shared/disqus %>
        <% } %> @@ -90,10 +90,10 @@ -<%- include ../build/pretty-scripts %> +<%- include build/pretty-scripts %> <% } else { %> -<%- include ../build/pretty-pack-scripts %> +<%- include build/pretty-pack-scripts %> <% } %> -<%- include ../shared/ga %> +<%- include shared/ga %> diff --git a/public/views/slide.ejs b/public/views/slide.ejs index eb1453f8..ffbfdce6 100644 --- a/public/views/slide.ejs +++ b/public/views/slide.ejs @@ -23,10 +23,10 @@ - <%- include ../build/slide-header %> + <%- include build/slide-header %> <% } else { %> - <%- include ../build/slide-pack-header %> + <%- include build/slide-pack-header %> <% } %> @@ -45,7 +45,7 @@ document.getElementsByTagName( 'head' )[0].appendChild( link ); - <%- include ../shared/polyfill %> + <%- include shared/polyfill %>
        @@ -79,7 +79,7 @@
        <% if(typeof disqus !== 'undefined' && disqus) { %>
        - <%- include ../shared/disqus %> + <%- include shared/disqus %>
        <% } %>
        @@ -104,13 +104,13 @@ - <%- include ../build/slide-scripts %> + <%- include build/slide-scripts %> <% } else { %> - <%- include ../build/slide-pack-scripts %> + <%- include build/slide-pack-scripts %> <% } %> -<%- include ../shared/ga %> +<%- include shared/ga %> -- cgit v1.2.3 From fc00fa74341a43b2f99b085aa52fee57f40082ff Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 21 Jan 2017 14:24:51 +0800 Subject: Add link to features on profile dropdown --- public/views/index/body.ejs | 1 + 1 file changed, 1 insertion(+) diff --git a/public/views/index/body.ejs b/public/views/index/body.ejs index b8072450..584d67ed 100644 --- a/public/views/index/body.ejs +++ b/public/views/index/body.ejs @@ -26,6 +26,7 @@ -- cgit v1.2.3 From 9ea66e8820eda8fb14b176477808a4ba1f213a35 Mon Sep 17 00:00:00 2001 From: Sheogorath Date: Sat, 21 Jan 2017 19:18:56 +0100 Subject: Add documentation for new permissions --- public/docs/features.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/public/docs/features.md b/public/docs/features.md index 1c25bfea..1e9d48fa 100644 --- a/public/docs/features.md +++ b/public/docs/features.md @@ -49,7 +49,9 @@ There are four possible options: **Freely**: Anyone can edit this note. **Editable**: A signed-in user can edit this note. - **Locked**: Only the owner can edit this note. + **Limited**: People have to sign-in to view and edit this note. + **Locked**: Anyone can view this note but only the owner can edit it. + **Protected**: People have to sign-in to view this note but only owner can edit. **Private**: Only the owner can view and edit this note. **Only the owner of the note can change the note's permissions.** -- cgit v1.2.3 From 9122ccd1b8dc4d6a41aaa0794e80b5e06f2484d5 Mon Sep 17 00:00:00 2001 From: Sheogorath Date: Mon, 23 Jan 2017 06:11:20 +0100 Subject: Add fail fast option Fail the script if a command inside it fails to prevent a install with exitcode 0 even when commands in it are failing.--- bin/setup | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bin/setup b/bin/setup index 6724b2d5..3f143cd3 100755 --- a/bin/setup +++ b/bin/setup @@ -1,5 +1,7 @@ #!/bin/bash +set -e + # run command at repo root CURRENT_PATH=$PWD if [ -d .git ]; then -- cgit v1.2.3 From 3df5507589e09b9ec75fb1f8e0c750c6590fc003 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Thu, 2 Feb 2017 23:27:34 +0800 Subject: Upgrade viz.js to fix manual workaround and get smaller file size --- package.json | 2 +- public/js/extra.js | 33 ++++++++++++--------------------- 2 files changed, 13 insertions(+), 22 deletions(-) diff --git a/package.json b/package.json index 1ed81c98..1c043184 100644 --- a/package.json +++ b/package.json @@ -115,7 +115,7 @@ "validator": "^6.2.0", "velocity-animate": "^1.4.0", "visibilityjs": "^1.2.4", - "viz.js": "^1.4.1", + "viz.js": "^1.7.0", "winston": "^2.3.0", "xss": "^0.3.3" }, diff --git a/public/js/extra.js b/public/js/extra.js index b651d9e6..b0a4bdcb 100644 --- a/public/js/extra.js +++ b/public/js/extra.js @@ -345,30 +345,21 @@ export 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('
        ' + err + '
        '); - console.warn(err); - } + $value.unwrap(); + $value.parent().append('
        ' + err + '
        '); + console.warn(err); } }); //mermaid -- cgit v1.2.3 From 4dbafe62a3cd0d0c5a19248e25e7262c5aec1bea Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Thu, 2 Feb 2017 23:28:05 +0800 Subject: Upgrade mermaid to support class diagram --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 1c043184..f31c9da2 100644 --- a/package.json +++ b/package.json @@ -71,7 +71,7 @@ "markdown-it-sup": "^1.0.0", "markdown-pdf": "^7.0.0", "mathjax": "~2.7.0", - "mermaid": "~6.0.0", + "mermaid": "~7.0.0", "meta-marked": "^0.4.2", "method-override": "^2.3.7", "moment": "^2.17.1", -- cgit v1.2.3 From d5008b7aeb339f98751d9e0c78946e306c010b3f Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Thu, 2 Feb 2017 23:37:20 +0800 Subject: Update viz.js and mermaid CDN links --- public/views/hackmd/foot.ejs | 4 ++-- public/views/pretty.ejs | 4 ++-- public/views/slide.ejs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/public/views/hackmd/foot.ejs b/public/views/hackmd/foot.ejs index 178b5504..5d469374 100644 --- a/public/views/hackmd/foot.ejs +++ b/public/views/hackmd/foot.ejs @@ -11,14 +11,14 @@ - + - + <%- include ../build/index-scripts %> <% } else { %> diff --git a/public/views/pretty.ejs b/public/views/pretty.ejs index a6913f6c..15f853a9 100644 --- a/public/views/pretty.ejs +++ b/public/views/pretty.ejs @@ -84,12 +84,12 @@ - + - + <%- include build/pretty-scripts %> <% } else { %> diff --git a/public/views/slide.ejs b/public/views/slide.ejs index ffbfdce6..3799b2e0 100644 --- a/public/views/slide.ejs +++ b/public/views/slide.ejs @@ -98,12 +98,12 @@ - + - + <%- include build/slide-scripts %> <% } else { %> -- cgit v1.2.3 From 6c87262bd9d80f2fe409241d2e2084bc99b44b5b Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Thu, 2 Feb 2017 23:40:55 +0800 Subject: Fix to use minified CDN file source in mermaid --- public/views/hackmd/foot.ejs | 2 +- public/views/pretty.ejs | 2 +- public/views/slide.ejs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/public/views/hackmd/foot.ejs b/public/views/hackmd/foot.ejs index 5d469374..445b0213 100644 --- a/public/views/hackmd/foot.ejs +++ b/public/views/hackmd/foot.ejs @@ -11,7 +11,7 @@ - + diff --git a/public/views/pretty.ejs b/public/views/pretty.ejs index 15f853a9..64b65c70 100644 --- a/public/views/pretty.ejs +++ b/public/views/pretty.ejs @@ -84,7 +84,7 @@ - + diff --git a/public/views/slide.ejs b/public/views/slide.ejs index 3799b2e0..a3e2d1df 100644 --- a/public/views/slide.ejs +++ b/public/views/slide.ejs @@ -98,7 +98,7 @@ - + -- cgit v1.2.3 From e67a6ad3685289437e510906eeffb0d764ba4a37 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 3 Feb 2017 00:07:08 +0800 Subject: Fix missing type declaration --- public/js/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/js/index.js b/public/js/index.js index 39f28fbd..56f4fd38 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -2675,7 +2675,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(); }); }); -- cgit v1.2.3 From 5a212b933548ccc5ef1cd45d8b86d7d86c8f7b9e Mon Sep 17 00:00:00 2001 From: NV Date: Fri, 3 Feb 2017 17:35:16 +0900 Subject: Removed UTF-8 BOM in download function --- public/js/cover.js | 2 +- public/js/extra.js | 4 ++-- public/js/index.js | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/public/js/cover.js b/public/js/cover.js index 830564e8..bc6e73f9 100644 --- a/public/js/cover.js +++ b/public/js/cover.js @@ -325,7 +325,7 @@ $(".ui-save-history").click(() => { 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); }); }); diff --git a/public/js/extra.js b/public/js/extra.js index b651d9e6..a657c311 100644 --- a/public/js/extra.js +++ b/public/js/extra.js @@ -612,7 +612,7 @@ export function exportToRawHTML(view) { const blob = new Blob([html], { type: "text/html;charset=utf-8" }); - saveAs(blob, filename); + saveAs(blob, filename, true); } //extract markdown body to html and compile to template @@ -644,7 +644,7 @@ export function exportToHTML(view) { const blob = new Blob([html], { type: "text/html;charset=utf-8" }); - saveAs(blob, filename); + saveAs(blob, filename, true); }); }); } diff --git a/public/js/index.js b/public/js/index.js index 39f28fbd..176f0da7 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -1542,7 +1542,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) { @@ -1922,7 +1922,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; -- cgit v1.2.3 From 92ad67b813c3b940f619983c7daee7cdf21c3f4e Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 3 Feb 2017 21:39:08 +0800 Subject: Update to remove history cache to lower application coupling --- app.js | 6 +-- lib/history.js | 147 ++++++++++++++++++-------------------------------------- lib/realtime.js | 25 +++++----- 3 files changed, 64 insertions(+), 114 deletions(-) diff --git a/app.js b/app.js index ba0b67d3..ee82fab5 100644 --- a/app.js +++ b/app.js @@ -26,7 +26,6 @@ var validator = require('validator'); var config = require("./lib/config.js"); var logger = require("./lib/logger.js"); var auth = require("./lib/auth.js"); -var history = require("./lib/history.js"); var response = require("./lib/response.js"); var models = require("./lib/models"); @@ -443,6 +442,7 @@ app.get('/logout', function (req, res) { req.logout(); res.redirect(config.serverurl + '/'); }); +var history = require("./lib/history.js"); //get history app.get('/history', history.historyGet); //post history @@ -608,7 +608,7 @@ function startListen() { // sync db then start listen models.sequelize.sync().then(function () { // check if realtime is ready - if (history.isReady() && realtime.isReady()) { + if (realtime.isReady()) { models.Revision.checkAllNotesRevision(function (err, notes) { if (err) throw new Error(err); if (!notes || notes.length <= 0) return startListen(); @@ -639,7 +639,7 @@ function handleTermSignals() { }, 0); }); var checkCleanTimer = setInterval(function () { - if (history.isReady() && realtime.isReady()) { + if (realtime.isReady()) { models.Revision.checkAllNotesRevision(function (err, notes) { if (err) return logger.error(err); if (!notes || notes.length <= 0) { diff --git a/lib/history.js b/lib/history.js index 2723422c..e7fb3087 100644 --- a/lib/history.js +++ b/lib/history.js @@ -1,7 +1,6 @@ //history //external modules var async = require('async'); -var moment = require('moment'); //core var config = require("./config.js"); @@ -14,45 +13,32 @@ var History = { historyGet: historyGet, historyPost: historyPost, historyDelete: historyDelete, - isReady: isReady, updateHistory: updateHistory }; -var caches = {}; -//update when the history is dirty -var updater = setInterval(function () { - var deleted = []; - async.each(Object.keys(caches), function (key, callback) { - var cache = caches[key]; - if (cache.isDirty) { - if (config.debug) logger.info("history updater found dirty history: " + key); - var history = parseHistoryToArray(cache.history); - cache.isDirty = false; - finishUpdateHistory(key, history, function (err, count) { - if (err) return callback(err, null); - if (!count) return callback(null, null); - cache.updateAt = Date.now(); - return callback(null, null); - }); - } else { - if (moment().isAfter(moment(cache.updateAt).add(5, 'minutes'))) { - deleted.push(key); - } - return callback(null, null); +function getHistory(userid, callback) { + models.User.findOne({ + where: { + id: userid } - }, function (err) { - if (err) return logger.error('history updater error', err); + }).then(function (user) { + if (!user) + return callback(null, null); + var history = {}; + if (user.history) + history = parseHistoryToObject(JSON.parse(user.history)); + if (config.debug) + logger.info('read history success: ' + user.id); + return callback(null, history); + }).catch(function (err) { + logger.error('read history failed: ' + err); + return callback(err, null); }); - // delete specified caches - for (var i = 0, l = deleted.length; i < l; i++) { - caches[deleted[i]].history = {}; - delete caches[deleted[i]]; - } -}, 1000); +} -function finishUpdateHistory(userid, history, callback) { +function setHistory(userid, history, callback) { models.User.update({ - history: JSON.stringify(history) + history: JSON.stringify(parseHistoryToArray(history)) }, { where: { id: userid @@ -60,72 +46,27 @@ function finishUpdateHistory(userid, history, callback) { }).then(function (count) { return callback(null, count); }).catch(function (err) { + logger.error('set history failed: ' + err); return callback(err, null); }); } -function isReady() { - var dirtyCount = 0; - async.each(Object.keys(caches), function (key, callback) { - if (caches[key].isDirty) dirtyCount++; - return callback(null, null); - }, function (err) { - if (err) return logger.error('history ready check error', err); - }); - return dirtyCount > 0 ? false : true; -} - -function getHistory(userid, callback) { - if (caches[userid]) { - return callback(null, caches[userid].history); - } else { - models.User.findOne({ - where: { - id: userid - } - }).then(function (user) { - if (!user) - return callback(null, null); - var history = []; - if (user.history) - history = JSON.parse(user.history); - if (config.debug) - logger.info('read history success: ' + user.id); - setHistory(userid, history); - return callback(null, history); - }).catch(function (err) { - logger.error('read history failed: ' + err); - return callback(err, null); - }); - } -} - -function setHistory(userid, history) { - if (Array.isArray(history)) history = parseHistoryToObject(history); - if (!caches[userid]) { - caches[userid] = { - history: {}, - isDirty: false, - updateAt: Date.now() - }; - } - caches[userid].history = history; -} - -function updateHistory(userid, noteId, document) { +function updateHistory(userid, noteId, document, time) { if (userid && noteId && typeof document !== 'undefined') { getHistory(userid, function (err, history) { if (err || !history) return; - if (!caches[userid].history[noteId]) { - caches[userid].history[noteId] = {}; + if (!history[noteId]) { + history[noteId] = {}; } - var noteHistory = caches[userid].history[noteId]; + var noteHistory = history[noteId]; var noteInfo = models.Note.parseNoteInfo(document); noteHistory.id = noteId; noteHistory.text = noteInfo.title; - noteHistory.time = moment().valueOf(); + noteHistory.time = time || Date.now(); noteHistory.tags = noteInfo.tags; - caches[userid].isDirty = true; + setHistory(userid, history, function (err, count) { + return; + }); }); } } @@ -175,9 +116,10 @@ function historyPost(req, res) { return response.errorBadRequest(res); } if (Array.isArray(history)) { - setHistory(req.user.id, history); - caches[req.user.id].isDirty = true; - res.end(); + setHistory(req.user.id, history, function (err, count) { + if (err) return response.errorInternalError(res); + res.end(); + }); } else { return response.errorBadRequest(res); } @@ -186,11 +128,13 @@ function historyPost(req, res) { getHistory(req.user.id, function (err, history) { if (err) return response.errorInternalError(res); if (!history) return response.errorNotFound(res); - if (!caches[req.user.id].history[noteId]) return response.errorNotFound(res); + if (!history[noteId]) return response.errorNotFound(res); if (req.body.pinned === 'true' || req.body.pinned === 'false') { - caches[req.user.id].history[noteId].pinned = (req.body.pinned === 'true'); - caches[req.user.id].isDirty = true; - res.end(); + history[noteId].pinned = (req.body.pinned === 'true'); + setHistory(req.user.id, history, function (err, count) { + if (err) return response.errorInternalError(res); + res.end(); + }); } else { return response.errorBadRequest(res); } @@ -205,16 +149,19 @@ function historyDelete(req, res) { if (req.isAuthenticated()) { var noteId = req.params.noteId; if (!noteId) { - setHistory(req.user.id, []); - caches[req.user.id].isDirty = true; - res.end(); + setHistory(req.user.id, [], function (err, count) { + if (err) return response.errorInternalError(res); + res.end(); + }); } else { getHistory(req.user.id, function (err, history) { if (err) return response.errorInternalError(res); if (!history) return response.errorNotFound(res); - delete caches[req.user.id].history[noteId]; - caches[req.user.id].isDirty = true; - res.end(); + delete history[noteId]; + setHistory(req.user.id, history, function (err, count) { + if (err) return response.errorInternalError(res); + res.end(); + }); }); } } else { diff --git a/lib/realtime.js b/lib/realtime.js index fadea4f2..def8f217 100644 --- a/lib/realtime.js +++ b/lib/realtime.js @@ -122,6 +122,12 @@ function updateNote(note, callback) { } }).then(function (_note) { if (!_note) return callback(null, null); + // update user note history + var tempUsers = Object.assign({}, note.tempUsers); + note.tempUsers = {}; + Object.keys(tempUsers).forEach(function (key) { + updateHistory(key, note, tempUsers[key]); + }); if (note.lastchangeuser) { if (_note.lastchangeuserId != note.lastchangeuser) { models.User.findOne({ @@ -405,10 +411,7 @@ function finishConnection(socket, note, user) { note.server.setColor(socket, user.color); // update user note history - setTimeout(function () { - var noteId = note.alias ? note.alias : LZString.compressToBase64(note.id); - if (note.server) history.updateHistory(user.userid, noteId, note.server.document); - }, 0); + updateHistory(user.userid, note); emitOnlineUsers(socket); emitRefresh(socket); @@ -497,6 +500,7 @@ function startConnection(socket) { lastchangeuserprofile: lastchangeuserprofile, socks: [], users: {}, + tempUsers: {}, createtime: moment(createtime).valueOf(), updatetime: moment(updatetime).valueOf(), server: server, @@ -687,15 +691,14 @@ function operationCallback(socket, operation) { return logger.error('operation callback failed: ' + err); }); } - // update user note history - setTimeout(function() { - var noteId = note.alias ? note.alias : LZString.compressToBase64(note.id); - if (note.server) history.updateHistory(userId, noteId, note.server.document); - }, 0); - + note.tempUsers[userId] = Date.now(); } // save authorship note.authorship = models.Note.updateAuthorshipByOperation(operation, userId, note.authorship); + +function updateHistory(userId, note, time) { + var noteId = note.alias ? note.alias : LZString.compressToBase64(note.id); + if (note.server) history.updateHistory(userId, noteId, note.server.document, time); } function connection(socket) { @@ -925,4 +928,4 @@ function connection(socket) { }); } -module.exports = realtime; +module.exports = realtime; \ No newline at end of file -- cgit v1.2.3 From ef0ac7768d5dbd6a99c4126a1ed8b091f004d3bf Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 3 Feb 2017 21:47:38 +0800 Subject: Update realtime to use timer to avoid memory leaks on busy tick --- lib/realtime.js | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/lib/realtime.js b/lib/realtime.js index def8f217..c1db6886 100644 --- a/lib/realtime.js +++ b/lib/realtime.js @@ -354,9 +354,12 @@ function clearSocketQueue(queue, socket) { } function connectNextSocket() { - isConnectionBusy = false; - if (connectionSocketQueue.length > 0) - startConnection(connectionSocketQueue[0]); + setTimeout(function () { + isConnectionBusy = false; + if (connectionSocketQueue.length > 0) { + startConnection(connectionSocketQueue[0]); + } + }, 1); } function interruptConnection(socket, note, user) { @@ -693,8 +696,11 @@ function operationCallback(socket, operation) { } note.tempUsers[userId] = Date.now(); } - // save authorship - note.authorship = models.Note.updateAuthorshipByOperation(operation, userId, note.authorship); + // save authorship - use timer here because it's an O(n) complexity algorithm + setImmediate(function () { + note.authorship = models.Note.updateAuthorshipByOperation(operation, userId, note.authorship); + }); +} function updateHistory(userId, note, time) { var noteId = note.alias ? note.alias : LZString.compressToBase64(note.id); -- cgit v1.2.3 From 8cfbfa43520a298637b6f4e3137e4dea9d09e34d Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 3 Feb 2017 21:48:36 +0800 Subject: Update to add biggerphoto on parsing user profile --- lib/models/user.js | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/lib/models/user.js b/lib/models/user.js index 7d27242c..aee42041 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -79,39 +79,54 @@ module.exports = function (sequelize, DataTypes) { if (profile) { profile = { name: profile.displayName || profile.username, - photo: User.parsePhotoByProfile(profile) + photo: User.parsePhotoByProfile(profile), + biggerphoto: User.parsePhotoByProfile(profile, true) } } return profile; }, - parsePhotoByProfile: function (profile) { + parsePhotoByProfile: function (profile, bigger) { var photo = null; switch (profile.provider) { case "facebook": - photo = 'https://graph.facebook.com/' + profile.id + '/picture?width=96'; + photo = 'https://graph.facebook.com/' + profile.id + '/picture'; + if (bigger) photo += '?width=400'; + else photo += '?width=96'; break; case "twitter": - photo = 'https://twitter.com/' + profile.username + '/profile_image?size=bigger'; + photo = 'https://twitter.com/' + profile.username + '/profile_image'; + if (bigger) photo += '?size=original'; + else photo += '?size=bigger'; break; case "github": - photo = 'https://avatars.githubusercontent.com/u/' + profile.id + '?s=96'; + photo = 'https://avatars.githubusercontent.com/u/' + profile.id; + if (bigger) photo += '?s=400'; + else photo += '?s=96'; break; case "gitlab": - photo = profile.avatarUrl.replace(/(\?s=)\d*$/i, '$196'); + photo = profile.avatarUrl; + if (bigger) photo.replace(/(\?s=)\d*$/i, '$1400'); + else photo.replace(/(\?s=)\d*$/i, '$196'); break; case "dropbox": //no image api provided, use gravatar - photo = 'https://www.gravatar.com/avatar/' + md5(profile.emails[0].value) + '?s=96'; + photo = 'https://www.gravatar.com/avatar/' + md5(profile.emails[0].value); + if (bigger) photo += '?s=400'; + else photo += '?s=96'; break; case "google": - photo = profile.photos[0].value.replace(/(\?sz=)\d*$/i, '$196'); + photo = profile.photos[0].value; + if (bigger) photo.replace(/(\?sz=)\d*$/i, '$1400'); + else photo.replace(/(\?sz=)\d*$/i, '$196'); break; case "ldap": //no image api provided, //use gravatar if email exists, //otherwise generate a letter avatar if (profile.emails[0]) { - photo = 'https://www.gravatar.com/avatar/' + md5(profile.emails[0]) + '?s=96'; + photo = 'https://www.gravatar.com/avatar/' + md5(profile.emails[0]); + if (bigger) photo += '?s=400'; + else photo += '?s=96'; } else { photo = letterAvatars(profile.username); } @@ -123,7 +138,8 @@ module.exports = function (sequelize, DataTypes) { var photoUrl = 'https://www.gravatar.com/avatar/' + md5(email); return { name: email.substring(0, email.lastIndexOf("@")), - photo: photoUrl += '?s=96' + photo: photoUrl += '?s=96', + biggerphoto: photoUrl += '?s=400' }; } } -- cgit v1.2.3 From 0a3baec5b6bf6340fb7dfee3dce18807b01acfa6 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 3 Feb 2017 21:59:26 +0800 Subject: Fix missing type declaration in text complete strategy --- public/js/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/js/index.js b/public/js/index.js index dd26d379..9b42e79c 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -3953,7 +3953,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) { -- cgit v1.2.3 From 7863eec3660c7d78f9cfd5b3eee0585975faac6e Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 3 Feb 2017 22:01:30 +0800 Subject: Fix "[object HTMLCollection] is not iterable!" error in some browsers --- public/js/extra.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/public/js/extra.js b/public/js/extra.js index 39812fd8..16235669 100644 --- a/public/js/extra.js +++ b/public/js/extra.js @@ -792,7 +792,8 @@ const anchorForId = id => { const linkifyAnchors = (level, containingElement) => { const headers = containingElement.getElementsByTagName(`h${level}`); - for (const header of headers) { + 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 -- cgit v1.2.3 From 1a617ddf2ee44e116a97e1bc0168af22a87d2102 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 3 Feb 2017 22:02:12 +0800 Subject: Fix duplicated headers anchor link not been updated properly --- public/js/extra.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/js/extra.js b/public/js/extra.js index 16235669..a3e840d2 100644 --- a/public/js/extra.js +++ b/public/js/extra.js @@ -833,7 +833,7 @@ export function deduplicatedHeaderId(view) { const newId = id + j; const $duplicatedHeader = $(duplicatedHeaders[j]); $duplicatedHeader.attr('id', newId); - const $headerLink = $duplicatedHeader.find('> .header-link'); + const $headerLink = $duplicatedHeader.find(`> a.anchor[href="#${id}"]`); $headerLink.attr('href', `#${newId}`); $headerLink.attr('title', newId); } -- cgit v1.2.3 From 5ce5d4cd849f764cc563fc4cb1f3288ebb14a2a4 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 3 Feb 2017 22:04:43 +0800 Subject: Update to use babel-polyfill to support ES6 features in old browsers --- package.json | 1 + webpackBaseConfig.js | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/package.json b/package.json index f31c9da2..74de2c80 100644 --- a/package.json +++ b/package.json @@ -144,6 +144,7 @@ "babel-core": "^6.21.0", "babel-loader": "^6.2.10", "babel-plugin-transform-runtime": "^6.15.0", + "babel-polyfill": "^6.22.0", "babel-preset-es2015": "^6.18.0", "babel-runtime": "^6.20.0", "copy-webpack-plugin": "^4.0.1", diff --git a/webpackBaseConfig.js b/webpackBaseConfig.js index 210001b1..419149c7 100644 --- a/webpackBaseConfig.js +++ b/webpackBaseConfig.js @@ -158,6 +158,7 @@ module.exports = { "bootstrap" ], cover: [ + "babel-polyfill", path.join(__dirname, 'public/js/cover.js') ], "cover-styles-pack": [ @@ -168,6 +169,7 @@ module.exports = { path.join(__dirname, 'node_modules/select2/select2-bootstrap.css'), ], "cover-pack": [ + "babel-polyfill", "bootstrap-validator", "script!listPagnation", "expose?select2!select2", @@ -176,6 +178,7 @@ module.exports = { path.join(__dirname, 'public/js/cover.js') ], index: [ + "babel-polyfill", "script!jquery-ui-resizable", "script!js-url", "expose?filterXSS!xss", @@ -221,6 +224,7 @@ module.exports = { path.join(__dirname, 'node_modules/octicons/octicons/octicons.css') ], "index-pack": [ + "babel-polyfill", "expose?Spinner!spin.js", "script!jquery-ui-resizable", "bootstrap-validator", @@ -251,6 +255,7 @@ module.exports = { path.join(__dirname, 'public/js/index.js') ], pretty: [ + "babel-polyfill", "expose?filterXSS!xss", "flowchart.js", "js-sequence-diagrams", @@ -270,6 +275,7 @@ module.exports = { path.join(__dirname, 'node_modules/octicons/octicons/octicons.css') ], "pretty-pack": [ + "babel-polyfill", "expose?jsyaml!js-yaml", "script!mermaid", "expose?moment!moment", @@ -285,6 +291,7 @@ module.exports = { path.join(__dirname, 'public/js/pretty.js') ], slide: [ + "babel-polyfill", "bootstrap-tooltip", "expose?filterXSS!xss", "flowchart.js", @@ -304,6 +311,7 @@ module.exports = { path.join(__dirname, 'node_modules/octicons/octicons/octicons.css') ], "slide-pack": [ + "babel-polyfill", "expose?jQuery!expose?$!jquery", "velocity-animate", "imports?$=jquery!jquery-mousewheel", -- cgit v1.2.3 From 15bf2b6da859f2ab73fab5838689291830005c66 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 3 Feb 2017 22:05:09 +0800 Subject: Update webpack config to use parallel uglify plugin to speed up production build --- package.json | 3 ++- webpack.production.js | 15 +++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 74de2c80..d5e8e55c 100644 --- a/package.json +++ b/package.json @@ -163,6 +163,7 @@ "script-loader": "^0.7.0", "style-loader": "^0.13.1", "url-loader": "^0.5.7", - "webpack": "^1.14.0" + "webpack": "^1.14.0", + "webpack-parallel-uglify-plugin": "^0.2.0" } } diff --git a/webpack.production.js b/webpack.production.js index b28c34ae..7c690d28 100644 --- a/webpack.production.js +++ b/webpack.production.js @@ -3,6 +3,7 @@ var webpack = require('webpack'); var path = require('path'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); +var ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin'); module.exports = [Object.assign({}, baseConfig, { plugins: baseConfig.plugins.concat([ @@ -11,12 +12,14 @@ module.exports = [Object.assign({}, baseConfig, { 'NODE_ENV': JSON.stringify('production') } }), - new webpack.optimize.UglifyJsPlugin({ - compress: { - warnings: false - }, - mangle: false, - sourceMap: false + new ParallelUglifyPlugin({ + uglifyJS: { + compress: { + warnings: false + }, + mangle: false, + sourceMap: false + } }), new ExtractTextPlugin("[name].[hash].css") ]), -- cgit v1.2.3 From 0e6d1bbd6d301e6ccf43c8e71cead7c6c71f2dac Mon Sep 17 00:00:00 2001 From: bananaappletw Date: Sat, 4 Feb 2017 13:31:37 +0800 Subject: Change database config development to sqlite, test to memory --- config.json.example | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/config.json.example b/config.json.example index 80662b0f..9ee00c09 100644 --- a/config.json.example +++ b/config.json.example @@ -2,18 +2,13 @@ "test": { "db": { "dialect": "sqlite", - "storage": "./db.hackmd.sqlite" + "storage": ":memory:" } }, "development": { - "domain": "localhost", "db": { - "username": "", - "password": "", - "database": "hackmd", - "host": "localhost", - "port": "3306", - "dialect": "mysql" + "dialect": "sqlite", + "storage": "./db.hackmd.sqlite" } }, "production": { -- cgit v1.2.3 From 373f32aab73e9bb4938dad97449abadb751aa337 Mon Sep 17 00:00:00 2001 From: Jun SAKATA Date: Mon, 6 Feb 2017 17:41:46 +0900 Subject: Add additional comment about Prerequisite to README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3025f84e..83255d43 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,8 @@ Prerequisite - Node.js 4.x or up (test up to 6.7.0) - Database (PostgreSQL, MySQL, MariaDB, SQLite, MSSQL) use charset `utf8` - npm +- gcc/make + - `yum groupinstall 'Development Tools'` for RHEL, `sudo apt-get install build-essential` for Debian Get started --- -- cgit v1.2.3 From c49a0849b2ed8187917ba4023b356e64a1b9a2c9 Mon Sep 17 00:00:00 2001 From: Jun SAKATA Date: Mon, 6 Feb 2017 17:48:08 +0900 Subject: add sudo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 83255d43..2f25193b 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Prerequisite - Database (PostgreSQL, MySQL, MariaDB, SQLite, MSSQL) use charset `utf8` - npm - gcc/make - - `yum groupinstall 'Development Tools'` for RHEL, `sudo apt-get install build-essential` for Debian + - `sudo yum groupinstall 'Development Tools'` for RHEL, `sudo apt-get install build-essential` for Debian Get started --- -- cgit v1.2.3 From bbbf64aae465ed46505f4945080fa2d72e8d0b2b Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Tue, 7 Feb 2017 21:17:05 +0800 Subject: Fix HMD_LDAP_TLS_CA not passing correctly and update README.md --- README.md | 12 ++++++------ lib/config.js | 13 +++++++++++-- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 3025f84e..198f2fb6 100644 --- a/README.md +++ b/README.md @@ -130,15 +130,15 @@ Environment variables (will overwrite other server configs) | HMD_DROPBOX_CLIENTSECRET | no example | Dropbox API client secret | | HMD_GOOGLE_CLIENTID | no example | Google API client id | | HMD_GOOGLE_CLIENTSECRET | no example | Google API client secret | -| HMD_LDAP_URL | ldap://example.com | url of LDAP server | +| HMD_LDAP_URL | `ldap://example.com` | url of LDAP server | | HMD_LDAP_BINDDN | no example | bindDn for LDAP access | | HMD_LDAP_BINDCREDENTIALS | no example | bindCredentials for LDAP access | -| HMD_LDAP_TOKENSECRET | supersecretkey | secret used for generating access/refresh tokens | -| HMD_LDAP_SEARCHBASE | o=users,dc=example,dc=com | LDAP directory to begin search from | -| HMD_LDAP_SEARCHFILTER | (uid={{username}}) | LDAP filter to search with | +| HMD_LDAP_TOKENSECRET | `supersecretkey` | secret used for generating access/refresh tokens | +| HMD_LDAP_SEARCHBASE | `o=users,dc=example,dc=com` | LDAP directory to begin search from | +| HMD_LDAP_SEARCHFILTER | `(uid={{username}})` | LDAP filter to search with | | HMD_LDAP_SEARCHATTRIBUTES | no example | LDAP attributes to search with | -| HMD_LDAP_TLS_CA | no example | Root CA for LDAP TLS in PEM format | -| HMD_LDAP_PROVIDERNAME | My institution | Optional name to be displayed at login form indicating the LDAP provider | +| HMD_LDAP_TLS_CA | `server-cert.pem, root.pem` | Root CA for LDAP TLS in PEM format (use comma to separate) | +| HMD_LDAP_PROVIDERNAME | `My institution` | Optional name to be displayed at login form indicating the LDAP provider | | HMD_IMGUR_CLIENTID | no example | Imgur API client id | | HMD_EMAIL | `true` or `false` | set to allow email signin | | HMD_ALLOW_EMAIL_REGISTER | `true` or `false` | set to allow email register (only applied when email is set, default is `true`) | diff --git a/lib/config.js b/lib/config.js index 3816017e..e765d730 100644 --- a/lib/config.js +++ b/lib/config.js @@ -1,4 +1,5 @@ // external modules +var fs = require('fs'); var path = require('path'); // configs @@ -123,9 +124,17 @@ if (process.env.HMD_LDAP_SEARCHATTRIBUTES) ldap.searchAttributes = process.env.HMD_LDAP_SEARCHATTRIBUTES; if (process.env.HMD_LDAP_TLS_CA) { var ca = { - ca: process.env.HMD_LDAP_TLS_CA + ca: process.env.HMD_LDAP_TLS_CA.split(',') + } + ldap.tlsOptions = ldap.tlsOptions ? Object.assign(ldap.tlsOptions, ca) : ca; + if (Array.isArray(ldap.tlsOptions.ca) && ldap.tlsOptions.ca.length > 0) { + var i, len, results; + results = []; + for (i = 0, len = ldap.tlsOptions.ca.length; i < len; i++) { + results.push(fs.readFileSync(ldap.tlsOptions.ca[i], 'utf8')); + } + ldap.tlsOptions.ca = results; } - ldap.tlsOptions = ldap.tlsOptions ? Object.assign(ldap.tlsOptions, ca) : ca } if (process.env.HMD_LDAP_PROVIDERNAME) { ldap.providerName = process.env.HMD_LDAP_PROVIDERNAME; -- cgit v1.2.3 From 1cc27e1794afbe9f23bfb13cd098eeba554b1086 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Tue, 7 Feb 2017 22:31:38 +0800 Subject: Fix ldap config not initialize properly --- lib/config.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/config.js b/lib/config.js index e765d730..c0373820 100644 --- a/lib/config.js +++ b/lib/config.js @@ -96,7 +96,7 @@ var google = (process.env.HMD_GOOGLE_CLIENTID && process.env.HMD_GOOGLE_CLIENTSE clientID: process.env.HMD_GOOGLE_CLIENTID, clientSecret: process.env.HMD_GOOGLE_CLIENTSECRET } : (config.google && config.google.clientID && config.google.clientSecret && config.google) || false; -var ldap = config.ldap || ( +var ldap = config.ldap || (( process.env.HMD_LDAP_URL || process.env.HMD_LDAP_BINDDN || process.env.HMD_LDAP_BINDCREDENTIALS || @@ -104,10 +104,9 @@ var ldap = config.ldap || ( process.env.HMD_LDAP_SEARCHBASE || process.env.HMD_LDAP_SEARCHFILTER || process.env.HMD_LDAP_SEARCHATTRIBUTES || + process.env.HMD_LDAP_TLS_CA || process.env.HMD_LDAP_PROVIDERNAME -) || false; -if (ldap == true) - ldap = {}; +) ? {} : false); if (process.env.HMD_LDAP_URL) ldap.url = process.env.HMD_LDAP_URL; if (process.env.HMD_LDAP_BINDDN) -- cgit v1.2.3 From 2ab57effbdec0d09e53d351cef47860c7a1f3618 Mon Sep 17 00:00:00 2001 From: Jun SAKATA Date: Wed, 8 Feb 2017 15:30:31 +0900 Subject: add reference to packages, instead of writing down solutions for specific os --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 2f25193b..743d8129 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,7 @@ Prerequisite - Node.js 4.x or up (test up to 6.7.0) - Database (PostgreSQL, MySQL, MariaDB, SQLite, MSSQL) use charset `utf8` -- npm -- gcc/make - - `sudo yum groupinstall 'Development Tools'` for RHEL, `sudo apt-get install build-essential` for Debian +- npm (and its dependencies, especially [uWebSockets](https://github.com/uWebSockets/uWebSockets#nodejs-developers), [node-gyp](https://github.com/nodejs/node-gyp#installation)) Get started --- -- cgit v1.2.3 From a6f4c94eb22361fa2e1255df94705af5bf48a8f7 Mon Sep 17 00:00:00 2001 From: Simon Joda Stößer Date: Thu, 9 Feb 2017 03:34:58 +0100 Subject: typo in German translation fixed --- locales/de.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/locales/de.json b/locales/de.json index 4d8ba05f..41d89777 100644 --- a/locales/de.json +++ b/locales/de.json @@ -47,7 +47,7 @@ "View": "Anzeigen", "Both": "Beides", "Help": "Hilfe", - "Upload Image": "Foto hochloaden", + "Upload Image": "Foto hochladen", "Menu": "Menü", "This page need refresh": "Bitte laden Sie die Seite neu", "You have an incompatible client version.": "Ihre Client Version ist nicht mit dem Server kompatibel", -- cgit v1.2.3 From a0d16eec2340aacb8cfaa83070500395bfd50672 Mon Sep 17 00:00:00 2001 From: NV Date: Thu, 9 Feb 2017 11:41:41 +0900 Subject: Update README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index c81948a0..ebe19f66 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ Environment variables (will overwrite other server configs) | HMD_USECDN | `true` or `false` | set to use CDN resources or not (default is `true`) | | HMD_ALLOW_ANONYMOUS | `true` or `false` | set to allow anonymous usage (default is `true`) | | HMD_ALLOW_FREEURL | `true` or `false` | set to allow new note by accessing not exist note url | +| HMD_DEFAULT_PERMISSION | `freely`, `editable`, `limited`, `locked` or `private` | when creates new note, uses this permission (only applied when logged in) | | HMD_DB_URL | `mysql://localhost:3306/database` | set the db url | | HMD_FACEBOOK_CLIENTID | no example | Facebook API client id | | HMD_FACEBOOK_CLIENTSECRET | no example | Facebook API client secret | @@ -164,6 +165,7 @@ Application settings `config.json` | usecdn | `true` or `false` | set to use CDN resources or not (default is `true`) | | allowanonymous | `true` or `false` | set to allow anonymous usage (default is `true`) | | allowfreeurl | `true` or `false` | set to allow new note by accessing not exist note url | +| defaultpermission | `freely`, `editable`, `limited`, `locked` or `private` | when creates new note, uses this permission (only applied when logged in) | | dburl | `mysql://localhost:3306/database` | set the db url, if set this variable then below db config won't be applied | | db | `{ "dialect": "sqlite", "storage": "./db.hackmd.sqlite" }` | set the db configs, [see more here](http://sequelize.readthedocs.org/en/latest/api/sequelize/) | | sslkeypath | `./cert/client.key` | ssl key path (only need when you set usessl) | -- cgit v1.2.3 From 90c83ebd5b5610652c9bc8ae81299e85fe7056ef Mon Sep 17 00:00:00 2001 From: NV Date: Thu, 9 Feb 2017 14:07:36 +0900 Subject: Fix image path problem when using filesystem backend --- app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app.js b/app.js index ee82fab5..67a62540 100644 --- a/app.js +++ b/app.js @@ -502,7 +502,7 @@ app.post('/uploadimage', function (req, res) { switch (config.imageUploadType) { case 'filesystem': res.send({ - link: url.resolve(config.serverurl, files.image.path.match(/^public(.+$)/)[1]) + link: url.resolve(config.serverurl + '/', files.image.path.match(/^public\/(.+$)/)[1]) }); break; -- cgit v1.2.3 From 0a7adaf35d07efa658c040e789967acdc2eb32ff Mon Sep 17 00:00:00 2001 From: NV Date: Thu, 9 Feb 2017 13:24:40 +0900 Subject: Add default permission config --- lib/config.js | 4 ++++ lib/models/note.js | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/config.js b/lib/config.js index c0373820..052a5d0d 100644 --- a/lib/config.js +++ b/lib/config.js @@ -24,6 +24,9 @@ var allowanonymous = process.env.HMD_ALLOW_ANONYMOUS ? (process.env.HMD_ALLOW_AN var allowfreeurl = process.env.HMD_ALLOW_FREEURL ? (process.env.HMD_ALLOW_FREEURL === 'true') : !!config.allowfreeurl; +var defaultpermission = process.env.HMD_DEFAULT_PERMISSION || config.defaultpermission || 'editable'; +defaultpermission = (!allowanonymous && defaultpermission == 'freely') ? 'editable' : defaultpermission; + // db var dburl = config.dburl || process.env.HMD_DB_URL || process.env.DATABASE_URL; var db = config.db || {}; @@ -173,6 +176,7 @@ module.exports = { usecdn: usecdn, allowanonymous: allowanonymous, allowfreeurl: allowfreeurl, + defaultpermission: defaultpermission, dburl: dburl, db: db, sslkeypath: path.join(cwd, sslkeypath), diff --git a/lib/models/note.js b/lib/models/note.js index 86112973..8b38d3f9 100644 --- a/lib/models/note.js +++ b/lib/models/note.js @@ -513,10 +513,10 @@ module.exports = function (sequelize, DataTypes) { } } } - // if no permission specified and have owner then give editable permission, else default permission is freely + // if no permission specified and have owner then give default permission in config, else default permission is freely if (!note.permission) { if (note.ownerId) { - note.permission = "editable"; + note.permission = config.defaultpermission; } else { note.permission = "freely"; } -- cgit v1.2.3 From 5375fe57790152bf97958bb54cef922f03b2b40e Mon Sep 17 00:00:00 2001 From: NV Date: Fri, 10 Feb 2017 11:46:10 +0900 Subject: Add validation to defaultpermission in config --- lib/config.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/config.js b/lib/config.js index 052a5d0d..bdc2cbdb 100644 --- a/lib/config.js +++ b/lib/config.js @@ -24,8 +24,13 @@ var allowanonymous = process.env.HMD_ALLOW_ANONYMOUS ? (process.env.HMD_ALLOW_AN var allowfreeurl = process.env.HMD_ALLOW_FREEURL ? (process.env.HMD_ALLOW_FREEURL === 'true') : !!config.allowfreeurl; -var defaultpermission = process.env.HMD_DEFAULT_PERMISSION || config.defaultpermission || 'editable'; -defaultpermission = (!allowanonymous && defaultpermission == 'freely') ? 'editable' : defaultpermission; +var permissions = ['editable', 'limited', 'locked', 'protected', 'private']; +if (allowanonymous) { + permissions.unshift('freely'); +} + +var defaultpermission = process.env.HMD_DEFAULT_PERMISSION || config.defaultpermission; +defaultpermission = permissions.indexOf(defaultpermission) != -1 ? defaultpermission : 'editable'; // db var dburl = config.dburl || process.env.HMD_DB_URL || process.env.DATABASE_URL; -- cgit v1.2.3 From 00d1543a1017a231761ac20aaa49627e5744d923 Mon Sep 17 00:00:00 2001 From: NV Date: Fri, 10 Feb 2017 11:49:45 +0900 Subject: simplified description --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ebe19f66..7991117b 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,7 @@ Environment variables (will overwrite other server configs) | HMD_USECDN | `true` or `false` | set to use CDN resources or not (default is `true`) | | HMD_ALLOW_ANONYMOUS | `true` or `false` | set to allow anonymous usage (default is `true`) | | HMD_ALLOW_FREEURL | `true` or `false` | set to allow new note by accessing not exist note url | -| HMD_DEFAULT_PERMISSION | `freely`, `editable`, `limited`, `locked` or `private` | when creates new note, uses this permission (only applied when logged in) | +| HMD_DEFAULT_PERMISSION | `freely`, `editable`, `limited`, `locked` or `private` | set notes default permission (only applied on signed users) | | HMD_DB_URL | `mysql://localhost:3306/database` | set the db url | | HMD_FACEBOOK_CLIENTID | no example | Facebook API client id | | HMD_FACEBOOK_CLIENTSECRET | no example | Facebook API client secret | @@ -165,7 +165,7 @@ Application settings `config.json` | usecdn | `true` or `false` | set to use CDN resources or not (default is `true`) | | allowanonymous | `true` or `false` | set to allow anonymous usage (default is `true`) | | allowfreeurl | `true` or `false` | set to allow new note by accessing not exist note url | -| defaultpermission | `freely`, `editable`, `limited`, `locked` or `private` | when creates new note, uses this permission (only applied when logged in) | +| defaultpermission | `freely`, `editable`, `limited`, `locked` or `private` | set notes default permission (only applied on signed users) | | dburl | `mysql://localhost:3306/database` | set the db url, if set this variable then below db config won't be applied | | db | `{ "dialect": "sqlite", "storage": "./db.hackmd.sqlite" }` | set the db configs, [see more here](http://sequelize.readthedocs.org/en/latest/api/sequelize/) | | sslkeypath | `./cert/client.key` | ssl key path (only need when you set usessl) | -- cgit v1.2.3 From 99a2cbc60461de724167c525cfc89d35c3480cec Mon Sep 17 00:00:00 2001 From: Max Wu Date: Sat, 11 Feb 2017 00:11:21 +0800 Subject: Update google drive picker to enable setOwnedByMe to show shared files and folders --- public/js/google-drive-picker.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 +}()); -- cgit v1.2.3 From 6dc70000f0cbda32087e53915ece89af2b9df703 Mon Sep 17 00:00:00 2001 From: Stratos Gerakakis Date: Fri, 10 Feb 2017 18:02:15 +0100 Subject: Fixed Greek mispellings and translations There were various misspellings and some translations that were not clear enough.--- locales/el.json | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/locales/el.json b/locales/el.json index ea68aac3..8f65dfa2 100644 --- a/locales/el.json +++ b/locales/el.json @@ -1,7 +1,7 @@ { "Collaborative markdown notes": "Συνεργατικές σημειώσεις markdown", "Realtime collaborative markdown notes on all platforms.": "Συνεργατική σημειώσεις markdown σε όλες τις πλατφόρμες σε πραγματικό χρόνο.", - "Best way to write and share your knowledge in markdown.": "Ο καλύτερος τρόπς να γράψεις και να μοιρατσείς την γνώση σου in markdown.", + "Best way to write and share your knowledge in markdown.": "Ο καλύτερος τρόπος να γράψεις και να μοιραστείς την γνώση σου σε markdown.", "Intro": "Εισαγωγή", "History": "Ιστορία", "New guest note": "Νέα σημείωση επισκέπτη", @@ -54,9 +54,9 @@ "Refresh to update.": "Ανανεώστε για ενημέρωση", "New version available!": "Νέα διαθέσιμη έκδοση ", "See releases notes here": "Δείτε τις κυκλοφορίες της σημείωσης εδώ", - "Refresh to enjoy new features.": "Ανανεώστε για να δείτε τις κανούργίες λειτουργίες", + "Refresh to enjoy new features.": "Ανανεώστε για να δείτε τις κανούργιες λειτουργίες", "Your user state has changed.": "Η κατάσταση χρήστη έχει αλλάξει.", - "Refresh to load new user state.": "Ανανεώστε για να φορτωσετε την νέα κατάσταση χρήστη.", + "Refresh to load new user state.": "Ανανεώστε για να φορτώσετε την νέα κατάσταση χρήστη.", "Refresh": "Ανανέωση", "Contacts": "Επαφές", "Report an issue": "Αναφέρετε ένα θέμα", @@ -73,32 +73,32 @@ "Ordered List": "Αριθμημένη λίστα", "Todo List": "Todo List", "Blockquote": "Παράγραφος", - "Bold font": "Εντονη γραμματόσειρά", - "Italics font": "Italics γραμματόσειρά", - "Strikethrough": "Διακριτή διαγραφή", + "Bold font": "Εντονη γραμματοσειρά", + "Italics font": "Πλάγια γραμματοσειρά", + "Strikethrough": "Διαγραμένη γραμματοσειρά", "Inserted text": "Εισαγμένο κείμενο", - "Marked text": "Επιλεγμένο κέιμενο", + "Marked text": "Επιλεγμένο κείμενο", "Link": "Σύνδεσμος", "Image": "Εικόνα", "Code": "Κώδικας", "Externals": "Εξωτερικά", - "This is a alert area.": "Αυτή είνια μια περιοχή ειδοποίησης", + "This is a alert area.": "Αυτή είναι μια περιοχή ειδοποίησης", "Revert": "Επαναστροφή", "Import from clipboard": "Εισαγωγή από πρόχειρο", - "Paste your markdown or webpage here...": "Επικολλήστε το markdown ή την ιστοσελίδα σας εδώ...", + "Paste your markdown or webpage here...": "Επικολλήστε markdown ή την ιστοσελίδα σας εδώ...", "Clear": "Καθαρισμός", "This note is locked": "Η σημείωση είναι κλειδωμένη", - "Sorry, only owner can edit this note.": "Συγνώμη, μόνο ο ιδικτήτης μπορεί να επεξεργαστεί αυτη την σημείωση.", + "Sorry, only owner can edit this note.": "Συγνώμη, μόνο ο ιδιοκτήτης μπορεί να επεξεργαστεί αυτη την σημείωση.", "OK": "Εντάξει", "Reach the limit": "Φτάσατε το όριο", "Sorry, you've reached the max length this note can be.": "Συγνώμη, φτάσατε το μέγιστο μέγεθος αυτής της σημείωσης.", - "Please reduce the content or divide it to more notes, thank you!": "Παρακαλώ μειώστε το περιεχόμενο η διαιρεστε το σε περισσότερες σημειώσεις, ευχαριστώ!", + "Please reduce the content or divide it to more notes, thank you!": "Παρακαλώ μειώστε το περιεχόμενο η διαιρέστε το σε περισσότερες σημειώσεις, ευχαριστώ!", "Import from Gist": "Εισαγωγή από Gist", "Paste your gist url here...": "Κάντε επικκόληση του gist url εδώ...", - "Import from Snippet": "Εισαγωγή απο Snippet", + "Import from Snippet": "Εισαγωγή από Snippet", "Select From Available Projects": "Eπιλογή από διαθέσιμα Projects", "Select From Available Snippets": "Eπιλογή από διαθέσιμα Snippets", "OR": "Ή", "Export to Snippet": "Eξαγωγή σε Snippet", "Select Visibility Level": "Επιλέξτε επίπεδο ορατότητας" -} \ No newline at end of file +} -- cgit v1.2.3 From d29aff6505ddb7e49153a5fc2082bc3efe08e512 Mon Sep 17 00:00:00 2001 From: Mike Date: Wed, 15 Feb 2017 10:22:38 +0100 Subject: first envs then the config or docker -e will not work--- lib/config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/config.js b/lib/config.js index bdc2cbdb..a14bf978 100644 --- a/lib/config.js +++ b/lib/config.js @@ -33,7 +33,7 @@ var defaultpermission = process.env.HMD_DEFAULT_PERMISSION || config.defaultperm defaultpermission = permissions.indexOf(defaultpermission) != -1 ? defaultpermission : 'editable'; // db -var dburl = config.dburl || process.env.HMD_DB_URL || process.env.DATABASE_URL; +var dburl = process.env.HMD_DB_URL || process.env.DATABASE_URL || config.dburl; var db = config.db || {}; // ssl path -- cgit v1.2.3 From 4198d0d56060117e0806389f26eed4e65c4d37a6 Mon Sep 17 00:00:00 2001 From: bananaappletw Date: Wed, 15 Feb 2017 18:14:58 +0800 Subject: Add travis ci --- .travis.yml | 13 +++++++++++++ Makefile | 3 +++ README.md | 10 ++++++++-- package.json | 2 ++ 4 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 .travis.yml create mode 100644 Makefile diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..ed8ab42f --- /dev/null +++ b/.travis.yml @@ -0,0 +1,13 @@ +language: node_js +node_js: + - 6 + - 7 + - stable +env: + - CXX=g++-4.8 +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-4.8 diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..b9afabe9 --- /dev/null +++ b/Makefile @@ -0,0 +1,3 @@ +lint: + @./node_modules/.bin/eslint . +.PHONY: lint diff --git a/README.md b/README.md index 7991117b..05b13f85 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ HackMD === -[![Join the chat at https://gitter.im/hackmdio/hackmd](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/hackmdio/hackmd?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Join the chat at https://gitter.im/hackmdio/hackmd][gitter-image]][gitter-url] +[![build status][travis-image]][travis-url] + HackMD lets you create realtime collaborative markdown notes on all platforms. Inspired by Hackpad, with more focus on speed and flexibility. @@ -48,7 +50,7 @@ Browsers Requirement Prerequisite --- -- Node.js 4.x or up (test up to 6.7.0) +- Node.js 6.x or up (test up to 6.7.0) - Database (PostgreSQL, MySQL, MariaDB, SQLite, MSSQL) use charset `utf8` - npm (and its dependencies, especially [uWebSockets](https://github.com/uWebSockets/uWebSockets#nodejs-developers), [node-gyp](https://github.com/nodejs/node-gyp#installation)) @@ -222,3 +224,7 @@ Additionally, now can show other clients' selections. See more at [http://operational-transformation.github.io/](http://operational-transformation.github.io/) **License under MIT.** +[gitter-image]: https://badges.gitter.im/Join%20Chat.svg +[gitter-url]: https://gitter.im/hackmdio/hackmd?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[travis-image]: https://travis-ci.org/hackmdio/hackmd.svg?branch=master +[travis-url]: https://travis-ci.org/hackmdio/hackmd diff --git a/package.json b/package.json index d5e8e55c..ad629d1a 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "main": "app.js", "license": "MIT", "scripts": { + "test": "make lint", "dev": "webpack --config webpack.config.js --progress --colors --watch", "build": "webpack --config webpack.production.js --progress --colors", "postinstall": "bin/heroku", @@ -150,6 +151,7 @@ "copy-webpack-plugin": "^4.0.1", "css-loader": "^0.26.1", "ejs-loader": "^0.3.0", + "eslint": "^3.15.0", "exports-loader": "^0.6.3", "expose-loader": "^0.7.1", "extract-text-webpack-plugin": "^1.0.1", -- cgit v1.2.3 From 327ab411ac93a34459e025f30b7792f5d886554a Mon Sep 17 00:00:00 2001 From: bananaappletw Date: Wed, 15 Feb 2017 19:16:36 +0800 Subject: Add Makefile .editorconfig --- .editorconfig | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.editorconfig b/.editorconfig index 619c178d..ff999c4d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,3 +13,5 @@ trim_trailing_whitespace = false [{.travis.yml,npm-shrinkwrap.json,package.json}] indent_style = space indent_size = 2 +[Makefile] +indent_style = tab -- cgit v1.2.3 From af783b2746c86c33558604654403bfc31798b273 Mon Sep 17 00:00:00 2001 From: bananaappletw Date: Wed, 15 Feb 2017 19:17:51 +0800 Subject: Update node dependency up to 6.x in package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ad629d1a..2a40bf05 100644 --- a/package.json +++ b/package.json @@ -121,7 +121,7 @@ "xss": "^0.3.3" }, "engines": { - "node": ">=4.x" + "node": ">=6.x" }, "bugs": "https://github.com/hackmdio/hackmd/issues", "keywords": [ -- cgit v1.2.3 From c48ba0ad48d5daa3663aeb929967fa9fc0e8c4dc Mon Sep 17 00:00:00 2001 From: bananaappletw Date: Wed, 15 Feb 2017 22:09:09 +0800 Subject: Test up to 7.5.0 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 05b13f85..2afeba26 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ Browsers Requirement Prerequisite --- -- Node.js 6.x or up (test up to 6.7.0) +- Node.js 6.x or up (test up to 7.5.0) - Database (PostgreSQL, MySQL, MariaDB, SQLite, MSSQL) use charset `utf8` - npm (and its dependencies, especially [uWebSockets](https://github.com/uWebSockets/uWebSockets#nodejs-developers), [node-gyp](https://github.com/nodejs/node-gyp#installation)) -- cgit v1.2.3 From 40dfffd4f47a72549fb52d39a25c630551e761fc Mon Sep 17 00:00:00 2001 From: bananaappletw Date: Thu, 16 Feb 2017 12:27:17 +0800 Subject: Using package.json to test lint instead Exclude *.min.js from eslint --- .editorconfig | 2 -- .eslintignore | 1 + Makefile | 3 --- package.json | 3 ++- 4 files changed, 3 insertions(+), 6 deletions(-) create mode 100644 .eslintignore delete mode 100644 Makefile diff --git a/.editorconfig b/.editorconfig index ff999c4d..619c178d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -13,5 +13,3 @@ trim_trailing_whitespace = false [{.travis.yml,npm-shrinkwrap.json,package.json}] indent_style = space indent_size = 2 -[Makefile] -indent_style = tab diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000..121531af --- /dev/null +++ b/.eslintignore @@ -0,0 +1 @@ +*.min.js diff --git a/Makefile b/Makefile deleted file mode 100644 index b9afabe9..00000000 --- a/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -lint: - @./node_modules/.bin/eslint . -.PHONY: lint diff --git a/package.json b/package.json index 2a40bf05..a179d93e 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,8 @@ "main": "app.js", "license": "MIT", "scripts": { - "test": "make lint", + "test": "npm run-script lint", + "lint": "eslint .", "dev": "webpack --config webpack.config.js --progress --colors --watch", "build": "webpack --config webpack.production.js --progress --colors", "postinstall": "bin/heroku", -- cgit v1.2.3 From 1ca39d9c8e47ae2ce5a524504beb0aaed221a97c Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Fri, 17 Feb 2017 21:56:35 +0800 Subject: Update to allow li tag specify value number --- public/js/render.js | 2 ++ 1 file changed, 2 insertions(+) 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 -- cgit v1.2.3 From 2aee0f267c2154ddf001507a62e4fe548515cd3a Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 18 Feb 2017 20:07:15 +0800 Subject: Fix user profile photo might not replace to proper size --- lib/models/user.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/models/user.js b/lib/models/user.js index aee42041..dd93bf78 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -105,8 +105,8 @@ module.exports = function (sequelize, DataTypes) { break; case "gitlab": photo = profile.avatarUrl; - if (bigger) photo.replace(/(\?s=)\d*$/i, '$1400'); - else photo.replace(/(\?s=)\d*$/i, '$196'); + if (bigger) photo = photo.replace(/(\?s=)\d*$/i, '$1400'); + else photo = photo.replace(/(\?s=)\d*$/i, '$196'); break; case "dropbox": //no image api provided, use gravatar @@ -116,8 +116,8 @@ module.exports = function (sequelize, DataTypes) { break; case "google": photo = profile.photos[0].value; - if (bigger) photo.replace(/(\?sz=)\d*$/i, '$1400'); - else photo.replace(/(\?sz=)\d*$/i, '$196'); + if (bigger) photo = photo.replace(/(\?sz=)\d*$/i, '$1400'); + else photo = photo.replace(/(\?sz=)\d*$/i, '$196'); break; case "ldap": //no image api provided, -- cgit v1.2.3 From f7149f5a834ea79ec82f04ef2da257fe72f1b330 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 18 Feb 2017 20:10:34 +0800 Subject: Fix to keep selections on save and restore info --- public/js/index.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/public/js/index.js b/public/js/index.js index 9b42e79c..3ad79d59 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -408,7 +408,8 @@ window.lastInfo = { cursor: { line: null, ch: null - } + }, + selections: null }, view: { scroll: { @@ -3394,6 +3395,7 @@ function saveInfo() { break; } lastInfo.edit.cursor = editor.getCursor(); + lastInfo.edit.selections = editor.listSelections(); lastInfo.needRestore = true; } @@ -3403,6 +3405,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') { -- cgit v1.2.3 From 0aaa59813018847c765624bcd8cfa22e9aa57284 Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 18 Feb 2017 20:11:18 +0800 Subject: Fix not determine OT have pending operations properly --- public/js/index.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/public/js/index.js b/public/js/index.js index 3ad79d59..f0c476ef 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -2519,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]; @@ -2734,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) { @@ -2764,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(); } -- cgit v1.2.3 From 0bea4da6238b1f46562b146b32d88fc8d8b9060a Mon Sep 17 00:00:00 2001 From: Wu Cheng-Han Date: Sat, 18 Feb 2017 20:11:57 +0800 Subject: Fix out of sync when deleting on same cursor position on several clients from: https://github.com/aullman/opentok-editor/issues/4 --- public/vendor/ot/codemirror-adapter.js | 4 +++- public/vendor/ot/ot.min.js | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/public/vendor/ot/codemirror-adapter.js b/public/vendor/ot/codemirror-adapter.js index d858c411..cc23be01 100755 --- a/public/vendor/ot/codemirror-adapter.js +++ b/public/vendor/ot/codemirror-adapter.js @@ -343,7 +343,9 @@ ot.CodeMirrorAdapter = (function (global) { }; CodeMirrorAdapter.prototype.applyOperation = function (operation) { - this.ignoreNextChange = true; + if (!operation.isNoop()) { + this.ignoreNextChange = true; + } CodeMirrorAdapter.applyOperationToCodeMirror(operation, this.cm); }; diff --git a/public/vendor/ot/ot.min.js b/public/vendor/ot/ot.min.js index aba0960e..d942cb5d 100644 --- a/public/vendor/ot/ot.min.js +++ b/public/vendor/ot/ot.min.js @@ -1 +1 @@ -function hex2rgb(t){if("#"==t[0]&&(t=t.substr(1)),3==t.length){var e=t;t="",e=/^([a-f0-9])([a-f0-9])([a-f0-9])$/i.exec(e).slice(1);for(var n=0;n<3;n++)t+=e[n]+e[n]}var o=/^([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.exec(t).slice(1);return{red:parseInt(o[0],16),green:parseInt(o[1],16),blue:parseInt(o[2],16)}}if("undefined"==typeof ot)var ot={};if(ot.TextOperation=function(){"use strict";function t(){return this&&this.constructor===t?(this.ops=[],this.baseLength=0,void(this.targetLength=0)):new t}function e(e,n){var o=e.ops,r=t.isRetain;switch(o.length){case 1:return o[0];case 2:return r(o[0])?o[1]:r(o[1])?o[0]:null;case 3:if(r(o[0])&&r(o[2]))return o[1]}return null}function n(t){return o(t.ops[0])?t.ops[0]:0}t.prototype.equals=function(t){if(this.baseLength!==t.baseLength)return!1;if(this.targetLength!==t.targetLength)return!1;if(this.ops.length!==t.ops.length)return!1;for(var e=0;e0},r=t.isInsert=function(t){return"string"==typeof t},i=t.isDelete=function(t){return"number"==typeof t&&t<0};return t.prototype.retain=function(t){if("number"!=typeof t)throw new Error("retain expects an integer");return 0===t?this:(this.baseLength+=t,this.targetLength+=t,o(this.ops[this.ops.length-1])?this.ops[this.ops.length-1]+=t:this.ops.push(t),this)},t.prototype.insert=function(t){if("string"!=typeof t)throw new Error("insert expects a string");if(""===t)return this;this.targetLength+=t.length;var e=this.ops;return r(e[e.length-1])?e[e.length-1]+=t:i(e[e.length-1])?r(e[e.length-2])?e[e.length-2]+=t:(e[e.length]=e[e.length-1],e[e.length-2]=t):e.push(t),this},t.prototype["delete"]=function(t){if("string"==typeof t&&(t=t.length),"number"!=typeof t)throw new Error("delete expects an integer or a string");return 0===t?this:(t>0&&(t=-t),this.baseLength-=t,i(this.ops[this.ops.length-1])?this.ops[this.ops.length-1]+=t:this.ops.push(t),this)},t.prototype.isNoop=function(){return 0===this.ops.length||1===this.ops.length&&o(this.ops[0])},t.prototype.toString=function(){var t=Array.prototype.map||function(t){for(var e=this,n=[],o=0,r=e.length;ot.length)throw new Error("Operation can't retain more characters than are left in the string.");n[i++]=t.slice(s,s+c),s+=c}else r(c)?n[i++]=c:s-=c}if(s!==t.length)throw new Error("The operation didn't operate on the whole string.");return n.join("")},t.prototype.invert=function(e){for(var n=0,i=new t,s=this.ops,a=0,h=s.length;au?(s.retain(u),l-=u,u=h[c++]):l===u?(s.retain(l),l=a[p++],u=h[c++]):(s.retain(l),u-=l,l=a[p++]);else if(r(l)&&i(u))l.length>-u?(l=l.slice(-u),u=h[c++]):l.length===-u?(l=a[p++],u=h[c++]):(u+=l.length,l=a[p++]);else if(r(l)&&o(u))l.length>u?(s.insert(l.slice(0,u)),l=l.slice(u),u=h[c++]):l.length===u?(s.insert(l),l=a[p++],u=h[c++]):(s.insert(l),u-=l.length,l=a[p++]);else{if(!o(l)||!i(u))throw new Error("This shouldn't happen: op1: "+JSON.stringify(l)+", op2: "+JSON.stringify(u));l>-u?(s["delete"](u),l+=u,u=h[c++]):l===-u?(s["delete"](u),l=a[p++],u=h[c++]):(s["delete"](l),u+=l,l=a[p++])}}}return s},t.prototype.shouldBeComposedWith=function(t){if(this.isNoop()||t.isNoop())return!0;var o=n(this),s=n(t),a=e(this),h=e(t);return!(!a||!h)&&(r(a)&&r(h)?o+a.length===s:!(!i(a)||!i(h))&&(s-h===o||o===s))},t.prototype.shouldBeComposedWithInverted=function(t){if(this.isNoop()||t.isNoop())return!0;var o=n(this),s=n(t),a=e(this),h=e(t);return!(!a||!h)&&(r(a)&&r(h)?o+a.length===s||o===s:!(!i(a)||!i(h))&&s-h===o)},t.transform=function(e,n){if(e.baseLength!==n.baseLength)throw new Error("Both operations have to have the same base length");for(var s=new t,a=new t,h=e.ops,p=n.ops,c=0,l=0,u=h[c++],f=p[l++];;){if("undefined"==typeof u&&"undefined"==typeof f)break;if(r(u))s.insert(u),a.retain(u.length),u=h[c++];else if(r(f))s.retain(f.length),a.insert(f),f=p[l++];else{if("undefined"==typeof u)throw new Error("Cannot compose operations: first operation is too short.");if("undefined"==typeof f)throw new Error("Cannot compose operations: first operation is too long.");var d;if(o(u)&&o(f))u>f?(d=f,u-=f,f=p[l++]):u===f?(d=f,u=h[c++],f=p[l++]):(d=u,f-=u,u=h[c++]),s.retain(d),a.retain(d);else if(i(u)&&i(f))-u>-f?(u-=f,f=p[l++]):u===f?(u=h[c++],f=p[l++]):(f-=u,u=h[c++]);else if(i(u)&&o(f))-u>f?(d=f,u+=f,f=p[l++]):-u===f?(d=f,u=h[c++],f=p[l++]):(d=-u,f+=u,u=h[c++]),s["delete"](d);else{if(!o(u)||!i(f))throw new Error("The two operations aren't compatible");u>-f?(d=-f,u+=f,f=p[l++]):u===-f?(d=u,u=h[c++],f=p[l++]):(d=u,f+=u,u=h[c++]),a["delete"](d)}}}return[s,a]},t}(),"object"==typeof module&&(module.exports=ot.TextOperation),"undefined"==typeof ot)var ot={};if(ot.Selection=function(t){"use strict";function e(t,e){this.anchor=t,this.head=e}function n(t){this.ranges=t||[]}var o=t.ot?t.ot.TextOperation:require("./text-operation");return e.fromJSON=function(t){return new e(t.anchor,t.head)},e.prototype.equals=function(t){return this.anchor===t.anchor&&this.head===t.head},e.prototype.isEmpty=function(){return this.anchor===this.head},e.prototype.transform=function(t){function n(e){for(var n=e,r=t.ops,i=0,s=t.ops.length;i=0;r--){var i=o.transform(t[r],e);"function"==typeof i[0].isNoop&&i[0].isNoop()||n.push(i[0]),e=i[1]}return n.reverse()}var n="normal",o="undoing",r="redoing";return t.prototype.add=function(t,e){if(this.state===o)this.redoStack.push(t),this.dontCompose=!0;else if(this.state===r)this.undoStack.push(t),this.dontCompose=!0;else{var n=this.undoStack;!this.dontCompose&&e&&n.length>0?n.push(t.compose(n.pop())):(n.push(t),n.length>this.maxItems&&n.shift()),this.dontCompose=!1,this.redoStack=[]}},t.prototype.transform=function(t){this.undoStack=e(this.undoStack,t),this.redoStack=e(this.redoStack,t)},t.prototype.performUndo=function(t){if(this.state=o,0===this.undoStack.length)throw new Error("undo not possible");t(this.undoStack.pop()),this.state=n},t.prototype.performRedo=function(t){if(this.state=r,0===this.redoStack.length)throw new Error("redo not possible");t(this.redoStack.pop()),this.state=n},t.prototype.canUndo=function(){return 0!==this.undoStack.length},t.prototype.canRedo=function(){return 0!==this.redoStack.length},t.prototype.isUndoing=function(){return this.state===o},t.prototype.isRedoing=function(){return this.state===r},t}(),"object"==typeof module&&(module.exports=ot.UndoManager),"undefined"==typeof ot)var ot={};ot.Client=function(t){"use strict";function e(t){this.revision=t,this.setState(a)}function n(){}function o(t){this.outstanding=t}function r(t,e){this.outstanding=t,this.buffer=e}function i(t,e,n){this.acknowlaged=t,this.client=e,this.revision=n}function s(t,e,n,o){this.acknowlaged=t,this.buffer=e,this.client=n,this.revision=o}e.prototype.setState=function(t){this.state=t},e.prototype.applyClient=function(t){this.setState(this.state.applyClient(this,t))},e.prototype.applyServer=function(t,e){this.setState(this.state.applyServer(this,t,e))},e.prototype.applyOperations=function(t,e){this.setState(this.state.applyOperations(this,t,e))},e.prototype.serverAck=function(t){this.setState(this.state.serverAck(this,t))},e.prototype.serverReconnect=function(){"function"==typeof this.state.resend&&this.state.resend(this)},e.prototype.transformSelection=function(t){return this.state.transformSelection(t)},e.prototype.sendOperation=function(t,e){throw new Error("sendOperation must be defined in child class")},e.prototype.applyOperation=function(t){throw new Error("applyOperation must be defined in child class")},e.Synchronized=n,n.prototype.applyClient=function(t,e){return t.sendOperation(t.revision,e),new o(e)},n.prototype.applyServer=function(t,e,n){if(e-t.revision>1)throw new Error("Invalid revision.");return t.revision=e,t.applyOperation(n),this},n.prototype.serverAck=function(t,e){throw new Error("There is no pending operation.")},n.prototype.transformSelection=function(t){return t};var a=new n;return e.AwaitingConfirm=o,o.prototype.applyClient=function(t,e){return new r(this.outstanding,e)},o.prototype.applyServer=function(t,e,n){if(e-t.revision>1)throw new Error("Invalid revision.");t.revision=e;var r=n.constructor.transform(this.outstanding,n);return t.applyOperation(r[1]),new o(r[0])},o.prototype.serverAck=function(t,e){return e-t.revision>1?new i(this.outstanding,t,e).getOperations():(t.revision=e,a)},o.prototype.transformSelection=function(t){return t.transform(this.outstanding)},o.prototype.resend=function(t){t.sendOperation(t.revision,this.outstanding)},e.AwaitingWithBuffer=r,r.prototype.applyClient=function(t,e){var n=this.buffer.compose(e);return new r(this.outstanding,n)},r.prototype.applyServer=function(t,e,n){if(e-t.revision>1)throw new Error("Invalid revision.");t.revision=e;var o=n.constructor.transform,i=o(this.outstanding,n),s=o(this.buffer,i[1]);return t.applyOperation(s[1]),new r(i[0],s[0])},r.prototype.serverAck=function(t,e){return e-t.revision>1?new s(this.outstanding,this.buffer,t,e).getOperations():(t.revision=e,t.sendOperation(t.revision,this.buffer),new o(this.buffer))},r.prototype.transformSelection=function(t){return t.transform(this.outstanding).transform(this.buffer)},r.prototype.resend=function(t){t.sendOperation(t.revision,this.outstanding)},e.Stale=i,i.prototype.applyClient=function(t,e){return new s(this.acknowlaged,e,t,this.revision)},i.prototype.applyServer=function(t,e,n){throw new Error("Ignored server-side change.")},i.prototype.applyOperations=function(t,e,n){for(var o=this.acknowlaged.constructor.transform,r=0;re.line?1:t.che.ch?1:0}function o(t,e){return n(t,e)<=0}function r(t,e){return o(t,e)?t:e}function i(t,e){return o(t,e)?e:t}function s(t){return t.indexFromPos({line:t.lastLine(),ch:0})+t.getLine(t.lastLine()).length}function a(t,e){var n=t[e];t[e]=function(){n.apply(t,arguments)}}var h=ot.TextOperation,p=ot.Selection;e.prototype.detach=function(){this.cm.off("changes",this.onChanges),this.cm.off("change",this.onChange),this.cm.off("cursorActivity",this.onCursorActivity),this.cm.off("focus",this.onFocus),this.cm.off("blur",this.onBlur)},e.operationFromCodeMirrorChanges=function(t,e){function n(t){return t[t.length-1]}function r(t){if(0===t.length)return 0;for(var e=0,n=0;n=0;u--){var f=t[u];l=i(l,f);var d=l(f.from),g=a-d-r(f.text);p=(new h).retain(d)["delete"](r(f.removed)).insert(f.text.join("\n")).retain(g).compose(p),c=c.compose((new h).retain(d)["delete"](r(f.text)).insert(f.removed.join("\n")).retain(g)),a+=r(f.removed)-r(f.text)}return[p,c]},e.operationFromCodeMirrorChange=e.operationFromCodeMirrorChanges,e.applyOperationToCodeMirror=function(t,e){e.operation(function(){for(var n=t.ops,o=0,r=0,i=n.length;r0&&(this.majorRevision+=n.length,this.minorRevision=0);var o=t.events;if(o){for(e=0;e1&&(t-=1),6*t<1?i+6*(o-i)*t:2*t<1?o:3*t<2?i+6*(o-i)*(2/3-t):i};return r(s(t+1/3),s(t),s(t-1/3))}function s(t){for(var e=1,n=0;n0&&n.shouldBeComposedWithInverted(h(this.undoManager.undoStack).wrapped)),s=new t(this.selection,o);this.undoManager.add(new d(n,s),i),this.applyClient(e)},o.prototype.updateSelection=function(){this.selection=this.editorAdapter.getSelection()},o.prototype.onSelectionChange=function(){var t=this.selection;this.updateSelection(),t&&this.selection.equals(t)||this.sendSelection(this.selection)},o.prototype.onBlur=function(){this.selection=null,this.sendSelection(null)},o.prototype.sendSelection=function(t){this.state instanceof c.AwaitingWithBuffer||this.serverAdapter.sendSelection(t)},o.prototype.sendOperation=function(t,e){this.serverAdapter.sendOperation(t,e.toJSON(),this.selection)},o.prototype.getOperations=function(t,e){this.serverAdapter.getOperations(t,e)},o.prototype.applyOperation=function(t){this.editorAdapter.applyOperation(t),this.updateSelection(),this.undoManager.transform(new d(t,null))},o}(); \ No newline at end of file +function hex2rgb(t){if("#"==t[0]&&(t=t.substr(1)),3==t.length){var e=t;t="",e=/^([a-f0-9])([a-f0-9])([a-f0-9])$/i.exec(e).slice(1);for(var n=0;n<3;n++)t+=e[n]+e[n]}var o=/^([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i.exec(t).slice(1);return{red:parseInt(o[0],16),green:parseInt(o[1],16),blue:parseInt(o[2],16)}}if("undefined"==typeof ot)var ot={};if(ot.TextOperation=function(){"use strict";function t(){return this&&this.constructor===t?(this.ops=[],this.baseLength=0,void(this.targetLength=0)):new t}function e(e,n){var o=e.ops,r=t.isRetain;switch(o.length){case 1:return o[0];case 2:return r(o[0])?o[1]:r(o[1])?o[0]:null;case 3:if(r(o[0])&&r(o[2]))return o[1]}return null}function n(t){return o(t.ops[0])?t.ops[0]:0}t.prototype.equals=function(t){if(this.baseLength!==t.baseLength)return!1;if(this.targetLength!==t.targetLength)return!1;if(this.ops.length!==t.ops.length)return!1;for(var e=0;e0},r=t.isInsert=function(t){return"string"==typeof t},i=t.isDelete=function(t){return"number"==typeof t&&t<0};return t.prototype.retain=function(t){if("number"!=typeof t)throw new Error("retain expects an integer");return 0===t?this:(this.baseLength+=t,this.targetLength+=t,o(this.ops[this.ops.length-1])?this.ops[this.ops.length-1]+=t:this.ops.push(t),this)},t.prototype.insert=function(t){if("string"!=typeof t)throw new Error("insert expects a string");if(""===t)return this;this.targetLength+=t.length;var e=this.ops;return r(e[e.length-1])?e[e.length-1]+=t:i(e[e.length-1])?r(e[e.length-2])?e[e.length-2]+=t:(e[e.length]=e[e.length-1],e[e.length-2]=t):e.push(t),this},t.prototype["delete"]=function(t){if("string"==typeof t&&(t=t.length),"number"!=typeof t)throw new Error("delete expects an integer or a string");return 0===t?this:(t>0&&(t=-t),this.baseLength-=t,i(this.ops[this.ops.length-1])?this.ops[this.ops.length-1]+=t:this.ops.push(t),this)},t.prototype.isNoop=function(){return 0===this.ops.length||1===this.ops.length&&o(this.ops[0])},t.prototype.toString=function(){var t=Array.prototype.map||function(t){for(var e=this,n=[],o=0,r=e.length;ot.length)throw new Error("Operation can't retain more characters than are left in the string.");n[i++]=t.slice(s,s+c),s+=c}else r(c)?n[i++]=c:s-=c}if(s!==t.length)throw new Error("The operation didn't operate on the whole string.");return n.join("")},t.prototype.invert=function(e){for(var n=0,i=new t,s=this.ops,a=0,h=s.length;au?(s.retain(u),l-=u,u=h[c++]):l===u?(s.retain(l),l=a[p++],u=h[c++]):(s.retain(l),u-=l,l=a[p++]);else if(r(l)&&i(u))l.length>-u?(l=l.slice(-u),u=h[c++]):l.length===-u?(l=a[p++],u=h[c++]):(u+=l.length,l=a[p++]);else if(r(l)&&o(u))l.length>u?(s.insert(l.slice(0,u)),l=l.slice(u),u=h[c++]):l.length===u?(s.insert(l),l=a[p++],u=h[c++]):(s.insert(l),u-=l.length,l=a[p++]);else{if(!o(l)||!i(u))throw new Error("This shouldn't happen: op1: "+JSON.stringify(l)+", op2: "+JSON.stringify(u));l>-u?(s["delete"](u),l+=u,u=h[c++]):l===-u?(s["delete"](u),l=a[p++],u=h[c++]):(s["delete"](l),u+=l,l=a[p++])}}}return s},t.prototype.shouldBeComposedWith=function(t){if(this.isNoop()||t.isNoop())return!0;var o=n(this),s=n(t),a=e(this),h=e(t);return!(!a||!h)&&(r(a)&&r(h)?o+a.length===s:!(!i(a)||!i(h))&&(s-h===o||o===s))},t.prototype.shouldBeComposedWithInverted=function(t){if(this.isNoop()||t.isNoop())return!0;var o=n(this),s=n(t),a=e(this),h=e(t);return!(!a||!h)&&(r(a)&&r(h)?o+a.length===s||o===s:!(!i(a)||!i(h))&&s-h===o)},t.transform=function(e,n){if(e.baseLength!==n.baseLength)throw new Error("Both operations have to have the same base length");for(var s=new t,a=new t,h=e.ops,p=n.ops,c=0,l=0,u=h[c++],f=p[l++];;){if("undefined"==typeof u&&"undefined"==typeof f)break;if(r(u))s.insert(u),a.retain(u.length),u=h[c++];else if(r(f))s.retain(f.length),a.insert(f),f=p[l++];else{if("undefined"==typeof u)throw new Error("Cannot compose operations: first operation is too short.");if("undefined"==typeof f)throw new Error("Cannot compose operations: first operation is too long.");var d;if(o(u)&&o(f))u>f?(d=f,u-=f,f=p[l++]):u===f?(d=f,u=h[c++],f=p[l++]):(d=u,f-=u,u=h[c++]),s.retain(d),a.retain(d);else if(i(u)&&i(f))-u>-f?(u-=f,f=p[l++]):u===f?(u=h[c++],f=p[l++]):(f-=u,u=h[c++]);else if(i(u)&&o(f))-u>f?(d=f,u+=f,f=p[l++]):-u===f?(d=f,u=h[c++],f=p[l++]):(d=-u,f+=u,u=h[c++]),s["delete"](d);else{if(!o(u)||!i(f))throw new Error("The two operations aren't compatible");u>-f?(d=-f,u+=f,f=p[l++]):u===-f?(d=u,u=h[c++],f=p[l++]):(d=u,f+=u,u=h[c++]),a["delete"](d)}}}return[s,a]},t}(),"object"==typeof module&&(module.exports=ot.TextOperation),"undefined"==typeof ot)var ot={};if(ot.Selection=function(t){"use strict";function e(t,e){this.anchor=t,this.head=e}function n(t){this.ranges=t||[]}var o=t.ot?t.ot.TextOperation:require("./text-operation");return e.fromJSON=function(t){return new e(t.anchor,t.head)},e.prototype.equals=function(t){return this.anchor===t.anchor&&this.head===t.head},e.prototype.isEmpty=function(){return this.anchor===this.head},e.prototype.transform=function(t){function n(e){for(var n=e,r=t.ops,i=0,s=t.ops.length;i=0;r--){var i=o.transform(t[r],e);"function"==typeof i[0].isNoop&&i[0].isNoop()||n.push(i[0]),e=i[1]}return n.reverse()}var n="normal",o="undoing",r="redoing";return t.prototype.add=function(t,e){if(this.state===o)this.redoStack.push(t),this.dontCompose=!0;else if(this.state===r)this.undoStack.push(t),this.dontCompose=!0;else{var n=this.undoStack;!this.dontCompose&&e&&n.length>0?n.push(t.compose(n.pop())):(n.push(t),n.length>this.maxItems&&n.shift()),this.dontCompose=!1,this.redoStack=[]}},t.prototype.transform=function(t){this.undoStack=e(this.undoStack,t),this.redoStack=e(this.redoStack,t)},t.prototype.performUndo=function(t){if(this.state=o,0===this.undoStack.length)throw new Error("undo not possible");t(this.undoStack.pop()),this.state=n},t.prototype.performRedo=function(t){if(this.state=r,0===this.redoStack.length)throw new Error("redo not possible");t(this.redoStack.pop()),this.state=n},t.prototype.canUndo=function(){return 0!==this.undoStack.length},t.prototype.canRedo=function(){return 0!==this.redoStack.length},t.prototype.isUndoing=function(){return this.state===o},t.prototype.isRedoing=function(){return this.state===r},t}(),"object"==typeof module&&(module.exports=ot.UndoManager),"undefined"==typeof ot)var ot={};ot.Client=function(t){"use strict";function e(t){this.revision=t,this.setState(a)}function n(){}function o(t){this.outstanding=t}function r(t,e){this.outstanding=t,this.buffer=e}function i(t,e,n){this.acknowlaged=t,this.client=e,this.revision=n}function s(t,e,n,o){this.acknowlaged=t,this.buffer=e,this.client=n,this.revision=o}e.prototype.setState=function(t){this.state=t},e.prototype.applyClient=function(t){this.setState(this.state.applyClient(this,t))},e.prototype.applyServer=function(t,e){this.setState(this.state.applyServer(this,t,e))},e.prototype.applyOperations=function(t,e){this.setState(this.state.applyOperations(this,t,e))},e.prototype.serverAck=function(t){this.setState(this.state.serverAck(this,t))},e.prototype.serverReconnect=function(){"function"==typeof this.state.resend&&this.state.resend(this)},e.prototype.transformSelection=function(t){return this.state.transformSelection(t)},e.prototype.sendOperation=function(t,e){throw new Error("sendOperation must be defined in child class")},e.prototype.applyOperation=function(t){throw new Error("applyOperation must be defined in child class")},e.Synchronized=n,n.prototype.applyClient=function(t,e){return t.sendOperation(t.revision,e),new o(e)},n.prototype.applyServer=function(t,e,n){if(e-t.revision>1)throw new Error("Invalid revision.");return t.revision=e,t.applyOperation(n),this},n.prototype.serverAck=function(t,e){throw new Error("There is no pending operation.")},n.prototype.transformSelection=function(t){return t};var a=new n;return e.AwaitingConfirm=o,o.prototype.applyClient=function(t,e){return new r(this.outstanding,e)},o.prototype.applyServer=function(t,e,n){if(e-t.revision>1)throw new Error("Invalid revision.");t.revision=e;var r=n.constructor.transform(this.outstanding,n);return t.applyOperation(r[1]),new o(r[0])},o.prototype.serverAck=function(t,e){return e-t.revision>1?new i(this.outstanding,t,e).getOperations():(t.revision=e,a)},o.prototype.transformSelection=function(t){return t.transform(this.outstanding)},o.prototype.resend=function(t){t.sendOperation(t.revision,this.outstanding)},e.AwaitingWithBuffer=r,r.prototype.applyClient=function(t,e){var n=this.buffer.compose(e);return new r(this.outstanding,n)},r.prototype.applyServer=function(t,e,n){if(e-t.revision>1)throw new Error("Invalid revision.");t.revision=e;var o=n.constructor.transform,i=o(this.outstanding,n),s=o(this.buffer,i[1]);return t.applyOperation(s[1]),new r(i[0],s[0])},r.prototype.serverAck=function(t,e){return e-t.revision>1?new s(this.outstanding,this.buffer,t,e).getOperations():(t.revision=e,t.sendOperation(t.revision,this.buffer),new o(this.buffer))},r.prototype.transformSelection=function(t){return t.transform(this.outstanding).transform(this.buffer)},r.prototype.resend=function(t){t.sendOperation(t.revision,this.outstanding)},e.Stale=i,i.prototype.applyClient=function(t,e){return new s(this.acknowlaged,e,t,this.revision)},i.prototype.applyServer=function(t,e,n){throw new Error("Ignored server-side change.")},i.prototype.applyOperations=function(t,e,n){for(var o=this.acknowlaged.constructor.transform,r=0;re.line?1:t.che.ch?1:0}function o(t,e){return n(t,e)<=0}function r(t,e){return o(t,e)?t:e}function i(t,e){return o(t,e)?e:t}function s(t){return t.indexFromPos({line:t.lastLine(),ch:0})+t.getLine(t.lastLine()).length}function a(t,e){var n=t[e];t[e]=function(){n.apply(t,arguments)}}var h=ot.TextOperation,p=ot.Selection;e.prototype.detach=function(){this.cm.off("changes",this.onChanges),this.cm.off("change",this.onChange),this.cm.off("cursorActivity",this.onCursorActivity),this.cm.off("focus",this.onFocus),this.cm.off("blur",this.onBlur)},e.operationFromCodeMirrorChanges=function(t,e){function n(t){return t[t.length-1]}function r(t){if(0===t.length)return 0;for(var e=0,n=0;n=0;u--){var f=t[u];l=i(l,f);var d=l(f.from),g=a-d-r(f.text);p=(new h).retain(d)["delete"](r(f.removed)).insert(f.text.join("\n")).retain(g).compose(p),c=c.compose((new h).retain(d)["delete"](r(f.text)).insert(f.removed.join("\n")).retain(g)),a+=r(f.removed)-r(f.text)}return[p,c]},e.operationFromCodeMirrorChange=e.operationFromCodeMirrorChanges,e.applyOperationToCodeMirror=function(t,e){e.operation(function(){for(var n=t.ops,o=0,r=0,i=n.length;r0&&(this.majorRevision+=n.length,this.minorRevision=0);var o=t.events;if(o){for(e=0;e1&&(t-=1),6*t<1?i+6*(o-i)*t:2*t<1?o:3*t<2?i+6*(o-i)*(2/3-t):i};return r(s(t+1/3),s(t),s(t-1/3))}function s(t){for(var e=1,n=0;n0&&n.shouldBeComposedWithInverted(h(this.undoManager.undoStack).wrapped)),s=new t(this.selection,o);this.undoManager.add(new d(n,s),i),this.applyClient(e)},o.prototype.updateSelection=function(){this.selection=this.editorAdapter.getSelection()},o.prototype.onSelectionChange=function(){var t=this.selection;this.updateSelection(),t&&this.selection.equals(t)||this.sendSelection(this.selection)},o.prototype.onBlur=function(){this.selection=null,this.sendSelection(null)},o.prototype.sendSelection=function(t){this.state instanceof c.AwaitingWithBuffer||this.serverAdapter.sendSelection(t)},o.prototype.sendOperation=function(t,e){this.serverAdapter.sendOperation(t,e.toJSON(),this.selection)},o.prototype.getOperations=function(t,e){this.serverAdapter.getOperations(t,e)},o.prototype.applyOperation=function(t){this.editorAdapter.applyOperation(t),this.updateSelection(),this.undoManager.transform(new d(t,null))},o}(); \ No newline at end of file -- cgit v1.2.3