deno.land / x / lume@v2.1.4 / plugins / modify_urls.ts

modify_urls.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
import { merge } from "../core/utils/object.ts";import { concurrent } from "../core/utils/concurrent.ts";
import type Site from "../core/site.ts";import type { Page } from "../core/file.ts";
export interface Options { /** The list of extensions this plugin applies to */ extensions?: string[];
/** * The function to generate the new url * @default `(url) => url` */ fn: (url: string, page: Page, element: Element) => string | Promise<string>;}
// Default optionsexport const defaults: Options = { extensions: [".html"], fn: (url) => url,};
/** A plugin to modify all URLs found in the HTML documents */export default function (userOptions: Options) { const options = merge(defaults, userOptions);
function replace( url: string | null, page: Page, element: Element, ): string | Promise<string> { return url ? options.fn(url, page, element) : ""; }
async function replaceSrcset( attr: string | null, page: Page, element: Element, ): Promise<string> { const srcset = attr ? attr.trim().split(",") : []; const replaced: string[] = []; for (const src of srcset) { const [, url, rest] = src.trim().match(/^(\S+)(.*)/)!; replaced.push(await replace(url, page, element) + rest); }
return replaced.join(", "); }
return (site: Site) => { site.process( options.extensions, (pages) => concurrent(pages, async (page: Page) => { const { document } = page;
if (!document) { return; }
for (const element of document.querySelectorAll("[href]")) { element.setAttribute( "href", await replace(element.getAttribute("href"), page, element), ); }
for (const element of document.querySelectorAll("[src]")) { element.setAttribute( "src", await replace(element.getAttribute("src"), page, element), ); }
for (const element of document.querySelectorAll("video[poster]")) { element.setAttribute( "poster", await replace(element.getAttribute("poster"), page, element), ); }
for (const element of document.querySelectorAll("[srcset]")) { element.setAttribute( "srcset", await replaceSrcset( element.getAttribute("srcset"), page, element, ), ); }
for (const element of document.querySelectorAll("[imagesrcset]")) { element.setAttribute( "imagesrcset", await replaceSrcset( element.getAttribute("imagesrcset"), page, element, ), ); } }), ); };}
lume

Version Info

Tagged at
5 months ago