editor-markdown.vue 32 KB

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