1
0
mirror of synced 2025-12-23 11:54:18 -05:00
Files
docs/lib/render-content/plugins/parse-info-string.js
Kevin Heis b0e9bc314a Move annotate from Liquid to info string (#37651)
Co-authored-by: Peter Bengtsson <peterbe@github.com>
2023-06-08 19:25:23 +00:00

28 lines
730 B
JavaScript

// Based on https://spec.commonmark.org/0.30/#info-string
// Parse out info strings on fenced code blocks, example:
// ```javascript lineNumbers:left copy:all annotate
// becomes...
// node.lang = javascript
// node.meta = { lineNumbers: 'left', copy: 'all', annotate: true }
import { visit } from 'unist-util-visit'
const matcher = (node) => node.type === 'code' && node.lang && node.meta
export default function parseInfoString() {
return (tree) => {
visit(tree, matcher, (node) => {
node.meta = strToObj(node.meta)
})
}
}
function strToObj(str) {
return Object.fromEntries(
str
.split(/\s+/g)
.map((k) => k.split(':'))
.map(([k, ...v]) => [k, v.length ? v.join(':') : true])
)
}