-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgatsby-node.ts
More file actions
483 lines (428 loc) · 12.9 KB
/
gatsby-node.ts
File metadata and controls
483 lines (428 loc) · 12.9 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import type { CreateSchemaCustomizationArgs, GatsbyNode } from "gatsby";
import path from "path";
import chroma, { Color } from "chroma-js";
// import chalk from "chalk";
import * as R from "ramda";
import exifr from "exifr";
import sharp from "sharp";
// @ts-ignore
import { Palette } from "node-vibrant/lib/color";
import fs from "fs";
import md5 from "md5";
import { globSync } from "glob";
import {
DateFormatter,
parseAbsoluteToLocal,
ZonedDateTime,
} from "@internationalized/date";
import util from "node:util";
import { exec as _exec } from "child_process";
const exec = util.promisify(_exec);
const hash = md5(`${new Date().getTime()}`);
const addPageDataVersion = async (file: any) => {
const stats = await util.promisify(fs.stat)(file);
if (stats.isFile()) {
console.log(`Adding version to page-data.json in ${file}..`);
let content = await util.promisify(fs.readFile)(file, "utf8");
const result = content.replace(
/page-data.json(\?v=[a-f0-9]{32})?/g,
`page-data.json?v=${hash}`,
);
await util.promisify(fs.writeFile)(file, result, "utf8");
}
};
export const onPostBootstrap = async () => {
const loader = path.join(
__dirname,
"node_modules/gatsby/cache-dir/loader.js",
);
await addPageDataVersion(loader);
};
export const onPostBuild = async () => {
const publicPath = path.join(__dirname, "public");
const htmlAndJSFiles = globSync(`${publicPath}/**/*.{html,js}`);
for (let file of htmlAndJSFiles) {
await addPageDataVersion(file);
}
};
// const badContrast = (color1: Color, color2: Color) =>
// chroma.contrast(color1, color2) < 4.5;
// const logColorsWithContrast = (color1: Color, color2: Color, text: string) => {
// const c1hex = color1.hex();
// const c2hex = color2.hex();
// console.log(
// // chalk.hex(c1hex).bgHex(c2hex)(
// // `${text} ${c1hex}/${c2hex} ${chroma.contrast(color1, color2)}`,
// // ),
// );
// };
function processColors(vibrantData: Palette, imagePath: string) {
let Vibrant = chroma(vibrantData.Vibrant!.getRgb());
let DarkVibrant = chroma(vibrantData.DarkVibrant!.getRgb());
let LightVibrant = chroma(vibrantData.LightVibrant!.getRgb());
let Muted = chroma(vibrantData.Muted!.getRgb());
let DarkMuted = chroma(vibrantData.DarkMuted!.getRgb());
let LightMuted = chroma(vibrantData.LightMuted!.getRgb());
// // first pass - darken bg and lighten relevant fg colors
// if (
// badContrast(DarkVibrant, Vibrant) ||
// badContrast(DarkVibrant, LightMuted)
// ) {
// DarkVibrant = DarkVibrant.darken();
// }
// if (badContrast(DarkVibrant, Vibrant)) {
// Vibrant = Vibrant.brighten();
// }
// if (badContrast(DarkVibrant, Vibrant)) {
// Vibrant = Vibrant.brighten();
// }
// // second pass - first doesn't always do enough
// if (badContrast(DarkVibrant, Vibrant)) {
// Vibrant = Vibrant.brighten(2);
// }
// if (badContrast(DarkVibrant, LightMuted)) {
// LightMuted = LightMuted.brighten(2);
// }
// // only used for hover styles, so we should give it a shot but it's not a huge deal if it's not very legible
// if (badContrast(Muted, LightMuted)) {
// Muted = Muted.darken();
// }
// if (badContrast(DarkVibrant, Vibrant)) {
// console.warn("contrast still too low", imagePath);
// logColorsWithContrast(Vibrant, DarkVibrant, "V-DV");
// }
// if (badContrast(DarkVibrant, LightMuted)) {
// console.warn("contrast still too low", imagePath);
// logColorsWithContrast(LightMuted, DarkVibrant, "LM-DV");
// }
return {
Vibrant: Vibrant.rgb(),
DarkVibrant: DarkVibrant.rgb(),
LightVibrant: LightVibrant.rgb(),
Muted: Muted.rgb(),
DarkMuted: DarkMuted.rgb(),
LightMuted: LightMuted.rgb(),
};
}
// function convertDMSToDD(dms, positiveDirection) {
// const res = dms
// .map((item, i) => {
// return item / Math.pow(60, i);
// })
// .reduce((a, b) => a + b);
// return positiveDirection ? res : -res;
// }
// const gps = { longitude: null, latitude: null };
// if (exifData) {
// if (exifData.gps && exifData.gps.GPSLongitude && exifData.gps.GPSLatitude) {
// gps.longitude = convertDMSToDD(
// exifData.gps.GPSLongitude,
// exifData.gps.GPSLongitudeRef === "E"
// );
// gps.latitude = convertDMSToDD(
// exifData.gps.GPSLatitude,
// exifData.gps.GPSLatitudeRef === "N"
// );
// }
// }
function transformMetaToNodeData(
metaData: Record<string, unknown>,
dateTimeOriginal: ZonedDateTime,
vibrantData: Palette,
imagePath: string,
{ r, g, b }: { r: number; b: number; g: number },
datePublished: string,
) {
// const vibrant = vibrantData ? processColors(vibrantData, imagePath) : null;
// const vibrantHue = vibrantData.Vibrant!.getHsl()[0] * 360;
let dominantHue = chroma(r, g, b).hsl();
if (isNaN(dominantHue[0])) {
dominantHue[0] = 0;
}
let Keywords = metaData.Keywords;
if (!Keywords) {
Keywords = [];
}
if (!Array.isArray(Keywords)) {
Keywords = [Keywords];
}
return {
dateTaken: dateTimeOriginal.toDate(),
datePublished,
meta: {
Make: metaData.Make,
Model: metaData.Model,
ExposureTime: metaData.ExposureTime,
FNumber: metaData.FNumber,
ISO: metaData.ISO,
DateTimeOriginal: dateTimeOriginal.toDate(),
OffsetTimeOriginal: metaData.OffsetTimeOriginal,
CreateDate: metaData.CreateDate,
ModifyDate: metaData.ModifyDate,
ShutterSpeedValue: metaData.ShutterSpeedValue,
ApertureValue: metaData.ApertureValue,
FocalLength: metaData.FocalLength,
LensModel: metaData.LensModel,
ObjectName: metaData.ObjectName,
Caption: metaData.Caption,
City: metaData.City,
State: metaData.State,
Location: metaData.Location,
Rating: metaData.Rating,
Keywords,
},
// vibrant,
// vibrantHue,
// dominantHue,
};
}
function transformDate(imagePath: string, dateTimeOriginal: string, offsetTimeOriginal: string) {
if (!offsetTimeOriginal) {
console.log(`${imagePath} has no timezone offset. Defaulting to UTC-8`)
}
const [date, time] = dateTimeOriginal.split(" ");
const iso8601 = `${date.replace(/\:/g, "-")}T${time}${offsetTimeOriginal ?? '-08:00'}`;
return parseAbsoluteToLocal(iso8601);
}
// const monthFormatter = new DateFormatter("en_US", {
// month: "long",
// });
export const onCreateNode: GatsbyNode["onCreateNode"] = async function ({
node,
actions,
}) {
const { createNodeField } = actions;
if (node.internal.type === "File" && node.sourceInstanceName === "photos") {
// organization data
let meta: Awaited<ReturnType<typeof exifr.parse>>;
try {
meta = await exifr.parse(node.absolutePath as string, {
iptc: true,
xmp: true,
reviveValues: false,
// icc: true
});
} catch (e) {
console.error(
`🅱️ something went wrong with exifr on image ${node.base}`,
e,
);
throw e;
}
const dateTimeOriginal = transformDate(
node.base as string,
meta.DateTimeOriginal,
meta.OffsetTimeOriginal,
);
const month = dateTimeOriginal.month;
const year = dateTimeOriginal.year;
const yearFolder = year < 2021 ? "Older" : `${year}`;
const monthSlug =
yearFolder === "Older"
? `${yearFolder}`
: `${yearFolder}/${dateTimeOriginal.toDate().toLocaleString("en", { month: "long" })}`;
const slug = `photos/${monthSlug}/${node.base}`;
// const slug = `photos/${node.base}`;
createNodeField({
node,
name: "organization",
value: {
year,
month,
yearFolder,
monthSlug,
slug,
},
});
// image metadata
const { stdout: datePublished, stderr } = await exec(
`git log --diff-filter=A --follow --format=%aI -1 -- ${node.absolutePath}`,
);
if (stderr.length) {
console.error("something went wrong checking publish date: ", stderr);
}
if (!meta.Rating) {
console.log(`${node.base} has no rating`);
}
if (!meta.Keywords) {
console.log(`${node.base} has no keywords`);
}
let sharpImage: sharp.Sharp;
try {
sharpImage = sharp(node.absolutePath as string);
} catch (e) {
console.error(`something wen wrong with sharp on image ${node.base}`, e);
throw e;
}
const { dominant } = await sharpImage.stats();
// const resizedImage = await sharpImage
// .resize({
// width: 3000,
// height: 3000,
// fit: "inside",
// })
// .toBuffer();
// const vibrantData = await Vibrant.from(resizedImage)
// // .quality(1)
// .getPalette();
createNodeField({
node,
name: "imageMeta",
value: transformMetaToNodeData(
meta,
dateTimeOriginal,
null, // vibrantData,
node.absolutePath as string,
dominant,
// if datePublished is empty, image has not been committed to git yet and is thus brand new
datePublished.length
? datePublished.replace("\n", "")
: new Date().toDateString(),
),
});
}
};
// Implement the Gatsby API “createPages”. This is called once the
// data layer is bootstrapped to let plugins create pages from data.
export const createPages: GatsbyNode["createPages"] = async ({
graphql,
actions,
reporter,
}) => {
const { createPage } = actions;
const photos = await graphql<Queries.PhotosQuery>(`
query Photos {
allFile(filter: { sourceInstanceName: { eq: "photos" } }) {
nodes {
base
id
fields {
organization {
year
yearFolder
monthSlug
month
slug
}
}
}
}
}
`);
// Handle errors
if (photos.errors) {
reporter.panicOnBuild("Error while running GraphQL query.");
return;
}
// Create pages for each markdown file.
const photoImageTemplate = path.resolve(
"src/components/photos/PhotoImage/PhotoImage.tsx",
);
// const diffDate = (a, b) =>
// new Date(R.path(['node', 'childImageSharp', 'fields', 'imageMeta', 'dateTaken'], a)).getTime() - new Date(R.path(['node', 'childImageSharp', 'fields', 'imageMeta', 'dateTaken'],b)).getTime();
const nodes = R.sort(
R.descend(
(edge) =>
new Date(R.path(["node", "fields", "imageMeta", "dateTaken"], edge)!),
),
photos.data!.allFile.nodes!,
);
const years: Record<string, number> = {
Older: 1,
};
const months: Record<string, number> = {};
nodes.forEach(({ base, fields, id }) => {
if (!fields) {
console.log("no fields", base);
return;
}
const { yearFolder, monthSlug, slug } = fields.organization!;
years[yearFolder!] = 1;
months[monthSlug!] = 1;
const page = {
path: slug!,
component: photoImageTemplate,
context: {
imageId: id,
},
};
createPage(page);
});
const photoYearTemplate = path.resolve("src/components/photos/PhotoYear.tsx");
Object.keys(years).forEach((year) => {
createPage({
path: `photos/${year}`,
component: photoYearTemplate,
context: {
year,
},
});
});
const photoMonthTemplate = path.resolve(
"src/components/photos/PhotoMonth.tsx",
);
Object.keys(months).forEach((month) => {
createPage({
path: `photos/${month}`,
component: photoMonthTemplate,
context: {
monthSlug: month,
},
});
});
console.log("years", years);
console.log("months", months);
// posts
const postsQuery = await graphql<Queries.PostsQuery>(`
query Posts {
allMdx {
nodes {
id
frontmatter {
slug
date
}
internal {
contentFilePath
}
}
}
}
`);
if (postsQuery.errors) {
reporter.panicOnBuild("Error loading MDX result", postsQuery.errors);
}
// Create blog post pages.
const posts = postsQuery.data!.allMdx.nodes;
const postTemplate = path.resolve(`./src/components/Posts/PostTemplate.tsx`);
// you'll call `createPage` for each result
posts.forEach((node) => {
createPage({
// As mentioned above you could also query something else like frontmatter.title above and use a helper function
// like slugify to create a slug
path: `/posts${node.frontmatter!.slug!}`,
// Provide the path to the MDX content file so webpack can pick it up and transform it into JSX
component: `${postTemplate}?__contentFilePath=${node.internal.contentFilePath}`,
// You can use the values in this context in
// our page layout component
context: { id: node.id },
});
});
};
export const createSchemaCustomization = ({
actions,
schema,
}: CreateSchemaCustomizationArgs) => {
const { createTypes } = actions;
createTypes(`
type Mdx implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
date: Date
slug: String
title: String
galleryImages: [File] @link(by: "base")
}
`);
};