2021-09-25 15:17:57 +08:00
|
|
|
import tokenizer from './ref-block'
|
2020-08-13 11:47:56 +08:00
|
|
|
import visit from 'unist-util-visit'
|
|
|
|
import remove from 'unist-util-remove'
|
|
|
|
import { render } from './page'
|
|
|
|
|
|
|
|
const NAME = 'refblock'
|
|
|
|
const RE_REF = /^\^([-_a-z0-9]+)/i
|
|
|
|
|
|
|
|
export default function attacher () {
|
|
|
|
let proto = this.Parser.prototype
|
|
|
|
|
|
|
|
proto.blockTokenizers[NAME] = tokenizer
|
|
|
|
proto.interruptParagraph.push([NAME])
|
|
|
|
proto.interruptList.push([NAME])
|
|
|
|
proto.interruptBlockquote.push([NAME])
|
|
|
|
|
|
|
|
let methods = proto.blockMethods
|
|
|
|
methods.unshift(NAME)
|
|
|
|
|
|
|
|
return (tree, file) => {
|
|
|
|
let { path, data } = file
|
|
|
|
|
|
|
|
if (!data) {
|
|
|
|
file.data = data = {}
|
|
|
|
}
|
|
|
|
if (!data.refs) {
|
|
|
|
data.refs = {}
|
|
|
|
}
|
|
|
|
|
|
|
|
visit(tree, NAME, ({ id, value }) => {
|
2022-01-18 12:41:50 +08:00
|
|
|
data.refs[id] = () => render(value, path, data).contents
|
2020-08-13 11:47:56 +08:00
|
|
|
})
|
|
|
|
remove(tree, NAME)
|
|
|
|
|
|
|
|
visit(tree, 'linkReference', (node, index, parent) => {
|
|
|
|
let { identifier } = node
|
2021-09-25 15:17:57 +08:00
|
|
|
let [match, id] = identifier.match(RE_REF) || []
|
2020-08-13 11:47:56 +08:00
|
|
|
if (!match || !id || !data.refs[id]) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
parent.children.splice(index, 1, {
|
|
|
|
type: 'html',
|
2022-01-18 12:41:50 +08:00
|
|
|
value: data.refs[id]()
|
2020-08-13 11:47:56 +08:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|