editor-markdown.vue 35 KB

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