@cntrl-site/sdk-nextjs 1.11.17 → 1.11.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,28 +1,41 @@
1
1
  import { getLayoutStyles, getShownCaption, ImageStructuredBlock } from '@cntrl-site/sdk';
2
- import { FC, useCallback, useId, useState } from 'react';
2
+ import { FC, useCallback, useId, useRef, useState } from 'react';
3
3
  import JSXStyle from 'styled-jsx/style';
4
4
  import { useCntrlContext } from '../../../provider/useCntrlContext';
5
5
  import { useItemGeometry } from '../../../ItemGeometry/useItemGeometry';
6
+ import { ImageLightbox } from '../../ImageLightbox/ImageLightbox';
7
+ import { useLayoutContext } from '../../useLayoutContext';
6
8
  import { StructuredBlockItemProps } from '../StructuredBlockItem';
7
9
  import { BlockCaption } from '../BlockCaption/BlockCaption';
8
10
 
9
11
  const GALLERY_GAP_PX = 8;
12
+ const HOVER_ZOOM = 1.03;
10
13
 
11
14
  /**
12
15
  * A gallery: its images side by side in one row, each growing from nothing by its share of the row's
13
16
  * aspect ratios, so that they fill the row as their ratios do and come out equally tall, with the
14
- * caption under them. Until an image has loaded its ratio is taken to be square.
17
+ * caption under them. Until an image has loaded its ratio is taken to be square. A gallery that opens
18
+ * in a lightbox on some layout makes each image a button, live on the layouts it does: there it opens
19
+ * the image full screen, to step through the gallery's own images, and the image zooms a little under
20
+ * the pointer, within its place in the row, to say so. The image opened moves out of its place in the
21
+ * row into the lightbox, and the one shown when the lightbox closes moves back into its own.
15
22
  */
