-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
relative_urls.js
78 lines (64 loc) 路 1.85 KB
/
relative_urls.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
import { posix } from "../deps/path.js";
export default function () {
return (site) => {
site.process([".html"], processor);
const basePath = site.options.location.pathname;
function processor(page) {
const { document } = page;
const from = posix.dirname(site.url(page.dest.path));
document.querySelectorAll("[href]").forEach((element) => {
element.setAttribute(
"href",
relativeUrl(basePath, from, element.getAttribute("href")),
);
});
document.querySelectorAll("[src]").forEach((element) => {
element.setAttribute(
"src",
relativeUrl(basePath, from, element.getAttribute("src")),
);
});
const srcsetUrlRegex =
/(?<=^\s*|,\s+|\s,+|\s[^\s,]+,+)[^\s,](?:\S*[^\s,])?/g;
document.querySelectorAll("[srcset]").forEach((element) => {
element.setAttribute(
"srcset",
element.getAttribute("srcset").replace(
srcsetUrlRegex,
(url) => relativeUrl(basePath, from, url),
),
);
});
document.querySelectorAll("[imagesrcset]").forEach((element) => {
element.setAttribute(
"imagesrcset",
element.getAttribute("imagesrcset").replace(
srcsetUrlRegex,
(url) => relativeUrl(basePath, from, url),
),
);
});
}
};
}
function relativeUrl(basePath, from, to) {
if (ignore(to)) {
return to;
}
if (!to.startsWith(basePath)) {
to = posix.join(basePath, to);
}
const relative = posix.relative(from, to);
if (!relative || relative.startsWith("/")) {
return `.${relative}`;
}
return relative;
}
function ignore(url) {
return !url ||
url.startsWith("./") ||
url.startsWith("../") ||
url.startsWith("#") ||
url.startsWith("?") ||
url.includes("//");
}