Skip to content

Commit 5b07149

Browse files
Paul AlontePaul Alonte
authored andcommitted
support markdown link
1 parent c9de56d commit 5b07149

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export { default as md2hast } from "./md2hast.js";
22
export { default as preprocessor } from "./preprocessor.js";
3+
export { default as interpolationToLink } from "./interpolationToLink.js";

src/interpolationToLink.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)