editor-markdown.vue 37 KB

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