editor-markdown.vue 31 KB

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