editor-markdown.vue 32 KB

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