-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
157 lines (122 loc) · 4.41 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
import { posix, dirname, extname, basename } from 'lume/deps/path.ts';
import { exists } from 'lume/deps/fs.ts';
import type { Site, Page } from 'lume/core.ts';
import { HTMLDocument, Element } from "lume/deps/dom.ts";
const squooshTasks: string[] = [];
let formats: string[];
const mimeTypes: Record<string, string> = {
'avif': 'image/avif',
'webp': 'image/webp',
'jpg': 'image/jpeg',
'wp2': 'image/webp2',
'jxl': 'image/jxl'
};
async function generatePictureElement(site: Site, document: HTMLDocument, image: Element) {
const imgSrc = image.getAttribute('src');
const imgWidth = image.getAttribute('width');
if (!imgSrc) {
throw new ReferenceError('Image is missing src: ' + image.outerHTML);
}
// Remote image, ignore.
if (imgSrc.includes('http://') || imgSrc.includes('https://')) {
return image;
}
if (!imgWidth) {
throw new ReferenceError('Image is missing width: ' + image.outerHTML);
}
const url = posix.relative(site.options.location.pathname, imgSrc);
const originalImageExtention = extname(url);
const filename = basename(imgSrc).split(extname(imgSrc))[0];
const width = parseInt(imgWidth, 10);
const srcset = image.getAttribute('data-srcset');
const sizes: number[] = srcset ?
srcset
.split(',')
.map(s => s.trim())
.map(s => {
if (s.includes('w')) {
return parseInt(s, 10);
} else if (s.includes('x')) {
return parseFloat(s) * width;
} else {
throw new TypeError('Invalid srcset on image: ' + image.outerHTML);
}
}) :
[width, width * 1.5, width * 2];
const tasks = await Promise.all(
sizes.map(async size => {
const isMacOS = Deno.env.get('_system_type') === 'Darwin';
const formatsToRender = [];
const searches = formats.map(format => `_cache/${dirname(url)}/${filename}_${size}w.${format}`).map(async path => {
const found = await exists(path);
return { path, found };
});
for await (const search of searches) {
if (!search.found) {
formatsToRender.push(extname(search.path));
}
}
const formatOptions = formatsToRender.map(format => {
const flag = format === 'jpg' ? 'mozjpeg' : format.split('.').pop();
return `--${flag} auto`;
}).join(' ');
if (formatOptions.length === 0) {
return undefined;
}
return `npx @squoosh/cli --resize '{width: ${size}}' ${formatOptions} --output-dir _cache/${dirname(url)}/ -s '_${size}w' ${url}`;
})
);
const definedTasks = tasks.filter(Boolean) as string[];
squooshTasks.push(...definedTasks);
const picture = document.createElement('picture');
formats.forEach(format => {
const newSrcset = sizes
.map(size => `/${url.replace(originalImageExtention, `_${size}w.${format}`)} ${size}w`)
.join(', ');
const source = document.createElement('source');
source.setAttribute('srcset', newSrcset);
source.setAttribute('type', mimeTypes[format]);
picture.appendChild(source);
});
const img = document.createElement('img');
img.setAttribute('src', '/' + url.replace(originalImageExtention, `_${sizes[0]}w.${formats[0]}`));
img.setAttribute('alt', image.getAttribute('alt'));
img.setAttribute('width', image.getAttribute('width'));
img.setAttribute('sizes', width + 'w');
img.setAttribute('loading', 'lazy');
img.setAttribute('decoding', 'async');
picture.setAttribute('title', image.getAttribute('alt'));
picture.appendChild(img);
return picture;
}
function findAndOptimizeImages(site: Site, { document }: Page) {
if (document) {
const imgTags = [...document.querySelectorAll('img')];
return Promise.all(imgTags.map(async image => {
const picture = await generatePictureElement(site, document, image as Element);
if (image && image.parentNode) {
image.parentNode.replaceChild(picture, image);
}
}));
}
return Promise.resolve();
}
/**
*
* @param {'avif'|'jpg'|'webp'|'wp2'|'jxl'} _formats
* @returns
*/
export default function (_formats = [
'avif',
'webp'
]) {
formats = _formats;
return (site: Site) => {
site.process(['.html'], page => findAndOptimizeImages(site, page));
site.addEventListener('afterBuild', () => {
// Spread so they run in series, parallel will freeze your computer. :)
site.script('image-optimizer', ...squooshTasks, 'cp -r _cache/img _site/');
site.run('image-optimizer');
});
};
}