-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
314 lines (261 loc) · 8.63 KB
/
index.ts
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import type { Root } from "hast";
import { SKIP, visit } from "unist-util-visit";
export type LinkProcessorOptions = {
/**
* Sets the processing rules.
* The processor will execute them in sequence.
*/
rules?: LinkProcessorRule[]
/**
* Disables all builtin rules if set to `false`
* @defaults true
*/
useBuiltin?: boolean
}
export type MarkdownLink = {
href?: string
title?: string
text?: string
}
export type LinkAttributes = MarkdownLink & {
className?: string
rel?: string
target?: string
download?: string | boolean
}
export type Link = LinkAttributes & {
[key: string]: string | boolean | number | undefined
}
export type LinkTransformer = (link: Link) => Link
type MaybeArray<T> = T | T[];
export type LinkProcessorRule =
| LinkProcessorBuiltinRule
| LinkProcessorMatcherRule
| LinkProcessorTransformerRule
export type LinkProcessorBuiltinRule = keyof typeof R;
export type LinkProcessorTransformerRule = (link: MarkdownLink) => Link | false | undefined;
export type LinkProcessorMatcherRule = {
match(link: Readonly<MarkdownLink>): boolean | Link | undefined
action: MaybeArray<Readonly<Link> | LinkTransformer>
}
/**
* Rule action helper
*/
export const A = {
/**
* Set the link attribute with the specified value
*/
set(key: keyof LinkAttributes, value: string | boolean): LinkTransformer {
return link => {
link[key] = value as any;
return link;
}
},
/**
* Merge the link attribute with the specified value.
* Useful for space-separated values like class or rel attribute.
* - if the attribute has no actual value, it will be set with the value
* - if the attribute has already the same value, it does nothing
* - otherwise, the value will be merged (_actual_ + " " + _value_)
*/
merge(key: keyof LinkAttributes, value: string): LinkTransformer {
return link => {
const exiting = link[key];
if (exiting && typeof exiting === "string") {
link[key] = [...new Set([value, ...exiting.trim().split(" ")])].join(" ");
} else {
link[key] = value;
}
return link;
}
},
/**
* Add the specified class to the link
* If the class is already present, it does nothing
*/
mergeClass(className: string): LinkTransformer {
return A.merge("className", className);
}
};
/**
* Rule match helpers
*/
export const M = {
prefix(prefix: string): LinkProcessorMatcherRule["match"] {
return link => {
const { href, title, text } = link;
if (href?.startsWith(prefix)) {
return { href: href.substring(prefix.length) };
}
if (title?.startsWith(prefix)) {
return { title: title.substring(prefix.length) };
}
if (text?.startsWith(prefix)) {
return { text: text.substring(prefix.length) };
}
};
},
email(): LinkProcessorMatcherRule["match"] {
return link => {
if (link.href?.startsWith("mailto:")) {
return {};
}
return M.prefix("email:")(link);
}
},
external(): LinkProcessorMatcherRule["match"] {
return link => {
if (link.href?.startsWith("http:") || link.href?.startsWith("https:")) {
return {};
}
return M.prefix("external:")(link);
};
},
download(options?: {
skipExtensions?: string[]
}): LinkProcessorMatcherRule["match"] {
const {
skipExtensions = ["html", "htm", "md", "mdx"],
} = options || {};
return link => {
if (link.href?.startsWith("http:") || link.href?.startsWith("https:")) {
// check if is a file link
// check if has an extension, .1-4 char length
const { pathname } = new URL(link.href, "https://localhost");
const parts = pathname.split(".");
if (parts.length >= 2) {
const extension = parts.pop()!.toLowerCase();
if ((extension.length >= 1 || extension.length <= 4) && !skipExtensions.includes(extension)) {
return { download: pathname.split("/").pop()! };
}
}
}
return M.prefix("download:")(link);
}
},
}
export const R = {
download(options?: {
skipExtensions?: string[]
}): LinkProcessorMatcherRule {
return {
match: M.download(options),
action: [
A.mergeClass("download"),
link => ({ download: link.download || true })
]
};
},
external(): LinkProcessorMatcherRule {
return {
match: M.external(),
action: [
{ target: "_blank", rel: "external nofollow noopener" }, //cspell:disable-line
A.mergeClass("external")
]
};
},
email(): LinkProcessorMatcherRule {
return {
match: M.email(),
action: A.mergeClass("email")
};
},
"same-page"(): LinkProcessorMatcherRule {
return {
match: link => link.href?.startsWith("#"),
action: A.mergeClass("same-page")
};
}
}
/**
* Process links with transform rules like adding css classes or custom attributes
*
* @param options Optional configuration with rules to apply
*/
export default function rehypeLinkProcessor(options?: LinkProcessorOptions) {
const {
useBuiltin = true,
rules: designRules = []
} = options || {};
if (useBuiltin) {
const rules = (Object.keys(R) as LinkProcessorBuiltinRule[]).filter(x => !designRules.includes(x));
designRules.push(...rules.map(x => R[x]()));
}
const rules = designRules.map(rule => {
// it's a builtin rule --> expand it
if (typeof rule === "string") {
const builtin = R[rule];
if (!builtin) {
throw new Error(`Builtin rule '${rule}' unknown`);
}
rule = builtin();
}
// it's a matcher rule --> translate it in a transform rule
if (typeof rule === "object") {
const { match, action } = rule;
rule = link => {
const result = match(link);
if (!result) return;
if (typeof result === "object") {
link = { ...link, ...result };
}
const actions = Array.isArray(action) ? action : [action];
return actions.reduce((link, action) => {
const patch = typeof action === "function"
? action(link)
: action;
return { ...link, ...patch };
}, link);
}
}
return rule;
});
if (rules.length === 0) {
console.warn("[rehype-link-processor] no rule active");
return () => () => { }; // noop
}
function processor(link: MarkdownLink): Link | undefined {
for (const rule of rules) {
const processed = rule(link);
if (processed) {
return processed;
}
}
};
return () => (tree: Root) => {
visit(tree, "element", node => {
if (node.tagName !== "a") return;
const info: MarkdownLink = {
href: node.properties?.href as string,
title: node.properties?.title as string,
text: node.children?.[0]?.type === "text" ? node.children?.[0]?.value : undefined
};
const link = processor(info);
// apply
if (!link) {
return [SKIP];
}
const {
href,
title,
text,
target,
className,
download,
rel,
...extra
} = link;
node.properties ??= {};
if (href) node.properties.href = href;
if (title) node.properties.title = title;
if (target) node.properties.target = target;
if (className) node.properties.className = className;
if (download) node.properties.download = download;
if (rel) node.properties.rel = rel;
if (text) node.children = [{ type: "text", value: text }];
node.properties = { ...node.properties, ...extra };
return [SKIP];
});
};
}