editor-markdown.vue 29 KB

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