forked from stablecog/stablecog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdsvex.config.js
121 lines (109 loc) · 2.55 KB
/
mdsvex.config.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import rehypeHighlight from 'rehype-highlight';
import { defineMDSveXConfig as defineConfig } from 'mdsvex';
import remarkExternalLinks from 'remark-external-links';
import rehypeSlug from 'rehype-slug';
export const mdsvexOptions = defineConfig({
extensions: ['.svx', '.md'],
remarkPlugins: [
readingTime,
slug,
previewImageUrl,
toc,
[remarkExternalLinks, { target: '_blank', rel: 'noopener noreferrer' }]
],
rehypePlugins: [rehypeHighlight, rehypeSlug]
});
const AVERAGE_WORD_LENGTH = 5;
const WPM = 200;
const PUBLIC_BUCKET_AUX_URL = 'https://ba.stablecog.com';
function readingTime() {
return (_, file) => {
file.data.fm = {
...file.data.fm,
reading_time: Math.ceil(file.contents.length / AVERAGE_WORD_LENGTH / WPM)
};
};
}
function slug() {
return (_, file) => {
file.data.fm = {
...file.data.fm,
slug: file.filename.split('/').pop().split('.')[0]
};
};
}
function toc() {
return (tree, file) => {
const toc = getToc(tree);
file.data.fm = {
...file.data.fm,
toc: toc
};
};
}
function previewImageUrl() {
return (_, file) => {
const folder = file.filename.split('/md/')[1].split('/')[0];
file.data.fm = {
...file.data.fm,
preview_image_url: `${PUBLIC_BUCKET_AUX_URL}/${folder}/previews/${file.data.fm.slug}.jpg`
};
};
}
function getToc(tree) {
const flatToc = traverseNode(tree);
const toc = nodeArrayToHierarchy(flatToc);
return toc;
}
function traverseNode(node, arr = []) {
if (node.children && node.children.length > 2) {
node.children.forEach((child) => {
traverseNode(child, arr);
});
}
if (node.type === 'heading') {
arr.push({
title: findValue(node),
level: node.depth
});
}
return arr;
}
function findValue(node) {
let value = '';
if (node.type === 'text' && !node.children) {
value += node.value;
return value;
}
if (node.children && node.children.length > 0) {
node.children.forEach((child) => {
value += findValue(child);
});
}
return value;
}
function nodeArrayToHierarchy(array) {
let result = [];
let stack = [];
array.forEach((node) => {
const newNode = { title: node.title, level: node.level };
while (stack[stack.length - 1] && stack[stack.length - 1].level >= node.level) {
stack.pop();
}
if (stack.length === 0) {
stack.push(newNode);
result.push(newNode);
return;
}
if (node.level > stack[stack.length - 1].level) {
if (stack[stack.length - 1].children) {
stack[stack.length - 1].children.push(newNode);
} else {
stack[stack.length - 1].children = [newNode];
}
stack.push(newNode);
return;
}
});
return result;
}