Skip to content

Commit

Permalink
feat($markdown): code snippet hmr (close #1309) (#1358)
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma authored and ulivz committed Feb 26, 2019
1 parent d16d3d5 commit 8f83a17
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions packages/@vuepress/markdown/lib/snippet.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
const { fs } = require('@vuepress/shared-utils')
const { fs, path } = require('@vuepress/shared-utils')

module.exports = function snippet (md, options = {}) {
const fence = md.renderer.rules.fence
const root = options.root || process.cwd()

md.renderer.rules.fence = (...args) => {
const [tokens, idx, , { loader }] = args
const token = tokens[idx]
const { src } = token
if (src) {
if (loader) {
loader.addDependency(src)
}
if (fs.existsSync(src)) {
token.content = fs.readFileSync(src, 'utf8')
} else {
token.content = 'Not found: ' + src
token.info = ''
}
}
return fence(...args)
}

function parser (state, startLine, endLine, silent) {
const CH = '<'.charCodeAt(0)
const pos = state.bMarks[startLine] + state.tShift[startLine]
Expand All @@ -25,14 +45,13 @@ module.exports = function snippet (md, options = {}) {
const end = state.skipSpacesBack(max, pos)
const rawPath = state.src.slice(start, end).trim().replace(/^@/, root)
const filename = rawPath.split(/[{\s]/).shift()
const content = fs.existsSync(filename) ? fs.readFileSync(filename).toString() : 'Not found: ' + filename
const meta = rawPath.replace(filename, '')

state.line = startLine + 1

const token = state.push('fence', 'code', 0)
token.info = filename.split('.').pop() + meta
token.content = content
token.src = path.resolve(filename)
token.markup = '```'
token.map = [startLine, startLine + 1]

Expand Down

0 comments on commit 8f83a17

Please sign in to comment.