editor-markdown.vue 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. <template lang='pug'>
  2. .editor-markdown
  3. v-toolbar.editor-markdown-toolbar(dense, color='primary', dark, flat, style='overflow-x: hidden;')
  4. template(v-if='isModalShown')
  5. v-spacer
  6. v-btn.animated.fadeInRight(text, @click='closeAllModal')
  7. v-icon(left) mdi-arrow-left-circle
  8. span {{$t('editor:backToEditor')}}
  9. template(v-else)
  10. v-tooltip(bottom, color='primary')
  11. template(v-slot:activator='{ on }')
  12. v-btn.animated.fadeIn(icon, tile, v-on='on', @click='toggleMarkup({ start: `**` })').mx-0
  13. v-icon mdi-format-bold
  14. span {{$t('editor:markup.bold')}}
  15. v-tooltip(bottom, color='primary')
  16. template(v-slot:activator='{ on }')
  17. v-btn.animated.fadeIn.wait-p1s(icon, tile, v-on='on', @click='toggleMarkup({ start: `*` })').mx-0
  18. v-icon mdi-format-italic
  19. span {{$t('editor:markup.italic')}}
  20. v-tooltip(bottom, color='primary')
  21. template(v-slot:activator='{ on }')
  22. v-btn.animated.fadeIn.wait-p2s(icon, tile, v-on='on', @click='toggleMarkup({ start: `~~` })').mx-0
  23. v-icon mdi-format-strikethrough
  24. span {{$t('editor:markup.strikethrough')}}
  25. v-menu(offset-y, open-on-hover)
  26. template(v-slot:activator='{ on }')
  27. v-btn.animated.fadeIn.wait-p3s(icon, tile, v-on='on').mx-0
  28. v-icon mdi-format-header-pound
  29. v-list.py-0
  30. template(v-for='(n, idx) in 6')
  31. v-list-item(@click='setHeaderLine(n)', :key='idx')
  32. v-list-item-action
  33. v-icon(:size='24 - (idx - 1) * 2') mdi-format-header-{{n}}
  34. v-list-item-title {{$t('editor:markup.heading', { level: n })}}
  35. v-divider(v-if='idx < 5')
  36. v-tooltip(bottom, color='primary')
  37. template(v-slot:activator='{ on }')
  38. v-btn.animated.fadeIn.wait-p4s(icon, tile, v-on='on', @click='toggleMarkup({ start: `~` })').mx-0
  39. v-icon mdi-format-subscript
  40. span {{$t('editor:markup.subscript')}}
  41. v-tooltip(bottom, color='primary')
  42. template(v-slot:activator='{ on }')
  43. v-btn.animated.fadeIn.wait-p5s(icon, tile, v-on='on', @click='toggleMarkup({ start: `^` })').mx-0
  44. v-icon mdi-format-superscript
  45. span {{$t('editor:markup.superscript')}}
  46. v-menu(offset-y, open-on-hover)
  47. template(v-slot:activator='{ on }')
  48. v-btn.animated.fadeIn.wait-p6s(icon, tile, v-on='on').mx-0
  49. v-icon mdi-alpha-t-box-outline
  50. v-list.py-0
  51. v-list-item(@click='insertBeforeEachLine({ content: `> `})')
  52. v-list-item-action
  53. v-icon mdi-alpha-t-box-outline
  54. v-list-item-title {{$t('editor:markup.blockquote')}}
  55. v-divider
  56. v-list-item(@click='insertBeforeEachLine({ content: `> `, after: `{.is-info}`})')
  57. v-list-item-action
  58. v-icon(color='blue') mdi-alpha-i-box-outline
  59. v-list-item-title {{$t('editor:markup.blockquoteInfo')}}
  60. v-divider
  61. v-list-item(@click='insertBeforeEachLine({ content: `> `, after: `{.is-success}`})')
  62. v-list-item-action
  63. v-icon(color='success') mdi-alpha-s-box-outline
  64. v-list-item-title {{$t('editor:markup.blockquoteSuccess')}}
  65. v-divider
  66. v-list-item(@click='insertBeforeEachLine({ content: `> `, after: `{.is-warning}`})')
  67. v-list-item-action
  68. v-icon(color='warning') mdi-alpha-w-box-outline
  69. v-list-item-title {{$t('editor:markup.blockquoteWarning')}}
  70. v-divider
  71. v-list-item(@click='insertBeforeEachLine({ content: `> `, after: `{.is-danger}`})')
  72. v-list-item-action
  73. v-icon(color='error') mdi-alpha-e-box-outline
  74. v-list-item-title {{$t('editor:markup.blockquoteError')}}
  75. v-divider
  76. v-tooltip(bottom, color='primary')
  77. template(v-slot:activator='{ on }')
  78. v-btn.animated.fadeIn.wait-p7s(icon, tile, v-on='on', @click='insertBeforeEachLine({ content: `- `})').mx-0
  79. v-icon mdi-format-list-bulleted
  80. span {{$t('editor:markup.unorderedList')}}
  81. v-tooltip(bottom, color='primary')
  82. template(v-slot:activator='{ on }')
  83. v-btn.animated.fadeIn.wait-p8s(icon, tile, v-on='on', @click='insertBeforeEachLine({ content: `1. `})').mx-0
  84. v-icon mdi-format-list-numbered
  85. span {{$t('editor:markup.orderedList')}}
  86. v-tooltip(bottom, color='primary')
  87. template(v-slot:activator='{ on }')
  88. v-btn.animated.fadeIn.wait-p9s(icon, tile, v-on='on', @click='toggleMarkup({ start: "`" })').mx-0
  89. v-icon mdi-code-tags
  90. span {{$t('editor:markup.inlineCode')}}
  91. v-tooltip(bottom, color='primary')
  92. template(v-slot:activator='{ on }')
  93. v-btn.animated.fadeIn.wait-p10s(icon, tile, v-on='on', @click='toggleMarkup({ start: `<kbd>`, end: `</kbd>` })').mx-0
  94. v-icon mdi-keyboard-variant
  95. span {{$t('editor:markup.keyboardKey')}}
  96. v-tooltip(bottom, color='primary')
  97. template(v-slot:activator='{ on }')
  98. v-btn.animated.fadeIn.wait-p11s(icon, tile, v-on='on', @click='insertAfter({ content: `---`, newLine: true })').mx-0
  99. v-icon mdi-minus
  100. span {{$t('editor:markup.horizontalBar')}}
  101. template(v-if='$vuetify.breakpoint.mdAndUp')
  102. v-spacer
  103. v-tooltip(bottom, color='primary')
  104. template(v-slot:activator='{ on }')
  105. v-btn.animated.fadeIn.wait-p11s(icon, tile, v-on='on', @click='previewShown = !previewShown').mx-0
  106. v-icon mdi-book-open-outline
  107. span {{$t('editor:markup.togglePreviewPane')}}
  108. .editor-markdown-main
  109. .editor-markdown-sidebar
  110. v-tooltip(right, color='teal')
  111. template(v-slot:activator='{ on }')
  112. v-btn.animated.fadeInLeft(icon, tile, v-on='on', dark, disabled).mx-0
  113. v-icon mdi-link-plus
  114. span {{$t('editor:markup.insertLink')}}
  115. v-tooltip(right, color='teal')
  116. template(v-slot:activator='{ on }')
  117. v-btn.mt-3.animated.fadeInLeft.wait-p1s(icon, tile, v-on='on', dark, @click='toggleModal(`editorModalMedia`)').mx-0
  118. v-icon(:color='activeModal === `editorModalMedia` ? `teal` : ``') mdi-folder-multiple-image
  119. span {{$t('editor:markup.insertAssets')}}
  120. v-tooltip(right, color='teal')
  121. template(v-slot:activator='{ on }')
  122. v-btn.mt-3.animated.fadeInLeft.wait-p2s(icon, tile, v-on='on', dark, @click='toggleModal(`editorModalBlocks`)', disabled).mx-0
  123. v-icon(:color='activeModal === `editorModalBlocks` ? `teal` : ``') mdi-view-dashboard-outline
  124. span {{$t('editor:markup.insertBlock')}}
  125. v-tooltip(right, color='teal')
  126. template(v-slot:activator='{ on }')
  127. v-btn.mt-3.animated.fadeInLeft.wait-p3s(icon, tile, v-on='on', dark, disabled).mx-0
  128. v-icon mdi-code-braces
  129. span {{$t('editor:markup.insertCodeBlock')}}
  130. v-tooltip(right, color='teal')
  131. template(v-slot:activator='{ on }')
  132. v-btn.mt-3.animated.fadeInLeft.wait-p4s(icon, tile, v-on='on', dark, disabled).mx-0
  133. v-icon mdi-library-video
  134. span {{$t('editor:markup.insertVideoAudio')}}
  135. v-tooltip(right, color='teal')
  136. template(v-slot:activator='{ on }')
  137. v-btn.mt-3.animated.fadeInLeft.wait-p5s(icon, tile, v-on='on', dark, disabled).mx-0
  138. v-icon mdi-chart-multiline
  139. span {{$t('editor:markup.insertDiagram')}}
  140. v-tooltip(right, color='teal')
  141. template(v-slot:activator='{ on }')
  142. v-btn.mt-3.animated.fadeInLeft.wait-p6s(icon, tile, v-on='on', dark, disabled).mx-0
  143. v-icon mdi-function-variant
  144. span {{$t('editor:markup.insertMathExpression')}}
  145. v-tooltip(right, color='teal')
  146. template(v-slot:activator='{ on }')
  147. v-btn.mt-3.animated.fadeInLeft.wait-p7s(icon, tile, v-on='on', dark, disabled).mx-0
  148. v-icon mdi-table-plus
  149. span {{$t('editor:markup.tableHelper')}}
  150. template(v-if='$vuetify.breakpoint.mdAndUp')
  151. v-spacer
  152. v-tooltip(right, color='teal')
  153. template(v-slot:activator='{ on }')
  154. v-btn.mt-3.animated.fadeInLeft.wait-p8s(icon, tile, v-on='on', dark, @click='toggleFullscreen').mx-0
  155. v-icon mdi-arrow-expand-all
  156. span {{$t('editor:markup.distractionFreeMode')}}
  157. v-tooltip(right, color='teal')
  158. template(v-slot:activator='{ on }')
  159. v-btn.mt-3.animated.fadeInLeft.wait-p9s(icon, tile, v-on='on', dark, @click='toggleHelp').mx-0
  160. v-icon(:color='helpShown ? `teal` : ``') mdi-help-circle
  161. span {{$t('editor:markup.markdownFormattingHelp')}}
  162. .editor-markdown-editor
  163. textarea(ref='cm')
  164. transition(name='editor-markdown-preview')
  165. .editor-markdown-preview(v-if='previewShown')
  166. .editor-markdown-preview-content.contents(ref='editorPreviewContainer')
  167. div(ref='editorPreview', v-html='previewHTML')
  168. v-system-bar.editor-markdown-sysbar(dark, status, color='grey darken-3')
  169. .caption.editor-markdown-sysbar-locale {{locale.toUpperCase()}}
  170. .caption.px-3 /{{path}}
  171. template(v-if='$vuetify.breakpoint.mdAndUp')
  172. v-spacer
  173. .caption Markdown
  174. v-spacer
  175. .caption Ln {{cursorPos.line + 1}}, Col {{cursorPos.ch + 1}}
  176. markdown-help(v-if='helpShown')
  177. </template>
  178. <script>
  179. import _ from 'lodash'
  180. import { get, sync } from 'vuex-pathify'
  181. import markdownHelp from './markdown/help.vue'
  182. /* global siteConfig */
  183. // ========================================
  184. // IMPORTS
  185. // ========================================
  186. // Code Mirror
  187. import CodeMirror from 'codemirror'
  188. import 'codemirror/lib/codemirror.css'
  189. // Language
  190. import 'codemirror/mode/markdown/markdown.js'
  191. // Addons
  192. import 'codemirror/addon/selection/active-line.js'
  193. import 'codemirror/addon/display/fullscreen.js'
  194. import 'codemirror/addon/display/fullscreen.css'
  195. import 'codemirror/addon/selection/mark-selection.js'
  196. import 'codemirror/addon/search/searchcursor.js'
  197. // Markdown-it
  198. import MarkdownIt from 'markdown-it'
  199. import mdAttrs from 'markdown-it-attrs'
  200. import mdEmoji from 'markdown-it-emoji'
  201. import mdTaskLists from 'markdown-it-task-lists'
  202. import mdExpandTabs from 'markdown-it-expand-tabs'
  203. import mdAbbr from 'markdown-it-abbr'
  204. import mdSup from 'markdown-it-sup'
  205. import mdSub from 'markdown-it-sub'
  206. import mdMark from 'markdown-it-mark'
  207. import mdImsize from 'markdown-it-imsize'
  208. import katex from 'katex'
  209. import twemoji from 'twemoji'
  210. // Prism (Syntax Highlighting)
  211. import Prism from 'prismjs'
  212. // Helpers
  213. import katexHelper from './common/katex'
  214. // ========================================
  215. // INIT
  216. // ========================================
  217. // Platform detection
  218. const CtrlKey = /Mac/.test(navigator.platform) ? 'Cmd' : 'Ctrl'
  219. // Prism Config
  220. Prism.plugins.autoloader.languages_path = '/js/prism/'
  221. Prism.plugins.NormalizeWhitespace.setDefaults({
  222. 'remove-trailing': true,
  223. 'remove-indent': true,
  224. 'left-trim': true,
  225. 'right-trim': true,
  226. 'remove-initial-line-feed': true,
  227. 'tabs-to-spaces': 2
  228. })
  229. // Markdown Instance
  230. const md = new MarkdownIt({
  231. html: true,
  232. breaks: true,
  233. linkify: true,
  234. typography: true,
  235. highlight(str, lang) {
  236. return `<pre class="line-numbers"><code class="language-${lang}">${_.escape(str)}</code></pre>`
  237. }
  238. })
  239. .use(mdAttrs, {
  240. allowedAttributes: ['id', 'class', 'target']
  241. })
  242. .use(mdEmoji)
  243. .use(mdTaskLists, {label: true, labelAfter: true})
  244. .use(mdExpandTabs)
  245. .use(mdAbbr)
  246. .use(mdSup)
  247. .use(mdSub)
  248. .use(mdMark)
  249. .use(mdImsize)
  250. // ========================================
  251. // HELPER FUNCTIONS
  252. // ========================================
  253. // Inject line numbers for preview scroll sync
  254. let linesMap = []
  255. function injectLineNumbers (tokens, idx, options, env, slf) {
  256. let line
  257. if (tokens[idx].map && tokens[idx].level === 0) {
  258. line = tokens[idx].map[0]
  259. tokens[idx].attrJoin('class', 'line')
  260. tokens[idx].attrSet('data-line', String(line))
  261. linesMap.push(line)
  262. }
  263. return slf.renderToken(tokens, idx, options, env, slf)
  264. }
  265. md.renderer.rules.paragraph_open = injectLineNumbers
  266. md.renderer.rules.heading_open = injectLineNumbers
  267. md.renderer.rules.blockquote_open = injectLineNumbers
  268. // ========================================
  269. // KATEX
  270. // ========================================
  271. md.inline.ruler.after('escape', 'katex_inline', katexHelper.katexInline)
  272. md.renderer.rules.katex_inline = (tokens, idx) => {
  273. try {
  274. return katex.renderToString(tokens[idx].content, {
  275. displayMode: false
  276. })
  277. } catch (err) {
  278. console.warn(err)
  279. return tokens[idx].content
  280. }
  281. }
  282. md.block.ruler.after('blockquote', 'katex_block', katexHelper.katexBlock, {
  283. alt: [ 'paragraph', 'reference', 'blockquote', 'list' ]
  284. })
  285. md.renderer.rules.katex_block = (tokens, idx) => {
  286. try {
  287. return `<p>` + katex.renderToString(tokens[idx].content, {
  288. displayMode: true
  289. }) + `</p>`
  290. } catch (err) {
  291. console.warn(err)
  292. return tokens[idx].content
  293. }
  294. }
  295. // ========================================
  296. // TWEMOJI
  297. // ========================================
  298. md.renderer.rules.emoji = (token, idx) => {
  299. return twemoji.parse(token[idx].content, {
  300. callback (icon, opts) {
  301. return `/svg/twemoji/${icon}.svg`
  302. }
  303. })
  304. }
  305. // ========================================
  306. // Vue Component
  307. // ========================================
  308. export default {
  309. components: {
  310. markdownHelp
  311. },
  312. props: {
  313. save: {
  314. type: Function,
  315. default: () => {}
  316. }
  317. },
  318. data() {
  319. return {
  320. fabInsertMenu: false,
  321. cm: null,
  322. cursorPos: { ch: 0, line: 1 },
  323. previewShown: true,
  324. previewHTML: '',
  325. helpShown: false
  326. }
  327. },
  328. computed: {
  329. isMobile() {
  330. return this.$vuetify.breakpoint.smAndDown
  331. },
  332. isModalShown() {
  333. return this.helpShown || this.activeModal !== ''
  334. },
  335. locale: get('page/locale'),
  336. path: get('page/path'),
  337. mode: get('editor/mode'),
  338. activeModal: sync('editor/activeModal')
  339. },
  340. watch: {
  341. previewShown (newValue, oldValue) {
  342. if (newValue && !oldValue) {
  343. this.$nextTick(() => {
  344. Prism.highlightAllUnder(this.$refs.editorPreview)
  345. Array.from(this.$refs.editorPreview.querySelectorAll('pre.line-numbers')).forEach(pre => pre.classList.add('prismjs'))
  346. })
  347. }
  348. }
  349. },
  350. methods: {
  351. toggleModal(key) {
  352. this.activeModal = (this.activeModal === key) ? '' : key
  353. this.helpShown = false
  354. },
  355. closeAllModal() {
  356. this.activeModal = ''
  357. this.helpShown = false
  358. },
  359. onCmInput: _.debounce(function (newContent) {
  360. linesMap = []
  361. this.$store.set('editor/content', newContent)
  362. this.previewHTML = md.render(newContent)
  363. this.$nextTick(() => {
  364. Prism.highlightAllUnder(this.$refs.editorPreview)
  365. Array.from(this.$refs.editorPreview.querySelectorAll('pre.line-numbers')).forEach(pre => pre.classList.add('prismjs'))
  366. this.scrollSync(this.cm)
  367. })
  368. }, 500),
  369. onCmPaste (cm, ev) {
  370. // const clipItems = (ev.clipboardData || ev.originalEvent.clipboardData).items
  371. // for (let clipItem of clipItems) {
  372. // if (_.startsWith(clipItem.type, 'image/')) {
  373. // const file = clipItem.getAsFile()
  374. // const reader = new FileReader()
  375. // reader.onload = evt => {
  376. // this.$store.commit(`loadingStart`, 'editor-paste-image')
  377. // this.insertAfter({
  378. // content: `![${file.name}](${evt.target.result})`,
  379. // newLine: true
  380. // })
  381. // }
  382. // reader.readAsDataURL(file)
  383. // }
  384. // }
  385. },
  386. /**
  387. * Update cursor state
  388. */
  389. positionSync(cm) {
  390. this.cursorPos = cm.getCursor('head')
  391. },
  392. /**
  393. * Wrap selection with start / end tags
  394. */
  395. toggleMarkup({ start, end }) {
  396. if (!end) { end = start }
  397. if (!this.cm.doc.somethingSelected()) {
  398. return this.$store.commit('showNotification', {
  399. message: this.$t('editor:markup.noSelectionError'),
  400. style: 'warning',
  401. icon: 'warning'
  402. })
  403. }
  404. this.cm.doc.replaceSelections(this.cm.doc.getSelections().map(s => start + s + end))
  405. },
  406. /**
  407. * Set current line as header
  408. */
  409. setHeaderLine(lvl) {
  410. const curLine = this.cm.doc.getCursor('head').line
  411. let lineContent = this.cm.doc.getLine(curLine)
  412. const lineLength = lineContent.length
  413. if (_.startsWith(lineContent, '#')) {
  414. lineContent = lineContent.replace(/^(#+ )/, '')
  415. }
  416. lineContent = _.times(lvl, n => '#').join('') + ` ` + lineContent
  417. this.cm.doc.replaceRange(lineContent, { line: curLine, ch: 0 }, { line: curLine, ch: lineLength })
  418. },
  419. /**
  420. * Get the header lever of the current line
  421. */
  422. getHeaderLevel(cm) {
  423. const curLine = this.cm.doc.getCursor('head').line
  424. let lineContent = this.cm.doc.getLine(curLine)
  425. let lvl = 0
  426. const result = lineContent.match(/^(#+) /)
  427. if (result) {
  428. lvl = _.get(result, '[1]', '').length
  429. }
  430. return lvl
  431. },
  432. /**
  433. * Insert content at cursor
  434. */
  435. insertAtCursor({ content }) {
  436. const cursor = this.cm.doc.getCursor('head')
  437. this.cm.doc.replaceRange(content, cursor)
  438. },
  439. /**
  440. * Insert content after current line
  441. */
  442. insertAfter({ content, newLine }) {
  443. const curLine = this.cm.doc.getCursor('to').line
  444. const lineLength = this.cm.doc.getLine(curLine).length
  445. this.cm.doc.replaceRange(newLine ? `\n${content}\n` : content, { line: curLine, ch: lineLength + 1 })
  446. },
  447. /**
  448. * Insert content before current line
  449. */
  450. insertBeforeEachLine({ content, after }) {
  451. let lines = []
  452. if (!this.cm.doc.somethingSelected()) {
  453. lines.push(this.cm.doc.getCursor('head').line)
  454. } else {
  455. lines = _.flatten(this.cm.doc.listSelections().map(sl => {
  456. const range = Math.abs(sl.anchor.line - sl.head.line) + 1
  457. const lowestLine = (sl.anchor.line > sl.head.line) ? sl.head.line : sl.anchor.line
  458. return _.times(range, l => l + lowestLine)
  459. }))
  460. }
  461. lines.forEach(ln => {
  462. let lineContent = this.cm.doc.getLine(ln)
  463. const lineLength = lineContent.length
  464. if (_.startsWith(lineContent, content)) {
  465. lineContent = lineContent.substring(content.length)
  466. }
  467. this.cm.doc.replaceRange(content + lineContent, { line: ln, ch: 0 }, { line: ln, ch: lineLength })
  468. })
  469. if (after) {
  470. const lastLine = _.last(lines)
  471. this.cm.doc.replaceRange(`\n${after}\n`, { line: lastLine, ch: this.cm.doc.getLine(lastLine).length + 1 })
  472. }
  473. },
  474. /**
  475. * Update scroll sync
  476. */
  477. scrollSync: _.debounce(function (cm) {
  478. if (!this.previewShown || cm.somethingSelected()) { return }
  479. let currentLine = cm.getCursor().line
  480. if (currentLine < 3) {
  481. this.Velocity(this.$refs.editorPreview, 'stop', true)
  482. this.Velocity(this.$refs.editorPreview.firstChild, 'scroll', { offset: '-50', duration: 1000, container: this.$refs.editorPreviewContainer })
  483. } else {
  484. let closestLine = _.findLast(linesMap, n => n <= currentLine)
  485. let destElm = this.$refs.editorPreview.querySelector(`[data-line='${closestLine}']`)
  486. if (destElm) {
  487. this.Velocity(this.$refs.editorPreview, 'stop', true)
  488. this.Velocity(destElm, 'scroll', { offset: '-100', duration: 1000, container: this.$refs.editorPreviewContainer })
  489. }
  490. }
  491. }, 500),
  492. toggleHelp () {
  493. this.helpShown = !this.helpShown
  494. this.activeModal = ''
  495. },
  496. toggleFullscreen () {
  497. this.cm.setOption('fullScreen', true)
  498. },
  499. refresh() {
  500. this.$nextTick(() => {
  501. this.cm.refresh()
  502. })
  503. }
  504. },
  505. mounted() {
  506. this.$store.set('editor/editorKey', 'markdown')
  507. if (this.mode === 'create' && !this.$store.get('editor/content')) {
  508. this.$store.set('editor/content', '# Header\nYour content here')
  509. }
  510. // Initialize CodeMirror
  511. this.cm = CodeMirror.fromTextArea(this.$refs.cm, {
  512. tabSize: 2,
  513. mode: 'text/markdown',
  514. theme: 'wikijs-dark',
  515. lineNumbers: true,
  516. lineWrapping: true,
  517. line: true,
  518. styleActiveLine: true,
  519. highlightSelectionMatches: {
  520. annotateScrollbar: true
  521. },
  522. viewportMargin: 50,
  523. inputStyle: 'contenteditable',
  524. allowDropFileTypes: ['image/jpg', 'image/png', 'image/svg', 'image/jpeg', 'image/gif'],
  525. direction: siteConfig.rtl ? 'rtl' : 'ltr'
  526. })
  527. this.cm.setValue(this.$store.get('editor/content'))
  528. this.cm.on('change', c => {
  529. this.$store.set('editor/content', c.getValue())
  530. this.onCmInput(this.$store.get('editor/content'))
  531. })
  532. if (this.$vuetify.breakpoint.mdAndUp) {
  533. this.cm.setSize(null, 'calc(100vh - 112px - 24px)')
  534. } else {
  535. this.cm.setSize(null, 'calc(100vh - 112px - 16px)')
  536. }
  537. // Set Keybindings
  538. const keyBindings = {
  539. 'F11' (c) {
  540. c.setOption('fullScreen', !c.getOption('fullScreen'))
  541. },
  542. 'Esc' (c) {
  543. if (c.getOption('fullScreen')) c.setOption('fullScreen', false)
  544. }
  545. }
  546. _.set(keyBindings, `${CtrlKey}-S`, c => {
  547. this.save()
  548. return false
  549. })
  550. _.set(keyBindings, `${CtrlKey}-B`, c => {
  551. this.toggleMarkup({ start: `**` })
  552. return false
  553. })
  554. _.set(keyBindings, `${CtrlKey}-I`, c => {
  555. this.toggleMarkup({ start: `*` })
  556. return false
  557. })
  558. _.set(keyBindings, `${CtrlKey}-Alt-Right`, c => {
  559. let lvl = this.getHeaderLevel(c)
  560. if (lvl >= 6) { lvl = 5 }
  561. this.setHeaderLine(lvl + 1)
  562. return false
  563. })
  564. _.set(keyBindings, `${CtrlKey}-Alt-Left`, c => {
  565. let lvl = this.getHeaderLevel(c)
  566. if (lvl <= 1) { lvl = 2 }
  567. this.setHeaderLine(lvl - 1)
  568. return false
  569. })
  570. this.cm.setOption('extraKeys', keyBindings)
  571. // Handle cursor movement
  572. this.cm.on('cursorActivity', c => {
  573. this.positionSync(c)
  574. this.scrollSync(c)
  575. })
  576. // Handle special paste
  577. this.cm.on('paste', this.onCmPaste)
  578. // Render initial preview
  579. this.onCmInput(this.$store.get('editor/content'))
  580. this.refresh()
  581. this.$root.$on('editorInsert', opts => {
  582. switch (opts.kind) {
  583. case 'IMAGE':
  584. let img = `![${opts.text}](${opts.path})`
  585. if (opts.align && opts.align !== '') {
  586. img += `{.align-${opts.align}}`
  587. }
  588. this.insertAtCursor({
  589. content: img
  590. })
  591. break
  592. case 'BINARY':
  593. this.insertAtCursor({
  594. content: `[${opts.text}](${opts.path})`
  595. })
  596. break
  597. }
  598. })
  599. // Handle save conflict
  600. this.$root.$on('saveConflict', () => {
  601. this.toggleModal(`editorModalConflict`)
  602. })
  603. this.$root.$on('overwriteEditorContent', () => {
  604. this.cm.setValue(this.$store.get('editor/content'))
  605. })
  606. },
  607. beforeDestroy() {
  608. this.$root.$off('editorInsert')
  609. }
  610. }
  611. </script>
  612. <style lang='scss'>
  613. $editor-height: calc(100vh - 112px - 24px);
  614. $editor-height-mobile: calc(100vh - 112px - 16px);
  615. .editor-markdown {
  616. &-main {
  617. display: flex;
  618. width: 100%;
  619. }
  620. &-editor {
  621. background-color: darken(mc('grey', '900'), 4.5%);
  622. flex: 1 1 50%;
  623. display: block;
  624. height: $editor-height;
  625. position: relative;
  626. @include until($tablet) {
  627. height: $editor-height-mobile;
  628. }
  629. }
  630. &-preview {
  631. flex: 1 1 50%;
  632. background-color: mc('grey', '100');
  633. position: relative;
  634. height: $editor-height;
  635. overflow: hidden;
  636. padding: 1rem;
  637. @at-root .theme--dark & {
  638. background-color: mc('grey', '900');
  639. }
  640. @include until($tablet) {
  641. display: none;
  642. }
  643. &-enter-active, &-leave-active {
  644. transition: max-width .5s ease;
  645. max-width: 50vw;
  646. .editor-code-preview-content {
  647. width: 50vw;
  648. overflow:hidden;
  649. }
  650. }
  651. &-enter, &-leave-to {
  652. max-width: 0;
  653. }
  654. &-content {
  655. height: $editor-height;
  656. overflow-y: scroll;
  657. padding: 0;
  658. width: calc(100% + 17px);
  659. // -ms-overflow-style: none;
  660. // &::-webkit-scrollbar {
  661. // width: 0px;
  662. // background: transparent;
  663. // }
  664. @include until($tablet) {
  665. height: $editor-height-mobile;
  666. }
  667. }
  668. }
  669. &-toolbar {
  670. background-color: mc('blue', '700');
  671. background-image: linear-gradient(to bottom, mc('blue', '700') 0%, mc('blue','800') 100%);
  672. color: #FFF;
  673. .v-toolbar__content {
  674. padding-left: 64px;
  675. @include until($tablet) {
  676. padding-left: 8px;
  677. }
  678. }
  679. }
  680. &-insert:not(.v-speed-dial--right) {
  681. @include from($tablet) {
  682. left: 50%;
  683. margin-left: -28px;
  684. }
  685. }
  686. &-sidebar {
  687. background-color: mc('grey', '900');
  688. width: 64px;
  689. display: flex;
  690. flex-direction: column;
  691. justify-content: flex-start;
  692. align-items: center;
  693. padding: 24px 0;
  694. @include until($tablet) {
  695. padding: 12px 0;
  696. width: 40px;
  697. }
  698. }
  699. &-sysbar {
  700. padding-left: 0;
  701. &-locale {
  702. background-color: rgba(255,255,255,.25);
  703. display:inline-flex;
  704. padding: 0 12px;
  705. height: 24px;
  706. width: 63px;
  707. justify-content: center;
  708. align-items: center;
  709. }
  710. }
  711. // ==========================================
  712. // Fix FAB revealing under codemirror
  713. // ==========================================
  714. .speed-dial--fixed {
  715. z-index: 8;
  716. }
  717. // ==========================================
  718. // CODE MIRROR
  719. // ==========================================
  720. .CodeMirror {
  721. height: auto;
  722. font-family: 'Roboto Mono', monospace;
  723. font-size: .9rem;
  724. .cm-header-1 {
  725. font-size: 1.5rem;
  726. }
  727. .cm-header-2 {
  728. font-size: 1.25rem;
  729. }
  730. .cm-header-3 {
  731. font-size: 1.15rem;
  732. }
  733. .cm-header-4 {
  734. font-size: 1.1rem;
  735. }
  736. .cm-header-5 {
  737. font-size: 1.05rem;
  738. }
  739. .cm-header-6 {
  740. font-size: 1.025rem;
  741. }
  742. }
  743. .CodeMirror-focused .cm-matchhighlight {
  744. background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFklEQVQI12NgYGBgkKzc8x9CMDAwAAAmhwSbidEoSQAAAABJRU5ErkJggg==);
  745. background-position: bottom;
  746. background-repeat: repeat-x;
  747. }
  748. .cm-matchhighlight {
  749. background-color: mc('grey', '800');
  750. }
  751. .CodeMirror-selection-highlight-scrollbar {
  752. background-color: mc('green', '600');
  753. }
  754. .cm-s-wikijs-dark.CodeMirror {
  755. background: darken(mc('grey','900'), 3%);
  756. color: #e0e0e0;
  757. }
  758. .cm-s-wikijs-dark div.CodeMirror-selected {
  759. background: mc('blue','800');
  760. }
  761. .cm-s-wikijs-dark .cm-matchhighlight {
  762. background: mc('blue','800');
  763. }
  764. .cm-s-wikijs-dark .CodeMirror-line::selection, .cm-s-wikijs-dark .CodeMirror-line > span::selection, .cm-s-wikijs-dark .CodeMirror-line > span > span::selection {
  765. background: mc('amber', '500');
  766. }
  767. .cm-s-wikijs-dark .CodeMirror-line::-moz-selection, .cm-s-wikijs-dark .CodeMirror-line > span::-moz-selection, .cm-s-wikijs-dark .CodeMirror-line > span > span::-moz-selection {
  768. background: mc('amber', '500');
  769. }
  770. .cm-s-wikijs-dark .CodeMirror-gutters {
  771. background: darken(mc('grey','900'), 6%);
  772. border-right: 1px solid mc('grey','900');
  773. }
  774. .cm-s-wikijs-dark .CodeMirror-guttermarker {
  775. color: #ac4142;
  776. }
  777. .cm-s-wikijs-dark .CodeMirror-guttermarker-subtle {
  778. color: #505050;
  779. }
  780. .cm-s-wikijs-dark .CodeMirror-linenumber {
  781. color: mc('grey','800');
  782. }
  783. .cm-s-wikijs-dark .CodeMirror-cursor {
  784. border-left: 1px solid #b0b0b0;
  785. }
  786. .cm-s-wikijs-dark span.cm-comment {
  787. color: mc('orange','800');
  788. }
  789. .cm-s-wikijs-dark span.cm-atom {
  790. color: #aa759f;
  791. }
  792. .cm-s-wikijs-dark span.cm-number {
  793. color: #aa759f;
  794. }
  795. .cm-s-wikijs-dark span.cm-property, .cm-s-wikijs-dark span.cm-attribute {
  796. color: #90a959;
  797. }
  798. .cm-s-wikijs-dark span.cm-keyword {
  799. color: #ac4142;
  800. }
  801. .cm-s-wikijs-dark span.cm-string {
  802. color: #f4bf75;
  803. }
  804. .cm-s-wikijs-dark span.cm-variable {
  805. color: #90a959;
  806. }
  807. .cm-s-wikijs-dark span.cm-variable-2 {
  808. color: #6a9fb5;
  809. }
  810. .cm-s-wikijs-dark span.cm-def {
  811. color: #d28445;
  812. }
  813. .cm-s-wikijs-dark span.cm-bracket {
  814. color: #e0e0e0;
  815. }
  816. .cm-s-wikijs-dark span.cm-tag {
  817. color: #ac4142;
  818. }
  819. .cm-s-wikijs-dark span.cm-link {
  820. color: #aa759f;
  821. }
  822. .cm-s-wikijs-dark span.cm-error {
  823. background: #ac4142;
  824. color: #b0b0b0;
  825. }
  826. .cm-s-wikijs-dark .CodeMirror-activeline-background {
  827. background: mc('grey','900');
  828. }
  829. .cm-s-wikijs-dark .CodeMirror-matchingbracket {
  830. text-decoration: underline;
  831. color: white !important;
  832. }
  833. }
  834. </style>