-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-images.js
242 lines (209 loc) · 8.52 KB
/
generate-images.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
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
import fm from "front-matter"
import fs from "fs";
import path from 'path';
import {makeDirectory} from "./src/lib/utils/file.js";
import {metadata, dominantColour, lowResolutionPlaceholder} from "./src/lib/utils/image.js";
const BLOG_PATH = 'src/posts'
const PORTFOLIO_PATH = 'src/routes/works/portfolioData.json';
const __dirname = path.resolve();
const formats = ['avif', 'webp', 'auto'];
const sizes = [760];
const portfolioSizes = [548];
const densities = [1.0];
const maxWidth = sizes[sizes.length - 1];
const maxPortfolioImageWidth = sizes[sizes.length - 1];
// use sizes and densities arrays to determine the actual output widths needed
const outputSizes = [];
const portfolioOutputSizes = [];
sizes.forEach((sizesElement) => {
densities.forEach((densitiesElement) => outputSizes.push(densitiesElement * sizesElement));
});
outputSizes.sort((a, b) => b - a);
portfolioSizes.forEach((sizesElement) => {
densities.forEach((densitiesElement) => portfolioOutputSizes.push(densitiesElement * sizesElement));
});
portfolioOutputSizes.sort((a, b) => b - a);
async function generateImageMeta(source) {
const metaPromises = [
metadata({ source }),
dominantColour({ source }),
lowResolutionPlaceholder({ source }),
];
const [metadataResult, dominantColourObject, placeholder] = await Promise.all(metaPromises);
const { format, width, height } = metadataResult;
const { r, g, b } = dominantColourObject;
const dominantColourValue = `#${r.toString(16)}${g.toString(16)}${b.toString(16)}`;
return { dominantColour: dominantColourValue, placeholder, format, width, height };
}
async function getPostImages(location) {
const directories = fs
.readdirSync(location)
.filter((element) => fs.lstatSync(`${location}/${element}`).isDirectory());
const images = [];
for (const directory of directories) {
const contentPath = `${location}/${directory}/${directory}.md`;
if (!fs.existsSync(contentPath)) {
continue;
}
const content = fs.readFileSync(contentPath, { encoding: 'utf-8' });
const fmContent = fm(content);
const {
image,
imageAlt: alt
} = fmContent.attributes;
images.push({
image,
slug: directory,
alt,
contentImages: fmContent.attributes.postImages
})
}
return images;
}
async function generatePostImages() {
const location = path.join(__dirname, BLOG_PATH);
const postImages = await getPostImages(location);
const imageMetaPromises = postImages.map(async (element) => {
const { image, slug } = element;
const source = path.join(__dirname, 'src/lib/assets/blog/', slug, image);
return generateImageMeta(source);
});
const imageMetadata = await Promise.all(imageMetaPromises);
const contentImageMetaPromises = [];
for (const postImage of postImages) {
if (!postImage.contentImages) {
continue
}
const { slug } = postImage
for (const contentImage of postImage.contentImages) {
if (!contentImage) {
continue
}
const { image } = contentImage;
const source = path.join(__dirname, 'src/lib/assets/blog/', slug, image);
contentImageMetaPromises.push(generateImageMeta(source));
}
}
const contentImageMetaData = await Promise.all(contentImageMetaPromises);
const imageGeneratedDir = path.join(__dirname, 'src/lib/generated/posts');
await makeDirectory(imageGeneratedDir);
let contentImageIndex = 0;
for (let index in postImages) {
const postImage = postImages[index];
const { image, slug, alt } = postImage;
const { dominantColour, format, placeholder, width } = imageMetadata[index];
const postDirectory = path.join(imageGeneratedDir, slug);
const postPath = path.join(postDirectory, `${slug}.ts`);
const generatePath = (image, width, slug, alt, placeholder, dominantColour, format, renderSlug = null) => {
renderSlug = renderSlug ? renderSlug : slug;
const source = `$lib/assets/blog/${slug}/${image}`
const srcsetImportArray = formats.map(
(formatsElement) =>
`import srcset${formatsElement} from '${source}?w=${
width < outputSizes[0] ? `${width};` : ''
}${outputSizes
.filter((outputSizesElement) => outputSizesElement <= width)
.join(';')}&format=${formatsElement === 'auto' ? format : formatsElement}&as=srcset';`,
);
const sources = `[\n${formats
.map(
(formatsElement) =>
` { srcset: ${`srcset${formatsElement}`}, type: ${
formatsElement === 'auto' ? `'image/${format}'` : `'image/${formatsElement}'`
} },`,
)
.join('\n')}\n ]`;
return `import meta from '${source}?w=${Math.min(
maxWidth,
width,
)}&as=meta:height;src;width';
${srcsetImportArray.join('\n')}
const { height, src, width } = meta;
const data = {
slug: '${renderSlug}',
width,
height,
src,
alt: '${alt}',
sources: ${sources},
dominantColour: '${dominantColour}',
placeholder:
'${placeholder}',
};
export { data as default };
`;
}
const result = generatePath(image, width, slug, alt, placeholder, dominantColour, format);
await makeDirectory(postDirectory)
fs.writeFileSync(postPath, result, 'utf-8');
for (const contentImage of postImage.contentImages ) {
const { image, slug: contentImgSlug, alt } = contentImage;
const { dominantColour, format, placeholder, width } = contentImageMetaData[contentImageIndex];
const contentImagePath = path.join(postDirectory, `${contentImgSlug}.ts`);
const result = generatePath(image, width, slug, alt, placeholder, dominantColour, format, contentImgSlug);
fs.writeFileSync(contentImagePath, result, 'utf-8');
contentImageIndex++;
}
}
}
async function generatePortfolioImages() {
const location = path.join(__dirname, PORTFOLIO_PATH);
const file = fs.readFileSync(location, { encoding: 'utf-8' })
const data = JSON.parse(file);
const images = data.items.map(item => item.images).flat()
const imageMetaPromises = images.map(async (element) => {
const { url } = element;
const source = path.join(__dirname, 'src/lib/assets/works/', url);
return generateImageMeta(source);
});
const imageMetadata = await Promise.all(imageMetaPromises);
const imageGeneratedDir = path.join(__dirname, 'src/lib/generated/works');
await makeDirectory(imageGeneratedDir);
images.forEach((portfolioImage, index) => {
const { url, slug, alt } = portfolioImage;
const { dominantColour, format, placeholder, width } = imageMetadata[index];
const postPath = path.join(imageGeneratedDir, `${slug}.ts`);
const source = `$lib/assets/works/${url}`
const srcsetImportArray = formats.map(
(formatsElement) =>
`import srcset${formatsElement} from '${source}?w=${
width < portfolioOutputSizes[0] ? `${width};` : ''
}${portfolioOutputSizes
.filter((outputSizesElement) => outputSizesElement <= width)
.join(';')}&format=${formatsElement === 'auto' ? format : formatsElement}&as=srcset';`,
);
const sources = `[\n${formats
.map(
(formatsElement) =>
` { srcset: ${`srcset${formatsElement}`}, type: ${
formatsElement === 'auto' ? `'image/${format}'` : `'image/${formatsElement}'`
} },`,
)
.join('\n')}\n ]`;
const result = `import meta from '${source}?w=${Math.min(
maxWidth,
width,
)}&as=meta:height;src;width';
${srcsetImportArray.join('\n')}
const { height, src, width } = meta;
const data = {
slug: '${slug}',
width,
height,
alt: '${alt}',
src,
sources: ${sources},
dominantColour: '${dominantColour}',
placeholder:
'${placeholder}',
};
export { data as default };
`;
fs.writeFileSync(postPath, result, 'utf-8');
});
}
async function main() {
const promises = [generatePortfolioImages(), generatePostImages()]
await Promise.allSettled(promises)
}
await main();