forked from lumeland/lume
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpicture.ts
More file actions
241 lines (197 loc) Β· 6.15 KB
/
picture.ts
File metadata and controls
241 lines (197 loc) Β· 6.15 KB
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
import { posix } from "../deps/path.ts";
import { getPathAndExtension } from "../core/utils.ts";
import { typeByExtension } from "../deps/media_types.ts";
import type { Transformation } from "../plugins/imagick.ts";
import type { MagickFormat } from "../deps/imagick.ts";
import type { Document, Element } from "../deps/dom.ts";
import type { Plugin, Site } from "../core.ts";
interface SourceFormat {
width: number;
scales: Record<string, number>;
format: string;
}
interface Source extends SourceFormat {
paths: string[];
}
export default function (): Plugin {
return (site: Site) => {
const transforms = new Map<string, Source>();
site.process([".html"], (page) => {
const { document } = page;
if (!document) {
return;
}
const basePath = posix.dirname(page.outputPath!);
const nodeList = document.querySelectorAll("img");
for (const node of nodeList) {
const img = node as Element;
const imagick = closest(img, "[imagick]")?.getAttribute("imagick");
if (!imagick) {
continue;
}
if (!img.getAttribute("src")) {
throw new Error("img element must have a src attribute");
}
const picture = closest(img, "picture");
if (picture) {
handlePicture(imagick, img, picture, basePath);
continue;
}
handleImg(imagick, img, basePath);
}
});
site.process([".html"], (page) => {
page.document?.querySelectorAll("[imagick]").forEach((element) => {
(element as Element).removeAttribute("imagick");
});
});
site.process("*", (page) => {
const path = page.outputPath!;
for (const { paths, width, scales, format } of transforms.values()) {
if (!paths.includes(path)) {
continue;
}
const imagick: Transformation[] = page.data.imagick
? Array.isArray(page.data.imagick)
? page.data.imagick
: [page.data.imagick]
: (page.data.imagick = []);
for (const [suffix, scale] of Object.entries(scales)) {
imagick.push({
resize: width * scale,
suffix,
format: format as MagickFormat,
});
}
}
});
function handlePicture(
imagick: string,
img: Element,
picture: Element,
basePath: string,
) {
const src = img.getAttribute("src") as string;
const sizes = img.getAttribute("sizes");
const sourceFormats = saveTransform(basePath, src, imagick);
for (const sourceFormat of sourceFormats) {
const source = createSource(
img.ownerDocument!,
src,
sourceFormat,
sizes,
);
picture.insertBefore(source, img);
}
}
function handleImg(imagick: string, img: Element, basePath: string) {
const src = img.getAttribute("src") as string;
const sizes = img.getAttribute("sizes");
const sourceFormats = saveTransform(basePath, src, imagick);
const picture = img.ownerDocument!.createElement("picture");
img.replaceWith(picture);
for (const sourceFormat of sourceFormats) {
const source = createSource(
img.ownerDocument!,
src,
sourceFormat,
sizes,
);
picture.append(source);
}
picture.append(img);
}
function saveTransform(
basePath: string,
src: string,
imagick: string,
): SourceFormat[] {
const path = src.startsWith("/") ? src : posix.join(basePath, src);
const sizes: string[] = [];
const formats: string[] = [];
imagick.split(/\s+/).forEach((piece) => {
if (piece.match(/^\d/)) {
sizes.push(piece);
} else {
formats.push(piece);
}
});
const sourceFormats: SourceFormat[] = [];
for (const size of sizes) {
const [width, scales] = parseSize(size);
for (const format of formats) {
const key = `${width}:${format}`;
const sourceFormat = {
width,
format,
scales: {} as Record<string, number>,
};
sourceFormats.push(sourceFormat);
for (const scale of scales) {
const suffix = `-${width}w${scale === 1 ? "" : `@${scale}`}`;
sourceFormat.scales[suffix] = scale;
}
const transform = transforms.get(key);
if (transform) {
if (!transform.paths.includes(path)) {
transform.paths.push(path);
}
Object.assign(transform.scales, sourceFormat.scales);
} else {
transforms.set(key, {
...sourceFormat,
paths: [path],
});
}
}
}
return sourceFormats;
}
};
}
function parseSize(size: string): [number, number[]] {
const match = size.match(/^(\d+)(@([\d.,]+))?$/);
if (!match) {
throw new Error(`Invalid size: ${size}`);
}
const [, width, , scales] = match;
// Use a Set to avoid duplicates
const sizes = new Set<number>([1]);
scales?.split(",").forEach((size) => sizes.add(parseFloat(size)));
return [
parseInt(width),
[...sizes.values()],
];
}
function createSource(
document: Document,
src: string,
srcFormat: SourceFormat,
sizes?: string | null | undefined,
) {
const source = document.createElement("source");
const { scales, format, width } = srcFormat;
const path = encodeURI(getPathAndExtension(src)[0]);
const srcset: string[] = [];
for (const [suffix, scale] of Object.entries(scales)) {
const scaleSuffix = sizes
? ` ${scale * width}w`
: scale === 1
? ""
: ` ${scale}x`;
srcset.push(`${path}${suffix}.${format}${scaleSuffix}`);
}
source.setAttribute("srcset", srcset.join(", "));
source.setAttribute("type", typeByExtension(format));
if (sizes) {
source.setAttribute("sizes", sizes);
}
return source;
}
// Missing Element.closest in Deno DOM (https://github.com/b-fuze/deno-dom/issues/99)
function closest(element: Element, selector: string) {
while (element && !element.matches(selector)) {
element = element.parentElement!;
}
return element;
}