16
23
  export const StructuredImage: FC<StructuredBlockItemProps<ImageStructuredBlock>> = ({ block, readingWidth }) => {
17
24
  const reactId = useId();
18
25
  const { layouts } = useCntrlContext();
19
26
  const [ref, setRef] = useState<HTMLDivElement | null>(null);
20
27
  useItemGeometry(block.id, ref);
21
- const { altText } = block.commonParams;
28
+ const layoutId = useLayoutContext();
29
+ const hasLightbox = Object.values(block.layoutParams).some(params => params.lightbox);
30
+ // the layout is known once the page is on screen: until then the images open nothing
31
+ const opensLightbox = layoutId !== undefined && Boolean(block.layoutParams[layoutId]?.lightbox);
22
32
  // a file the API could not resolve comes as an empty url: nothing to draw for it
23
- const urls = block.commonParams.urls.filter(url => url !== '');
33
+ const pictures = block.commonParams.images.filter(({ url }) => url !== '');
24
34
  const caption = getShownCaption(block.commonParams);
25
35
  const [ratios, setRatios] = useState<Record<string, number>>({});
36
+ const [openIndex, setOpenIndex] = useState<number | null>(null);
37
+ const openers = useRef<(HTMLButtonElement | null)[]>([]);
38
+ const openerOf = useCallback((index: number) => openers.current[index] ?? null, []);
26
39
  // an image already loaded when the page hydrates fires no load event of its own
27
40
  const measure = useCallback((url: string, image: HTMLImageElement | null) => {
28
41
  if (!image || !image.complete || !image.naturalHeight) return;
@@ -31,24 +44,51 @@ export const StructuredImage: FC<StructuredBlockItemProps<ImageStructuredBlock>>
31
44
  }, []);
32
45
  // growth factors summing to less than one leave part of the row empty, so a lone portrait image
33
46
  // would fill only its ratio of the block: each image grows by its share of the total instead
34
- const totalRatio = urls.reduce((sum, url) => sum + (ratios[url] ?? 1), 0);
47
+ const totalRatio = pictures.reduce((sum, { url }) => sum + (ratios[url] ?? 1), 0);
35
48
  const layoutValues: Record<string, any>[] = [block.layoutParams];
49
+ const images = pictures.map(({ url, altText }, index) => {
50
+ const flexGrow = (ratios[url] ?? 1) / totalRatio;
51
+ const image = (
52
+ <img
53
+ key={`${url}-${index}`}
54
+ ref={image => measure(url, image)}
55
+ className={`structured-gallery-image-${block.id}`}
56
+ src={url}
57
+ alt={altText}
58
+ onLoad={event => measure(url, event.currentTarget)}
59
+ style={hasLightbox ? undefined : { flexGrow }}
60
+ />
61
+ );
62
+ if (!hasLightbox) return image;
63
+ return (
64
+ <button
65
+ key={`${url}-${index}`}
66
+ ref={(button) => {
67
+ openers.current[index] = button;
68
+ }}
69
+ type="button"
70
+ className={`structured-gallery-open-${block.id}`}
71
+ aria-label={`Open image ${index + 1} of ${pictures.length}`}
72
+ disabled={!opensLightbox}
73
+ style={{ flexGrow }}
74
+ onClick={() => setOpenIndex(index)}
75
+ >
76
+ {image}
77
+ </button>
78
+ );
79
+ });
36
80
  return (
37
81
  <div ref={setRef} className={`structured-gallery-${block.id}`}>
38
- <div className={`structured-gallery-row-${block.id}`}>
39
- {urls.map((url, index) => (
40
- <img
41
- key={`${url}-${index}`}
42
- ref={image => measure(url, image)}
43
- className={`structured-gallery-image-${block.id}`}
44
- src={url}
45
- alt={altText}
46
- onLoad={event => measure(url, event.currentTarget)}
47
- style={{ flexGrow: (ratios[url] ?? 1) / totalRatio }}
48
- />
49
- ))}
50
- </div>
82
+ <div className={`structured-gallery-row-${block.id}`}>{images}</div>
51
83
  {caption && <BlockCaption blockId={block.id} caption={caption} layoutParams={block.layoutParams} readingWidth={readingWidth} />}
84
+ {opensLightbox && openIndex !== null && (
85
+ <ImageLightbox
86
+ images={pictures.map(({ url, altText }) => ({ src: url, alt: altText }))}
87
+ initialIndex={openIndex}
88
+ onClose={() => setOpenIndex(null)}
89
+ originOf={openerOf}
90
+ />
91
+ )}
52
92
  <JSXStyle id={`${reactId}-gallery-${block.id}`}>{`
53
93
  .structured-gallery-row-${block.id} {
54
94
  display: flex;
@@ -63,6 +103,38 @@ export const StructuredImage: FC<StructuredBlockItemProps<ImageStructuredBlock>>
63
103
  min-width: 0;
64
104
  height: auto;
65
105
  }
106
+ ${hasLightbox ? `
107
+ .structured-gallery-open-${block.id} {
108
+ display: block;
109
+ flex-shrink: 1;
110
+ flex-basis: 0;
111
+ min-width: 0;
112
+ margin: 0;
113
+ padding: 0;
114
+ border: 0;
115
+ border-radius: 0;
116
+ background: none;
117
+ appearance: none;
118
+ overflow: hidden;
119
+ cursor: pointer;
120
+ }
121
+ .structured-gallery-open-${block.id}:disabled {
122
+ cursor: default;
123
+ }
124
+ .structured-gallery-open-${block.id}:focus-visible {
125
+ outline: 2px solid currentColor;
126
+ outline-offset: 2px;
127
+ }
128
+ .structured-gallery-open-${block.id} > .structured-gallery-image-${block.id} {
129
+ width: 100%;
130
+ transition: transform 300ms ease;
131
+ }
132
+ @media (hover: hover) {
133
+ .structured-gallery-open-${block.id}:not(:disabled):hover > .structured-gallery-image-${block.id} {
134
+ transform: scale(${HOVER_ZOOM});
135
+ }
136
+ }
137
+ ` : ''}
66
138
  ${getLayoutStyles(layouts, layoutValues, ([layoutParams], exemplary) => (`
67
139
  .structured-gallery-${block.id} {
68
140
  --gallery-gap: ${GALLERY_GAP_PX / exemplary * 100}vw;
@@ -9,6 +9,13 @@ import { StructuredContent } from './StructuredContent';
9
9
 
10
10
  // the styles each component writes, drawn where it is for the test to read them
11
11
  jest.mock('styled-jsx/style', () => ({ __esModule: true, default: ({ children }: { children: string | string[] }) => <style>{children}</style> }));
12
+ jest.mock('../ImageLightbox/ImageLightbox', () => ({
13
+ ImageLightbox: ({ images, initialIndex, onClose }: any) => (
14
+ <div data-testid="lightbox" data-index={initialIndex} data-images={images.map((image: any) => image.src).join(' ')} data-alt={images.map((image: any) => image.alt).join(' | ')}>
15
+ <button type="button" onClick={onClose}>close</button>
16
+ </div>
17
+ )
18
+ }));
12
19
  jest.mock('@vimeo/player', () => jest.fn().mockImplementation(() => ({ on: jest.fn(), off: jest.fn(), play: jest.fn(), pause: jest.fn() })));
13
20
 
14
21
  const layouts: Layout[] = [
@@ -71,9 +78,9 @@ const date = block(StructuredBlockType.Date, 'date', { ...paragraph('23 Sep 2026
71
78
  ...textStyles,
72
79
  rangeStyles: [{ start: 3, end: 6, style: 'FONTWEIGHT', value: '700' }]
73
80
  });
81
+ const pictures = (urls: string[], altText = '') => urls.map(url => ({ url, altText }));
74
82
  const gallery = block(StructuredBlockType.Image, 'gallery', {
75
- urls: ['https://cdn.cntrl.site/a.jpg', 'https://cdn.cntrl.site/b.jpg'],
76
- altText: 'Two views',
83
+ images: pictures(['https://cdn.cntrl.site/a.jpg', 'https://cdn.cntrl.site/b.jpg'], 'Two views'),
77
84
  caption: 'Seen from the hill'
78
85
  }, { opacity: 0.8, captionStyles: { ...textStyles, fontSize: 0.01, maxWidth: 0.45, innerPaddingTop: 0.02, innerPaddingBottom: 0.01 } });
79
86
  const video = block(StructuredBlockType.Video, 'video', { url: 'https://cdn.cntrl.site/clip.mp4', coverUrl: 'https://cdn.cntrl.site/cover.jpg' }, {
@@ -227,9 +234,55 @@ describe('StructuredContent', () => {
227
234
  expect(css()).toMatch(/\.structured-caption-gallery \{[^}]*width: min\(45vw, 100%\);[^}]*padding-top: 2vw;[^}]*padding-bottom: 1vw;/);
228
235
  });
229
236
 
237
+ it('leaves a gallery\'s images as they are while its lightbox is off', () => {
238
+ const { container } = draw(section(false));
239
+ expect(container.querySelector('.structured-gallery-row-gallery button')).toBeNull();
240
+ expect(css()).not.toMatch(/structured-gallery-open-/);
241
+ });
242
+
243
+ it('opens a gallery with its lightbox on at the image clicked, on its own images only', () => {
244
+ const withLightbox = { ...gallery, id: 'open', layoutParams: { ...gallery.layoutParams, desktop: { ...gallery.layoutParams.desktop, lightbox: true } } };
245
+ const { container, getByTestId, queryByTestId } = draw({ ...section(false), structuredContent: [gallery, withLightbox] } as Section);
246
+ const buttons = [...container.querySelectorAll<HTMLButtonElement>('.structured-gallery-row-open > button')];
247
+ expect(buttons.map(button => button.getAttribute('aria-label'))).toEqual(['Open image 1 of 2', 'Open image 2 of 2']);
248
+ expect(buttons.map(button => button.disabled)).toEqual([false, false]);
249
+ // the button takes the image's place in the row, and the image fills it
250
+ expect(buttons.map(button => button.style.flexGrow)).toEqual(['0.5', '0.5']);
251
+ expect(buttons.map(button => button.querySelector('img')!.style.flexGrow)).toEqual(['', '']);
252
+ expect(queryByTestId('lightbox')).toBeNull();
253
+
254
+ fireEvent.click(buttons[1]);
255
+ const lightbox = getByTestId('lightbox');
256
+ expect(lightbox.dataset).toMatchObject({
257
+ index: '1',
258
+ images: 'https://cdn.cntrl.site/a.jpg https://cdn.cntrl.site/b.jpg',
259
+ alt: 'Two views | Two views'
260
+ });
261
+
262
+ fireEvent.click(lightbox.querySelector('button')!);
263
+ expect(queryByTestId('lightbox')).toBeNull();
264
+ });
265
+
266
+ it('opens nothing on a layout where the gallery\'s size has no lightbox, its images kept as they are drawn', () => {
267
+ const onMobileOnly = { ...gallery, id: 'open', layoutParams: { ...gallery.layoutParams, mobile: { ...gallery.layoutParams.mobile, lightbox: true } } };
268
+ const { container, queryByTestId } = draw({ ...section(false), structuredContent: [onMobileOnly] } as Section);
269
+ const buttons = [...container.querySelectorAll<HTMLButtonElement>('.structured-gallery-row-open > button')];
270
+ expect(buttons.map(button => button.disabled)).toEqual([true, true]);
271
+ fireEvent.click(buttons[0]);
272
+ expect(queryByTestId('lightbox')).toBeNull();
273
+ expect(css()).toMatch(/\.structured-gallery-open-open:disabled \{\s*cursor: default;/);
274
+ });
275
+
276
+ it('zooms an image of a lightbox gallery under the pointer, within its place in the row', () => {
277
+ const withLightbox = { ...gallery, id: 'open', layoutParams: { ...gallery.layoutParams, desktop: { ...gallery.layoutParams.desktop, lightbox: true } } };
278
+ draw({ ...section(false), structuredContent: [withLightbox] } as Section);
279
+ expect(css()).toMatch(/\.structured-gallery-open-open \{[^}]*overflow: hidden;/);
280
+ expect(css()).toMatch(/@media \(hover: hover\) \{\s*\.structured-gallery-open-open:not\(:disabled\):hover > \.structured-gallery-image-open \{\s*transform: scale\(1\.03\);/);
281
+ });
282
+
230
283
  it('draws no caption an image has switched off, nor one that says nothing', () => {
231
- const switchedOff = block(StructuredBlockType.Image, 'off', { urls: ['https://cdn.cntrl.site/a.jpg'], altText: '', caption: 'Kept for later', showCaption: false }, { opacity: 1 });
232
- const blank = block(StructuredBlockType.Image, 'blank', { urls: ['https://cdn.cntrl.site/b.jpg'], altText: '', caption: ' ' }, { opacity: 1 });
284
+ const switchedOff = block(StructuredBlockType.Image, 'off', { images: pictures(['https://cdn.cntrl.site/a.jpg']), caption: 'Kept for later', showCaption: false }, { opacity: 1 });
285
+ const blank = block(StructuredBlockType.Image, 'blank', { images: pictures(['https://cdn.cntrl.site/b.jpg']), caption: ' ' }, { opacity: 1 });
233
286
  const keyImage = { ...headerImage, commonParams: { ...headerImage.commonParams, showCaption: false } };
234
287
  const { container } = draw({ ...section(false), structuredContent: [switchedOff, blank, keyImage] } as Section);
235
288
  expect(container.querySelector('.structured-caption-off')).toBeNull();
@@ -240,7 +293,7 @@ describe('StructuredContent', () => {
240
293
  });
241
294
 
242
295
  it('fills a gallery\'s row whatever its images\' proportions, a lone portrait image as wide as the block', () => {
243
- const portrait = block(StructuredBlockType.Image, 'portrait', { urls: ['https://cdn.cntrl.site/p.jpg'], altText: '', caption: '' }, { opacity: 1 });
296
+ const portrait = block(StructuredBlockType.Image, 'portrait', { images: pictures(['https://cdn.cntrl.site/p.jpg']), caption: '' }, { opacity: 1 });
244
297
  const { container } = draw({ ...section(false), structuredContent: [portrait] } as Section);
245
298
  const image = container.querySelector<HTMLImageElement>('.structured-gallery-image-portrait')!;
246
299
  Object.defineProperties(image, { complete: { value: true }, naturalWidth: { value: 300 }, naturalHeight: { value: 400 } });
@@ -360,9 +413,26 @@ describe('StructuredContent', () => {
360
413
  expect(css()).toMatch(/\.structured-text-plain \{[^}]*column-count: auto; column-gap: normal;/);
361
414
  });
362
415
 
416
+ it('gives each image of a gallery its own alt text, in the row and in the lightbox, an unresolved image\'s going with it', () => {
417
+ const described = block(StructuredBlockType.Image, 'described', {
418
+ images: [
419
+ { url: 'https://cdn.cntrl.site/a.jpg', altText: 'A hand' },
420
+ { url: '', altText: 'Never drawn' },
421
+ { url: 'https://cdn.cntrl.site/c.jpg', altText: 'A vase' }
422
+ ]
423
+ }, { opacity: 1, lightbox: true });
424
+ const { container, getByTestId } = draw({ ...section(false), structuredContent: [gallery, described] } as Section);
425
+ const alts = (id: string) => [...container.querySelectorAll<HTMLImageElement>(`.structured-gallery-image-${id}`)].map(image => image.alt);
426
+ expect(alts('described')).toEqual(['A hand', 'A vase']);
427
+ expect(alts('gallery')).toEqual(['Two views', 'Two views']);
428
+
429
+ fireEvent.click(container.querySelector('.structured-gallery-open-described')!);
430
+ expect(getByTestId('lightbox').dataset.alt).toBe('A hand | A vase');
431
+ });
432
+
363
433
  it('skips a block of a type it does not know, and an image the API could not resolve', () => {
364
434
  const later = { ...code, id: 'later', type: 'chart-block' };
365
- const missing = block(StructuredBlockType.Image, 'missing', { urls: ['https://cdn.cntrl.site/a.jpg', ''], altText: '' }, { opacity: 1 });
435
+ const missing = block(StructuredBlockType.Image, 'missing', { images: pictures(['https://cdn.cntrl.site/a.jpg', '']) }, { opacity: 1 });
366
436
  const { container } = draw({ ...section(false), structuredContent: [text, later, missing] } as Section);
367
437
  const skipped = container.querySelector('.structured-block-item-later')!;
368
438
  expect([...skipped.children].filter(child => child.tagName !== 'STYLE')).toHaveLength(0);