editor-markdown.vue 33 KB

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