-
Notifications
You must be signed in to change notification settings - Fork 0
/
link.ts
248 lines (226 loc) · 6.92 KB
/
link.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
/* eslint-disable unicorn/consistent-destructuring */
import { createBuilder } from "@yankeeinlondon/builder-api";
import { join } from "pathe";
import { pipe } from "fp-ts/lib/function.js";
import type {
LinkElement,
LinkTransformer,
LinkOptions,
StringTransformer,
WithTagAndBase,
} from "./types";
import { keys } from "./utils";
import { MdLink } from "./mdi";
const staticRuleLookup = {
externalLinkClass: /^https?:/,
internalLinkClass: /^[./a-z]*[^:]*$/,
relativeLinkClass: /^[.a-z][./a-z]*[^:]*$/,
fullyQualifiedLinkClass: /^\/[.a-z]*[^:]*$/,
anchorTagClass: /^#/,
insecureClass: /^http:/,
fileClass: /^file:/,
mailtoClass: /^mailto:/,
imageClass: /\.(gif|jpg|jpeg|png|webp|avif|tiff|heif)$/,
documentClass: /\.(doc|pdf|txt|xls)$/,
};
function isExternalLink(
meta: LinkElement
): meta is LinkElement & { href: string } {
return !!(meta.href && staticRuleLookup.externalLinkClass.test(meta.href));
}
function isInternalLink(
meta: LinkElement
): meta is LinkElement & { href: string } {
return !!(meta.href && staticRuleLookup.internalLinkClass.test(meta.href));
}
function strTransform(
transformer: string | StringTransformer | undefined,
meta: WithTagAndBase<LinkElement>
): string | undefined {
if (!transformer) {
return undefined;
} else if (typeof transformer === "function") {
return transformer(meta);
} else {
return transformer;
}
}
/** returns an array of classes based on the URL and configuration */
const addClasses =
(c: LinkOptions): LinkTransformer =>
/** returns an array of classes based on the URL and configuration */
(lnk) => {
const classes = keys(staticRuleLookup)
.flatMap((key) => {
if (!lnk.href || !staticRuleLookup[key].test(lnk.href)) {
return;
}
switch (typeof c[key]) {
case "function": {
return (c[key] as StringTransformer)(lnk);
}
case "string": {
return c[key] as string;
}
case "undefined": {
return;
}
default: {
throw new Error(
`Unexpected property type for property ${key} [${typeof c[key]}]`
);
}
}
})
// remove undefined values
.filter(Boolean) as string[];
if (lnk.href) {
for (const rc of c.ruleBasedClasses) {
const [rule, klass] = rc;
if (rule.test(lnk.href as string)) {
lnk.class = [lnk.class, klass].join(" ");
}
}
}
return { ...lnk, class: [lnk.class, ...classes].join(" ") };
};
/** adds "target" and "rel" properties to links */
const addTargetingAndRel =
(c: LinkOptions): LinkTransformer =>
/** adds "target" and "rel" properties to links */
(lnk) => {
if (isExternalLink(lnk)) {
lnk.target = strTransform(c.externalTarget, lnk);
lnk.rel = strTransform(c.externalRel, lnk);
}
if (isInternalLink(lnk)) {
lnk.target = strTransform(c.internalTarget, lnk);
lnk.rel = strTransform(c.internalRel, lnk);
}
return lnk;
};
/** works on URL structure and messages based on config */
const cleanupAndCloseOut =
(c: LinkOptions): LinkTransformer =>
/** works on URL structure and messages based on config */
(lnk) => {
if (isInternalLink(lnk)) {
if (
lnk.href &&
lnk.href.trim().endsWith("index.md") &&
c.cleanIndexRoutes
) {
lnk.href = lnk.href.replace(/index\.md\s*/, "");
} else if (
lnk.href &&
lnk.href.trim().endsWith(".md") &&
c.cleanAllRoutes
) {
{
lnk.href = lnk.href.replace(/(\S+)\.md$/, "$1");
}
}
const removal = new RegExp(`.*${c.rootDir}`);
if (isInternalLink(lnk)) {
lnk.href = join(lnk._base.replace(removal, ""), lnk.href);
}
if (lnk.tagName === "a" && c.useRouterLinks) {
lnk = {
...lnk,
to: lnk.href,
href: undefined,
tagName: "router-link",
class: [lnk.class, c.routerLinkClass].join(" "),
};
}
}
return lnk;
};
/**
* A _builder_ which provides:
* - contextual classes to links within Markdown pages
* - relative versus absolute links
* - local versus external links
* - content-type based links
* - protocol based links (http/file/mailto)
* - cleans up _relative_ links relative nature based
* on current route
* - converts `<a href>` properties to `<router-link to>` props
* - `postProcessing` hook to allow programmatic mutation
* beyond the core use-cases
*/
export const link = createBuilder("link", "parser")
.options<Partial<LinkOptions>>()
.initializer()
// the approach for this builder is to inject a rule into the MarkdownIt
// which will call our `transform` function on each instance of a link element
// discovered and allow mutation.
.handler(async (p, o) => {
const {
fileName,
viteConfig: { base },
} = p;
// merge default settings with user settings
const options: LinkOptions = {
rootDir: "src/pages",
externalLinkClass: "external-link",
internalLinkClass: "internal-link",
routerLinkClass: "router-link",
relativeLinkClass: undefined,
fullyQualifiedLinkClass: undefined,
anchorTagClass: "anchor-tag",
insecureClass: "insecure",
fileClass: "file-link",
mailtoClass: "mailto-link",
imageClass: "image-reference",
documentClass: "doc-reference",
ruleBasedClasses: [],
externalTarget: "_blank",
externalRel: "noreferrer noopener",
internalTarget: undefined,
internalRel: undefined,
useRouterLinks: true,
cleanIndexRoutes: true,
cleanAllRoutes: true,
postProcessing: (f) => f,
...o,
};
const [cleanup, targeting, classes] = [
cleanupAndCloseOut(options),
addTargetingAndRel(options),
addClasses(options),
];
const { postProcessing } = options;
const transform: LinkTransformer = (event: WithTagAndBase<LinkElement>) => {
return pipe(
event,
classes,
targeting,
cleanup,
postProcessing
);
};
// once we pass our rule into the parser
// we will get the callback's to our transformer
// in order to fulfill our goals
p.parser.use(MdLink({ file: fileName, transform, base }));
return p;
})
.meta({
description:
"provides default classes for all links based on protocol, content-type, and whether internal or external; also converts <a> tags to <router-links> and cleans up relative paths.",
parserRules: [
{
ruleName: "link_open",
usage: "patches",
description:
"allows attributes to modified on link DOM elements, including changing the tag's name from <a> to <router-link>",
},
{
ruleName: "link_close",
usage: "patches",
description:
"used to make sure end tag has a matching tag name to start tag",
},
],
});