|
80 | 80 | */
|
81 | 81 |
|
82 | 82 | import assert from 'assert'
|
| 83 | +import {directiveFromMarkdown} from 'mdast-util-directive' |
83 | 84 | import {toString} from 'mdast-util-to-string'
|
84 | 85 | import {parse} from 'micromark/lib/parse.js'
|
85 | 86 | import {preprocess} from 'micromark/lib/preprocess.js'
|
86 | 87 | import {postprocess} from 'micromark/lib/postprocess.js'
|
| 88 | +import {directive} from 'micromark-extension-directive' |
87 | 89 | import {decodeNumericCharacterReference} from 'micromark-util-decode-numeric-character-reference'
|
88 | 90 | import {decodeString} from 'micromark-util-decode-string'
|
89 | 91 | import {normalizeIdentifier} from 'micromark-util-normalize-identifier'
|
@@ -1142,3 +1144,35 @@ function extension(combined, extension) {
|
1142 | 1144 | }
|
1143 | 1145 | }
|
1144 | 1146 | }
|
| 1147 | + |
| 1148 | +/** |
| 1149 | + * @param {TemplateStringsArray} strings |
| 1150 | + * @param {...Node} values |
| 1151 | + * @returns {Root} |
| 1152 | + */ |
| 1153 | +export function md(strings, ...values) { |
| 1154 | + // Interleve `:expression` between strings. |
| 1155 | + const tree = fromMarkdown(strings.join(':expression'), { |
| 1156 | + extensions: [directive()], |
| 1157 | + mdastExtensions: [directiveFromMarkdown] |
| 1158 | + }) |
| 1159 | + // Swap `:expression` nodes for values. |
| 1160 | + visit(tree) |
| 1161 | + return tree |
| 1162 | + |
| 1163 | + /** |
| 1164 | + * @param {Node} node |
| 1165 | + * @returns {void} |
| 1166 | + */ |
| 1167 | + function visit(node) { |
| 1168 | + if ('children' in node) { |
| 1169 | + for (const [i, child] of node.children.entries()) { |
| 1170 | + if (child.type === 'textDirective' && child.name === 'expression') { |
| 1171 | + node.children[i] = /** @type {Content} */ (values.shift()) |
| 1172 | + } else { |
| 1173 | + visit(child) |
| 1174 | + } |
| 1175 | + } |
| 1176 | + } |
| 1177 | + } |
| 1178 | +} |
0 commit comments