editor-markdown.vue 33 KB

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