editor-markdown.vue 33 KB

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