|
| 1 | +// eslint-disable-next-line import/no-extraneous-dependencies |
| 2 | +import { visit } from "unist-util-visit"; |
| 3 | +import type { Node, Element } from "hast"; |
| 4 | + |
| 5 | +type Field = { |
| 6 | + value: string; |
| 7 | +}; |
| 8 | + |
| 9 | +function interpolationToLink( |
| 10 | + options: { fields: Record<string, Field> } = { fields: {} }, |
| 11 | +) { |
| 12 | + return (tree: Node) => { |
| 13 | + visit(tree, "element", (node: Element) => { |
| 14 | + if ( |
| 15 | + node.tagName === "a" && |
| 16 | + node.properties?.href && |
| 17 | + typeof node.properties.href === "string" |
| 18 | + ) { |
| 19 | + // Decode potential URL-encoded curly braces |
| 20 | + // e.g [site](http://site.com/%7B%7Bfield%7B%7B) |
| 21 | + // replace and becomes [site](http://site.com/{{field}}) |
| 22 | + const href = node.properties.href |
| 23 | + .replace(/%7B%7B/gi, "{{") |
| 24 | + .replace(/%7D%7D/gi, "}}"); |
| 25 | + |
| 26 | + // // Only apply regex if the pattern exists |
| 27 | + const interpolationRegex = /{{\s*(\w+)\s*}}/; |
| 28 | + |
| 29 | + if (interpolationRegex.test(href)) { |
| 30 | + const match = interpolationRegex.exec(href); |
| 31 | + |
| 32 | + if (match) { |
| 33 | + // we get the key from the string e.g. {{field}} |
| 34 | + const key = match[1]; |
| 35 | + |
| 36 | + if (options?.fields[key] === undefined) return; |
| 37 | + // get the value based from the fields object using the key |
| 38 | + const replacement = options?.fields[key]?.value; |
| 39 | + const resolvedHref = href.replace(interpolationRegex, replacement); |
| 40 | + |
| 41 | + // eslint-disable-next-line no-param-reassign |
| 42 | + node.properties.href = resolvedHref; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + }); |
| 47 | + }; |
| 48 | +} |
| 49 | + |
| 50 | +export default interpolationToLink; |
0 commit comments