-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenhance-images.ts
More file actions
483 lines (443 loc) · 12.5 KB
/
Copy pathenhance-images.ts
File metadata and controls
483 lines (443 loc) · 12.5 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 {
ArticleDesign,
type ArticleFormat,
ArticleSpecial,
isUndefined,
} from '@guardian/libs';
import { JSDOM } from 'jsdom';
import { getLargest, getMaster } from '../lib/image';
import type {
CartoonBlockElement,
FEElement,
Image,
ImageBlockElement,
ImageForLightbox,
MultiImageBlockElement,
SubheadingBlockElement,
TextBlockElement,
} from '../types/content';
interface HalfWidthImageBlockElement extends ImageBlockElement {
role: 'halfWidth';
}
/**
* When opening cartoons in the lightbox we always want the entire cartoon,
* i.e. the desktop version stored in the large variant
*/
export const getCartoonImageForLightbox = (
element: CartoonBlockElement,
): Image[] => {
const largeVariant = element.variants.find(
(variant) => variant.viewportSize === 'large',
);
return largeVariant?.images ?? [];
};
const isHalfWidthImage = (
element?: FEElement,
): element is HalfWidthImageBlockElement => {
if (!element) return false;
return (
element._type ===
'model.dotcomrendering.pageElements.ImageBlockElement' &&
element.role === 'halfWidth'
);
};
const isMultiImage = (
element?: FEElement,
): element is MultiImageBlockElement => {
if (!element) return false;
return (
element._type ===
'model.dotcomrendering.pageElements.MultiImageBlockElement'
);
};
export const isImage = (element?: FEElement): element is ImageBlockElement => {
if (!element) return false;
return (
element._type === 'model.dotcomrendering.pageElements.ImageBlockElement'
);
};
export const isCartoon = (
element?: FEElement,
): element is CartoonBlockElement => {
if (!element) return false;
return (
element._type ===
'model.dotcomrendering.pageElements.CartoonBlockElement'
);
};
const isTitle = (element?: FEElement): element is SubheadingBlockElement => {
if (!element) return false;
// Checks if this element is a 'title' based on the convention: <h2>Title text</h2>
if (
element._type !==
'model.dotcomrendering.pageElements.SubheadingBlockElement'
) {
return false;
}
const frag = JSDOM.fragment(element.html);
return frag.firstElementChild?.nodeName === 'H2';
};
const extractTitle = (element: SubheadingBlockElement): string => {
// We cast here because we're know this element is a subheading but TS isn't sure
const subHeading = element;
// Extract 'title' based on the convention: <h2>Title text</h2>
const frag = JSDOM.fragment(subHeading.html);
if (!frag.firstElementChild) return '';
const isH2tag = frag.firstElementChild.nodeName === 'H2';
if (isH2tag) {
// element is an essay title
return frag.textContent?.trim() ?? '';
}
return '';
};
const isCaption = (element?: FEElement): element is TextBlockElement => {
if (!element) return false;
// Checks if this element is a 'caption' based on the convention: <ul><li><Caption text</li></ul>
if (
element._type !== 'model.dotcomrendering.pageElements.TextBlockElement'
) {
return false;
}
const frag = JSDOM.fragment(element.html);
if (!frag.firstElementChild) return false;
const hasULwrapper = frag.firstElementChild.nodeName === 'UL';
const containsLItags = frag.firstElementChild.outerHTML.includes('<li>');
return hasULwrapper && containsLItags;
};
const extractCaption = (element: TextBlockElement): string => {
// Extract 'caption' based on the convention: <ul><li><Caption text</li></ul>
// We cast here because we're know this element is a text element but TS isn't sure
const textElement = element;
const frag = JSDOM.fragment(textElement.html);
if (!frag.firstElementChild) return '';
const hasULwrapper = frag.firstElementChild.nodeName === 'UL';
const containsLItags = frag.firstElementChild.outerHTML.includes('<li>');
if (hasULwrapper && containsLItags) {
return textElement.html;
}
return '';
};
const constructMultiImageElement = (
first: ImageBlockElement,
second: ImageBlockElement,
): MultiImageBlockElement => {
return {
_type: 'model.dotcomrendering.pageElements.MultiImageBlockElement',
elementId: first.elementId,
images: [
{
...first,
data: {
...first.data,
caption: '', // Delete any existing caption (special captions might be added later)
},
},
{
...second,
data: {
...second.data,
caption: '', // ibid
},
},
],
};
};
const addMultiImageElements = (elements: FEElement[]): FEElement[] => {
const withMultiImageElements: FEElement[] = [];
for (const [i, thisElement] of elements.entries()) {
const nextElement = elements[i + 1];
if (isHalfWidthImage(thisElement) && isHalfWidthImage(nextElement)) {
// Pair found. Add a multi element and remove the next entry
withMultiImageElements.push(
constructMultiImageElement(thisElement, nextElement),
);
// Remove the next element
elements.splice(i + 1, 1);
} else {
// Pass through
withMultiImageElements.push(thisElement);
}
}
return withMultiImageElements;
};
const addTitles = (elements: FEElement[]): FEElement[] => {
const withTitles: FEElement[] = [];
for (const [i, thisElement] of elements.entries()) {
const nextElement = elements[i + 1];
const subsequentElement = elements[i + 2];
if (isImage(thisElement) && isTitle(nextElement)) {
// This element is an image and is immediately followed by a title
withTitles.push({
...thisElement,
title: extractTitle(nextElement),
});
// Remove the element
elements.splice(i + 1, 1);
} else if (
isImage(thisElement) &&
isCaption(nextElement) &&
isTitle(subsequentElement)
) {
// This element is an image, was followed by a caption, and then had a title after it
withTitles.push({
...thisElement,
title: extractTitle(subsequentElement),
});
// Remove the element
elements.splice(i + 2, 1);
} else {
// Pass through
withTitles.push(thisElement);
}
}
return withTitles;
};
const addCaptionsToImages = (elements: FEElement[]): FEElement[] => {
const withSpecialCaptions: FEElement[] = [];
for (const [i, thisElement] of elements.entries()) {
const nextElement = elements[i + 1];
const subsequentElement = elements[i + 2];
if (isImage(thisElement) && isCaption(nextElement)) {
const thisImage = thisElement;
withSpecialCaptions.push({
...thisImage,
data: {
...thisImage.data,
caption: extractCaption(nextElement),
},
});
// Remove the next element
elements.splice(i + 1, 1);
} else if (
isImage(thisElement) &&
isTitle(nextElement) &&
isCaption(subsequentElement)
) {
const thisImage = thisElement;
withSpecialCaptions.push({
...thisImage,
data: {
...thisImage.data,
caption: extractCaption(subsequentElement),
},
});
// Remove the subsequent element
elements.splice(i + 2, 1);
} else {
// Pass through
withSpecialCaptions.push(thisElement);
}
}
return withSpecialCaptions;
};
const addCaptionsToMultis = (elements: FEElement[]): FEElement[] => {
const withSpecialCaptions: FEElement[] = [];
for (const [i, thisElement] of elements.entries()) {
const nextElement = elements[i + 1];
const subsequentElement = elements[i + 2];
if (isMultiImage(thisElement) && isCaption(nextElement)) {
withSpecialCaptions.push({
...thisElement,
caption: extractCaption(nextElement),
});
// Remove the next element
elements.splice(i + 1, 1);
} else if (
isMultiImage(thisElement) &&
isTitle(nextElement) &&
isCaption(subsequentElement)
) {
withSpecialCaptions.push({
...thisElement,
caption: extractCaption(subsequentElement),
});
// Remove the subsequent element
elements.splice(i + 2, 1);
} else {
// Pass through
withSpecialCaptions.push(thisElement);
}
}
return withSpecialCaptions;
};
const stripCaptions = (elements: FEElement[]): FEElement[] =>
// Remove all captions from all images
elements.map<FEElement>((thisElement) => {
if (
thisElement._type ===
'model.dotcomrendering.pageElements.ImageBlockElement'
) {
// Remove the caption from this image
return {
...thisElement,
data: {
...thisElement.data,
caption: '',
},
};
} else {
// Pass through
return thisElement;
}
});
const removeCredit = (elements: FEElement[]): FEElement[] =>
// Remove credit from all images
elements.map<FEElement>((thisElement) => {
if (
thisElement._type ===
'model.dotcomrendering.pageElements.ImageBlockElement'
) {
// Remove the credit from this image
return {
...thisElement,
data: {
...thisElement.data,
credit: '',
},
};
} else {
// Pass through
return thisElement;
}
});
const addImagePositions = <E extends FEElement>(
elements: E[],
imagesForLightbox: ImageForLightbox[],
): E[] =>
elements.map<E>((element) => {
if (isMultiImage(element)) {
return {
...element,
images: addImagePositions(element.images, imagesForLightbox),
};
}
if (!isImage(element) && !isCartoon(element)) {
return element;
}
const allImages = isImage(element)
? element.media.allImages
: getCartoonImageForLightbox(element);
const image = getMaster(allImages) ?? getLargest(allImages);
const position = imagesForLightbox.find(
({ masterUrl }) => image?.url === masterUrl,
)?.position;
return isUndefined(position) ? element : { ...element, position };
});
class Enhancer {
elements: FEElement[];
constructor(elements: FEElement[]) {
this.elements = elements;
}
/**
* Photo essays by convention have all image captions removed and rely completely on
* special captions set using the `ul`/`li` trick
*/
stripCaptions() {
this.elements = stripCaptions(this.elements);
return this;
}
/**
* Replace pairs of halfWidth images with MultiImageBlockElements
*/
addMultiImageElements() {
this.elements = addMultiImageElements(this.elements);
return this;
}
/**
* Photo essay have a convention of adding titles to images if the subsequent block is a h2
*/
addTitles() {
this.elements = addTitles(this.elements);
return this;
}
/**
* If any MultiImageBlockElement is followed by a ul/l caption, delete the special caption
* element and use the value for the multi image `caption` prop
*/
addCaptionsToMultis() {
this.elements = addCaptionsToMultis(this.elements);
return this;
}
/**
* In photo essays, we also use ul captions for normal images as well
*/
addCaptionsToImages() {
this.elements = addCaptionsToImages(this.elements);
return this;
}
/**
* By convention, photo essays don't include credit for images in the caption
*/
removeCredit() {
this.elements = removeCredit(this.elements);
return this;
}
/**
* This function adds the position property to each image
* element.
*
* This value is used to add an id which means we can add a hash to
* the url, such as #img-2, letting us navigate to that image.
*
* We also use this id to open lightbox when the page is loaded
* with an image hash present on the url
*
*/
addImagePositions(imagesForLightbox: ImageForLightbox[]) {
this.elements = addImagePositions(this.elements, imagesForLightbox);
return this;
}
}
const enhance =
(
isPhotoEssay: boolean,
imagesForLightbox: ImageForLightbox[],
isPhotoEssayMainMedia = false,
) =>
(elements: FEElement[]): FEElement[] => {
if (isPhotoEssay) {
if (isPhotoEssayMainMedia) {
return new Enhancer(elements)
.addMultiImageElements()
.addTitles()
.addCaptionsToMultis()
.addCaptionsToImages()
.addImagePositions(imagesForLightbox).elements;
}
return new Enhancer(elements)
.stripCaptions()
.removeCredit()
.addMultiImageElements()
.addTitles()
.addCaptionsToMultis()
.addCaptionsToImages()
.addImagePositions(imagesForLightbox).elements;
}
return (
new Enhancer(elements)
// Replace pairs of halfWidth images with MultiImageBlockElements
.addMultiImageElements()
// If any MultiImageBlockElement is followed by a ul/l caption, delete the special caption
// element and use the value for the multi image `caption` prop
.addCaptionsToMultis()
.addImagePositions(imagesForLightbox).elements
);
};
export const enhanceImages = (
format: ArticleFormat,
imagesForLightbox: ImageForLightbox[],
): ((elements: FEElement[]) => FEElement[]) => {
const isPhotoEssay = format.design === ArticleDesign.PhotoEssay;
return enhance(isPhotoEssay, imagesForLightbox);
};
export const enhanceElementsImages = (
format: ArticleFormat,
isMainMedia: boolean,
imagesForLightbox: ImageForLightbox[],
): ((elements: FEElement[]) => FEElement[]) => {
const isPhotoEssay =
format.design === ArticleDesign.PhotoEssay &&
format.theme !== ArticleSpecial.Labs;
const isPhotoEssayMainMedia = isPhotoEssay && isMainMedia;
return enhance(isPhotoEssay, imagesForLightbox, isPhotoEssayMainMedia);
};