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