editor-markdown.vue 33 KB

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