editor-markdown.vue 37 KB

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