You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1141 lines
36 KiB

5 years ago
5 years ago
5 years ago
  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', v-if='previewShown')
  104. template(v-slot:activator='{ on }')
  105. v-btn.animated.fadeIn.wait-p1s(icon, tile, v-on='on', @click='spellModeActive = !spellModeActive').mx-0
  106. v-icon(:color='spellModeActive ? `amber` : `white`') mdi-spellcheck
  107. span {{$t('editor:markup.toggleSpellcheck')}}
  108. v-tooltip(bottom, color='primary')
  109. template(v-slot:activator='{ on }')
  110. v-btn.animated.fadeIn.wait-p2s(icon, tile, v-on='on', @click='previewShown = !previewShown').mx-0
  111. v-icon mdi-book-open-outline
  112. span {{$t('editor:markup.togglePreviewPane')}}
  113. .editor-markdown-main
  114. .editor-markdown-sidebar
  115. v-tooltip(right, color='teal')
  116. template(v-slot:activator='{ on }')
  117. v-btn.animated.fadeInLeft(icon, tile, v-on='on', dark, @click='insertLink').mx-0
  118. v-icon mdi-link-plus
  119. span {{$t('editor:markup.insertLink')}}
  120. v-tooltip(right, color='teal')
  121. template(v-slot:activator='{ on }')
  122. v-btn.mt-3.animated.fadeInLeft.wait-p1s(icon, tile, v-on='on', dark, @click='toggleModal(`editorModalMedia`)').mx-0
  123. v-icon(:color='activeModal === `editorModalMedia` ? `teal` : ``') mdi-folder-multiple-image
  124. span {{$t('editor:markup.insertAssets')}}
  125. v-tooltip(right, color='teal')
  126. template(v-slot:activator='{ on }')
  127. v-btn.mt-3.animated.fadeInLeft.wait-p2s(icon, tile, v-on='on', dark, disabled, @click='toggleModal(`editorModalBlocks`)').mx-0
  128. v-icon(:color='activeModal === `editorModalBlocks` ? `teal` : ``') mdi-view-dashboard-outline
  129. span {{$t('editor:markup.insertBlock')}}
  130. v-tooltip(right, color='teal')
  131. template(v-slot:activator='{ on }')
  132. v-btn.mt-3.animated.fadeInLeft.wait-p3s(icon, tile, v-on='on', dark, disabled).mx-0
  133. v-icon mdi-code-braces
  134. span {{$t('editor:markup.insertCodeBlock')}}
  135. v-tooltip(right, color='teal')
  136. template(v-slot:activator='{ on }')
  137. v-btn.mt-3.animated.fadeInLeft.wait-p4s(icon, tile, v-on='on', dark, disabled).mx-0
  138. v-icon mdi-movie
  139. span {{$t('editor:markup.insertVideoAudio')}}
  140. v-tooltip(right, color='teal')
  141. template(v-slot:activator='{ on }')
  142. v-btn.mt-3.animated.fadeInLeft.wait-p5s(icon, tile, v-on='on', dark, @click='toggleModal(`editorModalDrawio`)').mx-0
  143. v-icon mdi-chart-multiline
  144. span {{$t('editor:markup.insertDiagram')}}
  145. v-tooltip(right, color='teal')
  146. template(v-slot:activator='{ on }')
  147. v-btn.mt-3.animated.fadeInLeft.wait-p6s(icon, tile, v-on='on', dark, disabled).mx-0
  148. v-icon mdi-function-variant
  149. span {{$t('editor:markup.insertMathExpression')}}
  150. v-tooltip(right, color='teal')
  151. template(v-slot:activator='{ on }')
  152. v-btn.mt-3.animated.fadeInLeft.wait-p7s(icon, tile, v-on='on', dark, disabled).mx-0
  153. v-icon mdi-table-plus
  154. span {{$t('editor:markup.tableHelper')}}
  155. template(v-if='$vuetify.breakpoint.mdAndUp')
  156. v-spacer
  157. v-tooltip(right, color='teal')
  158. template(v-slot:activator='{ on }')
  159. v-btn.mt-3.animated.fadeInLeft.wait-p8s(icon, tile, v-on='on', dark, @click='toggleFullscreen').mx-0
  160. v-icon mdi-arrow-expand-all
  161. span {{$t('editor:markup.distractionFreeMode')}}
  162. v-tooltip(right, color='teal')
  163. template(v-slot:activator='{ on }')
  164. v-btn.mt-3.animated.fadeInLeft.wait-p9s(icon, tile, v-on='on', dark, @click='toggleHelp').mx-0
  165. v-icon(:color='helpShown ? `teal` : ``') mdi-help-circle
  166. span {{$t('editor:markup.markdownFormattingHelp')}}
  167. .editor-markdown-editor
  168. textarea(ref='cm')
  169. transition(name='editor-markdown-preview')
  170. .editor-markdown-preview(v-if='previewShown')
  171. .editor-markdown-preview-content.contents(ref='editorPreviewContainer')
  172. div(
  173. ref='editorPreview'
  174. v-html='previewHTML'
  175. :spellcheck='spellModeActive'
  176. :contenteditable='spellModeActive'
  177. @blur='spellModeActive = false'
  178. )
  179. v-system-bar.editor-markdown-sysbar(dark, status, color='grey darken-3')
  180. .caption.editor-markdown-sysbar-locale {{locale.toUpperCase()}}
  181. .caption.px-3 /{{path}}
  182. template(v-if='$vuetify.breakpoint.mdAndUp')
  183. v-spacer
  184. .caption Markdown
  185. v-spacer
  186. .caption Ln {{cursorPos.line + 1}}, Col {{cursorPos.ch + 1}}
  187. markdown-help(v-if='helpShown')
  188. page-selector(mode='select', v-model='insertLinkDialog', :open-handler='insertLinkHandler', :path='path', :locale='locale')
  189. </template>
  190. <script>
  191. import _ from 'lodash'
  192. import { get, sync } from 'vuex-pathify'
  193. import markdownHelp from './markdown/help.vue'
  194. import gql from 'graphql-tag'
  195. import DOMPurify from 'dompurify'
  196. /* global siteConfig, siteLangs */
  197. // ========================================
  198. // IMPORTS
  199. // ========================================
  200. // Code Mirror
  201. import CodeMirror from 'codemirror'
  202. import 'codemirror/lib/codemirror.css'
  203. // Language
  204. import 'codemirror/mode/markdown/markdown.js'
  205. // Addons
  206. import 'codemirror/addon/selection/active-line.js'
  207. import 'codemirror/addon/display/fullscreen.js'
  208. import 'codemirror/addon/display/fullscreen.css'
  209. import 'codemirror/addon/selection/mark-selection.js'
  210. import 'codemirror/addon/search/searchcursor.js'
  211. import 'codemirror/addon/hint/show-hint.js'
  212. import 'codemirror/addon/fold/foldcode.js'
  213. import 'codemirror/addon/fold/foldgutter.js'
  214. import 'codemirror/addon/fold/foldgutter.css'
  215. import './markdown/fold'
  216. // Markdown-it
  217. import MarkdownIt from 'markdown-it'
  218. import mdAttrs from 'markdown-it-attrs'
  219. import mdEmoji from 'markdown-it-emoji'
  220. import mdTaskLists from 'markdown-it-task-lists'
  221. import mdExpandTabs from 'markdown-it-expand-tabs'
  222. import mdAbbr from 'markdown-it-abbr'
  223. import mdSup from 'markdown-it-sup'
  224. import mdSub from 'markdown-it-sub'
  225. import mdMark from 'markdown-it-mark'
  226. import mdMultiTable from 'markdown-it-multimd-table'
  227. import mdFootnote from 'markdown-it-footnote'
  228. import mdImsize from 'markdown-it-imsize'
  229. import katex from 'katex'
  230. import underline from '../../libs/markdown-it-underline'
  231. import 'katex/dist/contrib/mhchem'
  232. import twemoji from 'twemoji'
  233. import plantuml from './markdown/plantuml'
  234. // Prism (Syntax Highlighting)
  235. import Prism from 'prismjs'
  236. // Mermaid
  237. import mermaid from 'mermaid'
  238. // Helpers
  239. import katexHelper from './common/katex'
  240. import tabsetHelper from './markdown/tabset'
  241. // ========================================
  242. // INIT
  243. // ========================================
  244. // Platform detection
  245. const CtrlKey = /Mac/.test(navigator.platform) ? 'Cmd' : 'Ctrl'
  246. // Prism Config
  247. Prism.plugins.autoloader.languages_path = '/_assets/js/prism/'
  248. Prism.plugins.NormalizeWhitespace.setDefaults({
  249. 'remove-trailing': true,
  250. 'remove-indent': true,
  251. 'left-trim': true,
  252. 'right-trim': true,
  253. 'remove-initial-line-feed': true,
  254. 'tabs-to-spaces': 2
  255. })
  256. // Markdown Instance
  257. const md = new MarkdownIt({
  258. html: true,
  259. breaks: true,
  260. linkify: true,
  261. typography: true,
  262. highlight(str, lang) {
  263. if (lang === 'diagram') {
  264. return `<pre class="diagram">` + Buffer.from(str, 'base64').toString() + `</pre>`
  265. } else if (['mermaid', 'plantuml'].includes(lang)) {
  266. return `<pre class="codeblock-${lang}"><code>${_.escape(str)}</code></pre>`
  267. } else {
  268. return `<pre class="line-numbers"><code class="language-${lang}">${_.escape(str)}</code></pre>`
  269. }
  270. }
  271. })
  272. .use(mdAttrs, {
  273. allowedAttributes: ['id', 'class', 'target']
  274. })
  275. .use(underline)
  276. .use(mdEmoji)
  277. .use(mdTaskLists, {label: true, labelAfter: true})
  278. .use(mdExpandTabs)
  279. .use(mdAbbr)
  280. .use(mdSup)
  281. .use(mdSub)
  282. .use(mdMultiTable, {multiline: true, rowspan: true, headerless: true})
  283. .use(mdMark)
  284. .use(mdFootnote)
  285. .use(mdImsize)
  286. // DOMPurify fix for draw.io
  287. DOMPurify.addHook('uponSanitizeElement', (elm) => {
  288. if (elm.querySelectorAll) {
  289. const breaks = elm.querySelectorAll('foreignObject br, foreignObject p')
  290. if (breaks && breaks.length) {
  291. for (let i = 0; i < breaks.length; i++) {
  292. breaks[i].parentNode.replaceChild(
  293. document.createElement('div'),
  294. breaks[i]
  295. )
  296. }
  297. }
  298. }
  299. })
  300. // ========================================
  301. // HELPER FUNCTIONS
  302. // ========================================
  303. // Inject line numbers for preview scroll sync
  304. let linesMap = []
  305. function injectLineNumbers (tokens, idx, options, env, slf) {
  306. let line
  307. if (tokens[idx].map && tokens[idx].level === 0) {
  308. line = tokens[idx].map[0]
  309. tokens[idx].attrJoin('class', 'line')
  310. tokens[idx].attrSet('data-line', String(line))
  311. linesMap.push(line)
  312. }
  313. return slf.renderToken(tokens, idx, options, env, slf)
  314. }
  315. md.renderer.rules.paragraph_open = injectLineNumbers
  316. md.renderer.rules.heading_open = injectLineNumbers
  317. md.renderer.rules.blockquote_open = injectLineNumbers
  318. // ========================================
  319. // PLANTUML
  320. // ========================================
  321. // TODO: Use same options as defined in backend
  322. plantuml.init(md, {})
  323. // ========================================
  324. // KATEX
  325. // ========================================
  326. md.inline.ruler.after('escape', 'katex_inline', katexHelper.katexInline)
  327. md.renderer.rules.katex_inline = (tokens, idx) => {
  328. try {
  329. return katex.renderToString(tokens[idx].content, {
  330. displayMode: false
  331. })
  332. } catch (err) {
  333. console.warn(err)
  334. return tokens[idx].content
  335. }
  336. }
  337. md.block.ruler.after('blockquote', 'katex_block', katexHelper.katexBlock, {
  338. alt: [ 'paragraph', 'reference', 'blockquote', 'list' ]
  339. })
  340. md.renderer.rules.katex_block = (tokens, idx) => {
  341. try {
  342. return `<p>` + katex.renderToString(tokens[idx].content, {
  343. displayMode: true
  344. }) + `</p>`
  345. } catch (err) {
  346. console.warn(err)
  347. return tokens[idx].content
  348. }
  349. }
  350. // ========================================
  351. // TWEMOJI
  352. // ========================================
  353. md.renderer.rules.emoji = (token, idx) => {
  354. return twemoji.parse(token[idx].content, {
  355. callback (icon, opts) {
  356. return `/_assets/svg/twemoji/${icon}.svg`
  357. }
  358. })
  359. }
  360. // ========================================
  361. // Vue Component
  362. // ========================================
  363. let mermaidId = 0
  364. export default {
  365. components: {
  366. markdownHelp
  367. },
  368. props: {
  369. save: {
  370. type: Function,
  371. default: () => {}
  372. }
  373. },
  374. data() {
  375. return {
  376. fabInsertMenu: false,
  377. cm: null,
  378. cursorPos: { ch: 0, line: 1 },
  379. previewShown: true,
  380. previewHTML: '',
  381. helpShown: false,
  382. spellModeActive: false,
  383. insertLinkDialog: false
  384. }
  385. },
  386. computed: {
  387. isMobile() {
  388. return this.$vuetify.breakpoint.smAndDown
  389. },
  390. isModalShown() {
  391. return this.helpShown || this.activeModal !== ''
  392. },
  393. locale: get('page/locale'),
  394. path: get('page/path'),
  395. mode: get('editor/mode'),
  396. activeModal: sync('editor/activeModal')
  397. },
  398. watch: {
  399. previewShown (newValue, oldValue) {
  400. if (newValue && !oldValue) {
  401. this.$nextTick(() => {
  402. this.renderMermaidDiagrams()
  403. Prism.highlightAllUnder(this.$refs.editorPreview)
  404. Array.from(this.$refs.editorPreview.querySelectorAll('pre.line-numbers')).forEach(pre => pre.classList.add('prismjs'))
  405. })
  406. }
  407. },
  408. spellModeActive (newValue, oldValue) {
  409. if (newValue) {
  410. this.$nextTick(() => {
  411. this.$refs.editorPreview.focus()
  412. })
  413. }
  414. }
  415. },
  416. methods: {
  417. toggleModal(key) {
  418. this.activeModal = (this.activeModal === key) ? '' : key
  419. this.helpShown = false
  420. },
  421. closeAllModal() {
  422. this.activeModal = ''
  423. this.helpShown = false
  424. },
  425. onCmInput: _.debounce(function (newContent) {
  426. this.processContent(newContent)
  427. }, 600),
  428. onCmPaste (cm, ev) {
  429. // const clipItems = (ev.clipboardData || ev.originalEvent.clipboardData).items
  430. // for (let clipItem of clipItems) {
  431. // if (_.startsWith(clipItem.type, 'image/')) {
  432. // const file = clipItem.getAsFile()
  433. // const reader = new FileReader()
  434. // reader.onload = evt => {
  435. // this.$store.commit(`loadingStart`, 'editor-paste-image')
  436. // this.insertAfter({
  437. // content: `![${file.name}](${evt.target.result})`,
  438. // newLine: true
  439. // })
  440. // }
  441. // reader.readAsDataURL(file)
  442. // }
  443. // }
  444. },
  445. processContent (newContent) {
  446. linesMap = []
  447. // this.$store.set('editor/content', newContent)
  448. this.processMarkers(this.cm.firstLine(), this.cm.lastLine())
  449. this.previewHTML = DOMPurify.sanitize(md.render(newContent), {
  450. ADD_TAGS: ['foreignObject']
  451. })
  452. this.$nextTick(() => {
  453. tabsetHelper.format()
  454. this.renderMermaidDiagrams()
  455. Prism.highlightAllUnder(this.$refs.editorPreview)
  456. Array.from(this.$refs.editorPreview.querySelectorAll('pre.line-numbers')).forEach(pre => pre.classList.add('prismjs'))
  457. this.scrollSync(this.cm)
  458. })
  459. },
  460. /**
  461. * Update cursor state
  462. */
  463. positionSync(cm) {
  464. this.cursorPos = cm.getCursor('head')
  465. },
  466. /**
  467. * Wrap selection with start / end tags
  468. */
  469. toggleMarkup({ start, end }) {
  470. if (!end) { end = start }
  471. if (!this.cm.doc.somethingSelected()) {
  472. return this.$store.commit('showNotification', {
  473. message: this.$t('editor:markup.noSelectionError'),
  474. style: 'warning',
  475. icon: 'warning'
  476. })
  477. }
  478. this.cm.doc.replaceSelections(this.cm.doc.getSelections().map(s => start + s + end))
  479. },
  480. /**
  481. * Set current line as header
  482. */
  483. setHeaderLine(lvl) {
  484. const curLine = this.cm.doc.getCursor('head').line
  485. let lineContent = this.cm.doc.getLine(curLine)
  486. const lineLength = lineContent.length
  487. if (_.startsWith(lineContent, '#')) {
  488. lineContent = lineContent.replace(/^(#+ )/, '')
  489. }
  490. lineContent = _.times(lvl, n => '#').join('') + ` ` + lineContent
  491. this.cm.doc.replaceRange(lineContent, { line: curLine, ch: 0 }, { line: curLine, ch: lineLength })
  492. },
  493. /**
  494. * Get the header lever of the current line
  495. */
  496. getHeaderLevel(cm) {
  497. const curLine = this.cm.doc.getCursor('head').line
  498. let lineContent = this.cm.doc.getLine(curLine)
  499. let lvl = 0
  500. const result = lineContent.match(/^(#+) /)
  501. if (result) {
  502. lvl = _.get(result, '[1]', '').length
  503. }
  504. return lvl
  505. },
  506. /**
  507. * Insert content at cursor
  508. */
  509. insertAtCursor({ content }) {
  510. const cursor = this.cm.doc.getCursor('head')
  511. this.cm.doc.replaceRange(content, cursor)
  512. },
  513. /**
  514. * Insert content after current line
  515. */
  516. insertAfter({ content, newLine }) {
  517. const curLine = this.cm.doc.getCursor('to').line
  518. const lineLength = this.cm.doc.getLine(curLine).length
  519. this.cm.doc.replaceRange(newLine ? `\n${content}\n` : content, { line: curLine, ch: lineLength + 1 })
  520. },
  521. /**
  522. * Insert content before current line
  523. */
  524. insertBeforeEachLine({ content, after }) {
  525. let lines = []
  526. if (!this.cm.doc.somethingSelected()) {
  527. lines.push(this.cm.doc.getCursor('head').line)
  528. } else {
  529. lines = _.flatten(this.cm.doc.listSelections().map(sl => {
  530. const range = Math.abs(sl.anchor.line - sl.head.line) + 1
  531. const lowestLine = (sl.anchor.line > sl.head.line) ? sl.head.line : sl.anchor.line
  532. return _.times(range, l => l + lowestLine)
  533. }))
  534. }
  535. lines.forEach(ln => {
  536. let lineContent = this.cm.doc.getLine(ln)
  537. const lineLength = lineContent.length
  538. if (_.startsWith(lineContent, content)) {
  539. lineContent = lineContent.substring(content.length)
  540. }
  541. this.cm.doc.replaceRange(content + lineContent, { line: ln, ch: 0 }, { line: ln, ch: lineLength })
  542. })
  543. if (after) {
  544. const lastLine = _.last(lines)
  545. this.cm.doc.replaceRange(`\n${after}\n`, { line: lastLine, ch: this.cm.doc.getLine(lastLine).length + 1 })
  546. }
  547. },
  548. /**
  549. * Update scroll sync
  550. */
  551. scrollSync: _.debounce(function (cm) {
  552. if (!this.previewShown || cm.somethingSelected()) { return }
  553. let currentLine = cm.getCursor().line
  554. if (currentLine < 3) {
  555. this.Velocity(this.$refs.editorPreview, 'stop', true)
  556. this.Velocity(this.$refs.editorPreview.firstChild, 'scroll', { offset: '-50', duration: 1000, container: this.$refs.editorPreviewContainer })
  557. } else {
  558. let closestLine = _.findLast(linesMap, n => n <= currentLine)
  559. let destElm = this.$refs.editorPreview.querySelector(`[data-line='${closestLine}']`)
  560. if (destElm) {
  561. this.Velocity(this.$refs.editorPreview, 'stop', true)
  562. this.Velocity(destElm, 'scroll', { offset: '-100', duration: 1000, container: this.$refs.editorPreviewContainer })
  563. }
  564. }
  565. }, 500),
  566. toggleHelp () {
  567. this.helpShown = !this.helpShown
  568. this.activeModal = ''
  569. },
  570. toggleFullscreen () {
  571. this.cm.setOption('fullScreen', true)
  572. },
  573. refresh() {
  574. this.$nextTick(() => {
  575. this.cm.refresh()
  576. })
  577. },
  578. renderMermaidDiagrams () {
  579. document.querySelectorAll('.editor-markdown-preview pre.codeblock-mermaid > code').forEach(elm => {
  580. mermaidId++
  581. const mermaidDef = elm.innerText
  582. const mmElm = document.createElement('div')
  583. mmElm.innerHTML = `<div id="mermaid-id-${mermaidId}">${mermaid.render(`mermaid-id-${mermaidId}`, mermaidDef)}</div>`
  584. elm.parentElement.replaceWith(mmElm)
  585. })
  586. },
  587. autocomplete (cm, change) {
  588. if (cm.getModeAt(cm.getCursor()).name !== 'markdown') {
  589. return
  590. }
  591. // Links
  592. if (change.text[0] === '(') {
  593. const curLine = cm.getLine(change.from.line).substring(0, change.from.ch)
  594. if (curLine[curLine.length - 1] === ']') {
  595. cm.showHint({
  596. hint: async (cm, options) => {
  597. const cur = cm.getCursor()
  598. const curLine = cm.getLine(cur.line).substring(0, cur.ch)
  599. const queryString = curLine.substring(curLine.lastIndexOf('[')+1,curLine.length-2)
  600. const token = cm.getTokenAt(cur)
  601. try {
  602. const respRaw = await this.$apollo.query({
  603. query: gql`
  604. query ($query: String!, $locale: String) {
  605. pages {
  606. search(query:$query, locale:$locale) {
  607. results {
  608. title
  609. path
  610. locale
  611. }
  612. totalHits
  613. }
  614. }
  615. }
  616. `,
  617. variables: {
  618. query: queryString,
  619. locale: this.locale
  620. },
  621. fetchPolicy: 'cache-first'
  622. })
  623. const resp = _.get(respRaw, 'data.pages.search', {})
  624. if (resp && resp.totalHits > 0) {
  625. return {
  626. list: resp.results.map(r => ({
  627. text: '(' + (siteLangs.length > 0 ? `/${r.locale}/${r.path}` : `/${r.path}`) + ')',
  628. displayText: siteLangs.length > 0 ? `/${r.locale}/${r.path} - ${r.title}` : `/${r.path} - ${r.title}`
  629. })),
  630. from: CodeMirror.Pos(cur.line, token.start),
  631. to: CodeMirror.Pos(cur.line, token.end)
  632. }
  633. }
  634. } catch (err) {}
  635. return {
  636. list: [],
  637. from: CodeMirror.Pos(cur.line, token.start),
  638. to: CodeMirror.Pos(cur.line, token.end)
  639. }
  640. }
  641. })
  642. }
  643. }
  644. },
  645. insertLink () {
  646. this.insertLinkDialog = true
  647. },
  648. insertLinkHandler ({ locale, path }) {
  649. const lastPart = _.last(path.split('/'))
  650. this.insertAtCursor({
  651. content: siteLangs.length > 0 ? `[${lastPart}](/${locale}/${path})` : `[${lastPart}](/${path})`
  652. })
  653. },
  654. processMarkers (from, to) {
  655. let found = null
  656. let foundStart = 0
  657. this.cm.doc.getAllMarks().forEach(mk => {
  658. if (mk.__kind) {
  659. mk.clear()
  660. }
  661. })
  662. this.cm.eachLine(from, to, ln => {
  663. const line = ln.lineNo()
  664. if (ln.text.startsWith('```diagram')) {
  665. found = 'diagram'
  666. foundStart = line
  667. } else if (ln.text === '```' && found) {
  668. switch (found) {
  669. // ------------------------------
  670. // -> DIAGRAM
  671. // ------------------------------
  672. case 'diagram': {
  673. if (line - foundStart !== 2) {
  674. return
  675. }
  676. this.addMarker({
  677. kind: 'diagram',
  678. from: { line: foundStart, ch: 3 },
  679. to: { line: foundStart, ch: 10 },
  680. text: 'Edit Diagram',
  681. action: ((start, end) => {
  682. return (ev) => {
  683. this.cm.doc.setSelection({ line: start, ch: 0 }, { line: end, ch: 3 })
  684. try {
  685. const raw = this.cm.doc.getLine(end - 1)
  686. this.$store.set('editor/activeModalData', Buffer.from(raw, 'base64').toString())
  687. this.toggleModal(`editorModalDrawio`)
  688. } catch (err) {
  689. return this.$store.commit('showNotification', {
  690. message: 'Failed to process diagram data.',
  691. style: 'warning',
  692. icon: 'warning'
  693. })
  694. }
  695. }
  696. })(foundStart, line)
  697. })
  698. if (ln.height > 0) {
  699. this.cm.foldCode(foundStart)
  700. }
  701. break
  702. }
  703. }
  704. found = null
  705. }
  706. })
  707. },
  708. addMarker ({ kind, from, to, text, action }) {
  709. const markerElm = document.createElement('span')
  710. markerElm.appendChild(document.createTextNode(text))
  711. markerElm.className = 'CodeMirror-buttonmarker'
  712. markerElm.addEventListener('click', action)
  713. this.cm.markText(from, to, { replacedWith: markerElm, __kind: kind })
  714. }
  715. },
  716. mounted() {
  717. this.$store.set('editor/editorKey', 'markdown')
  718. if (this.mode === 'create' && !this.$store.get('editor/content')) {
  719. this.$store.set('editor/content', '# Header\nYour content here')
  720. }
  721. // Initialize Mermaid API
  722. mermaid.initialize({
  723. startOnLoad: false,
  724. theme: this.$vuetify.theme.dark ? `dark` : `default`
  725. })
  726. // Initialize CodeMirror
  727. this.cm = CodeMirror.fromTextArea(this.$refs.cm, {
  728. tabSize: 2,
  729. mode: 'text/markdown',
  730. theme: 'wikijs-dark',
  731. lineNumbers: true,
  732. lineWrapping: true,
  733. line: true,
  734. styleActiveLine: true,
  735. highlightSelectionMatches: {
  736. annotateScrollbar: true
  737. },
  738. viewportMargin: 50,
  739. inputStyle: 'contenteditable',
  740. allowDropFileTypes: ['image/jpg', 'image/png', 'image/svg', 'image/jpeg', 'image/gif'],
  741. direction: siteConfig.rtl ? 'rtl' : 'ltr',
  742. foldGutter: true,
  743. gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
  744. })
  745. this.cm.setValue(this.$store.get('editor/content'))
  746. this.cm.on('change', c => {
  747. this.$store.set('editor/content', c.getValue())
  748. this.onCmInput(this.$store.get('editor/content'))
  749. })
  750. if (this.$vuetify.breakpoint.mdAndUp) {
  751. this.cm.setSize(null, 'calc(100vh - 112px - 24px)')
  752. } else {
  753. this.cm.setSize(null, 'calc(100vh - 112px - 16px)')
  754. }
  755. // Set Keybindings
  756. const keyBindings = {
  757. 'F11' (c) {
  758. c.setOption('fullScreen', !c.getOption('fullScreen'))
  759. },
  760. 'Esc' (c) {
  761. if (c.getOption('fullScreen')) c.setOption('fullScreen', false)
  762. }
  763. }
  764. _.set(keyBindings, `${CtrlKey}-S`, c => {
  765. this.save()
  766. return false
  767. })
  768. _.set(keyBindings, `${CtrlKey}-B`, c => {
  769. this.toggleMarkup({ start: `**` })
  770. return false
  771. })
  772. _.set(keyBindings, `${CtrlKey}-I`, c => {
  773. this.toggleMarkup({ start: `*` })
  774. return false
  775. })
  776. _.set(keyBindings, `${CtrlKey}-Alt-Right`, c => {
  777. let lvl = this.getHeaderLevel(c)
  778. if (lvl >= 6) { lvl = 5 }
  779. this.setHeaderLine(lvl + 1)
  780. return false
  781. })
  782. _.set(keyBindings, `${CtrlKey}-Alt-Left`, c => {
  783. let lvl = this.getHeaderLevel(c)
  784. if (lvl <= 1) { lvl = 2 }
  785. this.setHeaderLine(lvl - 1)
  786. return false
  787. })
  788. this.cm.setOption('extraKeys', keyBindings)
  789. this.cm.on('inputRead', this.autocomplete)
  790. // Handle cursor movement
  791. this.cm.on('cursorActivity', c => {
  792. this.positionSync(c)
  793. this.scrollSync(c)
  794. })
  795. // Handle special paste
  796. this.cm.on('paste', this.onCmPaste)
  797. // Render initial preview
  798. this.processContent(this.$store.get('editor/content'))
  799. this.refresh()
  800. this.$root.$on('editorInsert', opts => {
  801. switch (opts.kind) {
  802. case 'IMAGE':
  803. let img = `![${opts.text}](${opts.path})`
  804. if (opts.align && opts.align !== '') {
  805. img += `{.align-${opts.align}}`
  806. }
  807. this.insertAtCursor({
  808. content: img
  809. })
  810. break
  811. case 'BINARY':
  812. this.insertAtCursor({
  813. content: `[${opts.text}](${opts.path})`
  814. })
  815. break
  816. case 'DIAGRAM':
  817. const selStartLine = this.cm.getCursor('from').line
  818. const selEndLine = this.cm.getCursor('to').line + 1
  819. this.cm.doc.replaceSelection('```diagram\n' + opts.text + '\n```\n', 'start')
  820. this.processMarkers(selStartLine, selEndLine)
  821. break
  822. }
  823. })
  824. // Handle save conflict
  825. this.$root.$on('saveConflict', () => {
  826. this.toggleModal(`editorModalConflict`)
  827. })
  828. this.$root.$on('overwriteEditorContent', () => {
  829. this.cm.setValue(this.$store.get('editor/content'))
  830. })
  831. },
  832. beforeDestroy() {
  833. this.$root.$off('editorInsert')
  834. }
  835. }
  836. </script>
  837. <style lang='scss'>
  838. $editor-height: calc(100vh - 112px - 24px);
  839. $editor-height-mobile: calc(100vh - 112px - 16px);
  840. .editor-markdown {
  841. &-main {
  842. display: flex;
  843. width: 100%;
  844. }
  845. &-editor {
  846. background-color: darken(mc('grey', '900'), 4.5%);
  847. flex: 1 1 50%;
  848. display: block;
  849. height: $editor-height;
  850. position: relative;
  851. @include until($tablet) {
  852. height: $editor-height-mobile;
  853. }
  854. }
  855. &-preview {
  856. flex: 1 1 50%;
  857. background-color: mc('grey', '100');
  858. position: relative;
  859. height: $editor-height;
  860. overflow: hidden;
  861. padding: 1rem;
  862. @at-root .theme--dark & {
  863. background-color: mc('grey', '900');
  864. }
  865. @include until($tablet) {
  866. display: none;
  867. }
  868. &-enter-active, &-leave-active {
  869. transition: max-width .5s ease;
  870. max-width: 50vw;
  871. .editor-code-preview-content {
  872. width: 50vw;
  873. overflow:hidden;
  874. }
  875. }
  876. &-enter, &-leave-to {
  877. max-width: 0;
  878. }
  879. &-content {
  880. height: $editor-height;
  881. overflow-y: scroll;
  882. padding: 0;
  883. width: calc(100% + 17px);
  884. // -ms-overflow-style: none;
  885. // &::-webkit-scrollbar {
  886. // width: 0px;
  887. // background: transparent;
  888. // }
  889. @include until($tablet) {
  890. height: $editor-height-mobile;
  891. }
  892. > div {
  893. outline: none;
  894. }
  895. p.line {
  896. overflow-wrap: break-word;
  897. }
  898. .tabset {
  899. background-color: mc('teal', '700');
  900. color: mc('teal', '100') !important;
  901. padding: 5px 12px;
  902. font-size: 14px;
  903. font-weight: 500;
  904. border-radius: 5px 0 0 0;
  905. font-style: italic;
  906. &::after {
  907. display: none;
  908. }
  909. &-header {
  910. background-color: mc('teal', '500');
  911. color: #FFF !important;
  912. padding: 5px 12px;
  913. font-size: 14px;
  914. font-weight: 500;
  915. margin-top: 0 !important;
  916. &::after {
  917. display: none;
  918. }
  919. }
  920. &-content {
  921. border-left: 5px solid mc('teal', '500');
  922. background-color: mc('teal', '50');
  923. padding: 0 15px 15px;
  924. overflow: hidden;
  925. @at-root .theme--dark & {
  926. background-color: rgba(mc('teal', '500'), .1);
  927. }
  928. }
  929. }
  930. }
  931. }
  932. &-toolbar {
  933. background-color: mc('blue', '700');
  934. background-image: linear-gradient(to bottom, mc('blue', '700') 0%, mc('blue','800') 100%);
  935. color: #FFF;
  936. .v-toolbar__content {
  937. padding-left: 64px;
  938. @include until($tablet) {
  939. padding-left: 8px;
  940. }
  941. }
  942. }
  943. &-insert:not(.v-speed-dial--right) {
  944. @include from($tablet) {
  945. left: 50%;
  946. margin-left: -28px;
  947. }
  948. }
  949. &-sidebar {
  950. background-color: mc('grey', '900');
  951. width: 64px;
  952. display: flex;
  953. flex-direction: column;
  954. justify-content: flex-start;
  955. align-items: center;
  956. padding: 24px 0;
  957. @include until($tablet) {
  958. padding: 12px 0;
  959. width: 40px;
  960. }
  961. }
  962. &-sysbar {
  963. padding-left: 0;
  964. &-locale {
  965. background-color: rgba(255,255,255,.25);
  966. display:inline-flex;
  967. padding: 0 12px;
  968. height: 24px;
  969. width: 63px;
  970. justify-content: center;
  971. align-items: center;
  972. }
  973. }
  974. // ==========================================
  975. // Fix FAB revealing under codemirror
  976. // ==========================================
  977. .speed-dial--fixed {
  978. z-index: 8;
  979. }
  980. // ==========================================
  981. // CODE MIRROR
  982. // ==========================================
  983. .CodeMirror {
  984. height: auto;
  985. font-family: 'Roboto Mono', monospace;
  986. font-size: .9rem;
  987. .cm-header-1 {
  988. font-size: 1.5rem;
  989. }
  990. .cm-header-2 {
  991. font-size: 1.25rem;
  992. }
  993. .cm-header-3 {
  994. font-size: 1.15rem;
  995. }
  996. .cm-header-4 {
  997. font-size: 1.1rem;
  998. }
  999. .cm-header-5 {
  1000. font-size: 1.05rem;
  1001. }
  1002. .cm-header-6 {
  1003. font-size: 1.025rem;
  1004. }
  1005. }
  1006. .CodeMirror-wrap pre.CodeMirror-line, .CodeMirror-wrap pre.CodeMirror-line-like {
  1007. word-break: break-word;
  1008. }
  1009. .CodeMirror-focused .cm-matchhighlight {
  1010. background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFklEQVQI12NgYGBgkKzc8x9CMDAwAAAmhwSbidEoSQAAAABJRU5ErkJggg==);
  1011. background-position: bottom;
  1012. background-repeat: repeat-x;
  1013. }
  1014. .cm-matchhighlight {
  1015. background-color: mc('grey', '800');
  1016. }
  1017. .CodeMirror-selection-highlight-scrollbar {
  1018. background-color: mc('green', '600');
  1019. }
  1020. }
  1021. // HINT DROPDOWN
  1022. .CodeMirror-hints {
  1023. position: absolute;
  1024. z-index: 10;
  1025. overflow: hidden;
  1026. list-style: none;
  1027. margin: 0;
  1028. padding: 1px;
  1029. box-shadow: 2px 3px 5px rgba(0,0,0,.2);
  1030. border: 1px solid mc('grey', '700');
  1031. background: mc('grey', '900');
  1032. font-family: 'Roboto Mono', monospace;
  1033. font-size: .9rem;
  1034. max-height: 150px;
  1035. overflow-y: auto;
  1036. min-width: 250px;
  1037. max-width: 80vw;
  1038. }
  1039. .CodeMirror-hint {
  1040. margin: 0;
  1041. padding: 0 4px;
  1042. white-space: pre;
  1043. color: #FFF;
  1044. cursor: pointer;
  1045. }
  1046. li.CodeMirror-hint-active {
  1047. background: mc('blue', '500');
  1048. color: #FFF;
  1049. }
  1050. </style>