forked from mattjennings/mdsvex-relative-images
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (53 loc) · 1.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { visit } from "unist-util-visit";
const RE_SCRIPT_START =
/<script(?:\s+?[a-zA-z]+(=(?:["']){0,1}[a-zA-Z0-9]+(?:["']){0,1}){0,1})*\s*?>/;
export default function remarkExcerpt(options = {}) {
const {
componentName = "More",
componentPath = "$lib/components/More.svelte",
excerptMark = "<!--more-->",
} = options;
const importMore = `\nimport ${componentName} from "${componentPath}";\n`;
return function transform(tree) {
let foundExcerptTerminator = false;
/**
* @param {import('unist').Node} node
*/
function visitor(node) {
if (
foundExcerptTerminator ||
node.type !== "html" ||
node.value !== excerptMark
) {
return;
}
foundExcerptTerminator = true;
node.value = `<${componentName}>`;
}
// find and replace <!--more-->
visit(tree, ["html"], visitor);
if (!foundExcerptTerminator) {
return;
}
tree.children.push({
type: "html",
value: `</${componentName}>`,
});
let is_script = false;
// append scripts or make a new one
visit(tree, "html", (node) => {
if (!is_script && RE_SCRIPT_START.test(node.value)) {
is_script = true;
node.value = node.value.replace(RE_SCRIPT_START, (existingScript) => {
return `${existingScript}${importMore}`;
});
}
});
if (!is_script) {
tree.children.push({
type: "html",
value: `<script>${importMore}</script>`,
});
}
};
}