editor-markdown.vue 36 KB

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