editor-markdown.vue 35 KB

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