@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.
@@ -10,23 +10,37 @@ const react_1 = require("react");
10
10
  const style_1 = __importDefault(require("styled-jsx/style"));
11
11
  const useCntrlContext_1 = require("../../../provider/useCntrlContext");
12
12
  const useItemGeometry_1 = require("../../../ItemGeometry/useItemGeometry");
13
+ const ImageLightbox_1 = require("../../ImageLightbox/ImageLightbox");
14
+ const useLayoutContext_1 = require("../../useLayoutContext");
13
15
  const BlockCaption_1 = require("../BlockCaption/BlockCaption");
14
16
  const GALLERY_GAP_PX = 8;
17
+ const HOVER_ZOOM = 1.03;
15
18
  /**
16
19
  * A gallery: its images side by side in one row, each growing from nothing by its share of the row's
17
20
  * aspect ratios, so that they fill the row as their ratios do and come out equally tall, with the
18
- * caption under them. Until an image has loaded its ratio is taken to be square.
21
+ * caption under them. Until an image has loaded its ratio is taken to be square. A gallery that opens
22
+ * in a lightbox on some layout makes each image a button, live on the layouts it does: there it opens
23
+ * the image full screen, to step through the gallery's own images, and the image zooms a little under
24
+ * the pointer, within its place in the row, to say so. The image opened moves out of its place in the
25
+ * row into the lightbox, and the one shown when the lightbox closes moves back into its own.
19
26
  */
20
27
  const StructuredImage = ({ block, readingWidth }) => {
28
+ var _a;
21
29
  const reactId = (0, react_1.useId)();
22
30
  const { layouts } = (0, useCntrlContext_1.useCntrlContext)();
23
31
  const [ref, setRef] = (0, react_1.useState)(null);
24
32
  (0, useItemGeometry_1.useItemGeometry)(block.id, ref);
25
- const { altText } = block.commonParams;
33
+ const layoutId = (0, useLayoutContext_1.useLayoutContext)();
34
+ const hasLightbox = Object.values(block.layoutParams).some(params => params.lightbox);
35
+ // the layout is known once the page is on screen: until then the images open nothing
36
+ const opensLightbox = layoutId !== undefined && Boolean((_a = block.layoutParams[layoutId]) === null || _a === void 0 ? void 0 : _a.lightbox);
26
37
  // a file the API could not resolve comes as an empty url: nothing to draw for it
27
- const urls = block.commonParams.urls.filter(url => url !== '');
38
+ const pictures = block.commonParams.images.filter(({ url }) => url !== '');
28
39
  const caption = (0, sdk_1.getShownCaption)(block.commonParams);
29
40
  const [ratios, setRatios] = (0, react_1.useState)({});
41
+ const [openIndex, setOpenIndex] = (0, react_1.useState)(null);
42
+ const openers = (0, react_1.useRef)([]);
43
+ const openerOf = (0, react_1.useCallback)((index) => { var _a; return (_a = openers.current[index]) !== null && _a !== void 0 ? _a : null; }, []);
30
44
  // an image already loaded when the page hydrates fires no load event of its own
31
45
  const measure = (0, react_1.useCallback)((url, image) => {
32
46
  if (!image || !image.complete || !image.naturalHeight)
@@ -36,12 +50,19 @@ const StructuredImage = ({ block, readingWidth }) => {
36
50
  }, []);
37
51
  // growth factors summing to less than one leave part of the row empty, so a lone portrait image
38
52
  // would fill only its ratio of the block: each image grows by its share of the total instead
39
- const totalRatio = urls.reduce((sum, url) => { var _a; return sum + ((_a = ratios[url]) !== null && _a !== void 0 ? _a : 1); }, 0);
53
+ const totalRatio = pictures.reduce((sum, { url }) => { var _a; return sum + ((_a = ratios[url]) !== null && _a !== void 0 ? _a : 1); }, 0);
40
54
  const layoutValues = [block.layoutParams];
41
- return ((0, jsx_runtime_1.jsxs)("div", { ref: setRef, className: `structured-gallery-${block.id}`, children: [(0, jsx_runtime_1.jsx)("div", { className: `structured-gallery-row-${block.id}`, children: urls.map((url, index) => {
42
- var _a;
43
- return ((0, jsx_runtime_1.jsx)("img", { ref: image => measure(url, image), className: `structured-gallery-image-${block.id}`, src: url, alt: altText, onLoad: event => measure(url, event.currentTarget), style: { flexGrow: ((_a = ratios[url]) !== null && _a !== void 0 ? _a : 1) / totalRatio } }, `${url}-${index}`));
44
- }) }), caption && (0, jsx_runtime_1.jsx)(BlockCaption_1.BlockCaption, { blockId: block.id, caption: caption, layoutParams: block.layoutParams, readingWidth: readingWidth }), (0, jsx_runtime_1.jsx)(style_1.default, { id: `${reactId}-gallery-${block.id}`, children: `
55
+ const images = pictures.map(({ url, altText }, index) => {
56
+ var _a;
57
+ const flexGrow = ((_a = ratios[url]) !== null && _a !== void 0 ? _a : 1) / totalRatio;
58
+ const image = ((0, jsx_runtime_1.jsx)("img", { ref: image => measure(url, image), className: `structured-gallery-image-${block.id}`, src: url, alt: altText, onLoad: event => measure(url, event.currentTarget), style: hasLightbox ? undefined : { flexGrow } }, `${url}-${index}`));
59
+ if (!hasLightbox)
60
+ return image;
61
+ return ((0, jsx_runtime_1.jsx)("button", { ref: (button) => {
62
+ openers.current[index] = button;
63
+ }, type: "button", className: `structured-gallery-open-${block.id}`, "aria-label": `Open image ${index + 1} of ${pictures.length}`, disabled: !opensLightbox, style: { flexGrow }, onClick: () => setOpenIndex(index), children: image }, `${url}-${index}`));
64
+ });
65
+ return ((0, jsx_runtime_1.jsxs)("div", { ref: setRef, className: `structured-gallery-${block.id}`, children: [(0, jsx_runtime_1.jsx)("div", { className: `structured-gallery-row-${block.id}`, children: images }), caption && (0, jsx_runtime_1.jsx)(BlockCaption_1.BlockCaption, { blockId: block.id, caption: caption, layoutParams: block.layoutParams, readingWidth: readingWidth }), opensLightbox && openIndex !== null && ((0, jsx_runtime_1.jsx)(ImageLightbox_1.ImageLightbox, { images: pictures.map(({ url, altText }) => ({ src: url, alt: altText })), initialIndex: openIndex, onClose: () => setOpenIndex(null), originOf: openerOf })), (0, jsx_runtime_1.jsx)(style_1.default, { id: `${reactId}-gallery-${block.id}`, children: `
45
66
  .structured-gallery-row-${block.id} {
46
67
  display: flex;
47
68
  align-items: flex-start;
@@ -55,6 +76,38 @@ const StructuredImage = ({ block, readingWidth }) => {
55
76
  min-width: 0;
56
77
  height: auto;
57
78
  }
79
+ ${hasLightbox ? `
80
+ .structured-gallery-open-${block.id} {
81
+ display: block;
82
+ flex-shrink: 1;
83
+ flex-basis: 0;
84
+ min-width: 0;
85
+ margin: 0;
86
+ padding: 0;
87
+ border: 0;
88
+ border-radius: 0;
89
+ background: none;
90
+ appearance: none;
91
+ overflow: hidden;
92
+ cursor: pointer;
93
+ }
94
+ .structured-gallery-open-${block.id}:disabled {
95
+ cursor: default;
96
+ }
97
+ .structured-gallery-open-${block.id}:focus-visible {
98
+ outline: 2px solid currentColor;
99
+ outline-offset: 2px;
100
+ }
101
+ .structured-gallery-open-${block.id} > .structured-gallery-image-${block.id} {
102
+ width: 100%;
103
+ transition: transform 300ms ease;
104
+ }
105
+ @media (hover: hover) {
106
+ .structured-gallery-open-${block.id}:not(:disabled):hover > .structured-gallery-image-${block.id} {
107
+ transform: scale(${HOVER_ZOOM});
108
+ }
109
+ }
110
+ ` : ''}
58
111
  ${(0, sdk_1.getLayoutStyles)(layouts, layoutValues, ([layoutParams], exemplary) => (`
59
112
  .structured-gallery-${block.id} {
60
113
  --gallery-gap: ${GALLERY_GAP_PX / exemplary * 100}vw;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cntrl-site/sdk-nextjs",
3
- "version": "1.11.17",
3
+ "version": "1.11.18",
4
4
  "description": "SDK for Next.js",
5
5
  "author": "arsen@momdesign.nyc",
6
6
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  "@cntrl-site/color": "^1.0.0",
33
33
  "@cntrl-site/components": "^1.0.117",
34
34
  "@cntrl-site/effects": "^1.4.2",
35
- "@cntrl-site/sdk": "^1.29.13",
35
+ "@cntrl-site/sdk": "^1.29.14",
36
36
  "@types/vimeo__player": "^2.18.0",
37
37
  "@vimeo/player": "^2.25.0",
38
38
  "franc-min": "^5.0.0",
@@ -0,0 +1,203 @@
1
+ import { act, fireEvent, render } from '@testing-library/react';
2
+ import { Layout } from '@cntrl-site/sdk';
3
+ import { CntrlContext } from '../../provider/CntrlContext';
4
+ import { CntrlSdkContext } from '../../provider/CntrlSdkContext';
5
+ import { CustomItemRegistry } from '../../provider/CustomItemRegistry';
6
+ import { CustomSectionRegistry } from '../../provider/CustomSectionRegistry';
7
+ import { ImageLightbox, LightboxImage } from './ImageLightbox';
8
+
9
+ // the styles the lightbox writes, drawn where it is for the test to read them
10
+ jest.mock('styled-jsx/style', () => ({ __esModule: true, default: ({ children }: { children: string | string[] }) => <style>{children}</style> }));
11
+
12
+ const IMAGES: LightboxImage[] = [
13
+ { src: 'https://cdn.cntrl.site/a.jpg', alt: 'A' },
14
+ { src: 'https://cdn.cntrl.site/b.jpg', alt: 'B' },
15
+ { src: 'https://cdn.cntrl.site/c.jpg', alt: 'C' }
16
+ ];
17
+
18
+ const LAYOUTS: Layout[] = [
19
+ { id: 'd', title: 'Desktop', startsWith: 1024, exemplary: 1440 },
20
+ { id: 't', title: 'Tablet', startsWith: 768, exemplary: 768 },
21
+ { id: 'm', title: 'Mobile', startsWith: 0, exemplary: 375 }
22
+ ];
23
+
24
+ const FADE_MS = 500;
25
+
26
+ function open(props: Partial<Parameters<typeof ImageLightbox>[0]> = {}, layouts = LAYOUTS) {
27
+ const sdk = new CntrlSdkContext(new CustomItemRegistry(), new CustomSectionRegistry());
28
+ sdk.setLayouts(layouts);
29
+ return render(
30
+ <CntrlContext.Provider value={sdk}>
31
+ <ImageLightbox images={IMAGES} initialIndex={0} onClose={() => {}} {...props} />
32
+ </CntrlContext.Provider>
33
+ );
34
+ }
35
+
36
+ const lightbox = () => document.querySelector<HTMLElement>('.image-lightbox');
37
+ const shown = () => lightbox()?.querySelector('img')?.getAttribute('src');
38
+ const stepZone = (side: 'prev' | 'next') => lightbox()!.querySelector<HTMLElement>(`[data-step="${side}"]`);
39
+ const css = () => [...document.querySelectorAll('style')].map(style => style.textContent).join('\n');
40
+
41
+ function step(side: 'prev' | 'next') {
42
+ fireEvent.click(stepZone(side)!);
43
+ act(() => { jest.advanceTimersByTime(1000); });
44
+ }
45
+
46
+ beforeEach(() => {
47
+ jest.useFakeTimers();
48
+ (globalThis as any).ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };
49
+ jest.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({
50
+ top: 0, left: 0, width: 1000, height: 800, right: 1000, bottom: 800, x: 0, y: 0, toJSON: () => ({})
51
+ });
52
+ });
53
+
54
+ afterEach(() => {
55
+ document.getElementById('component-portal')?.remove();
56
+ jest.restoreAllMocks();
57
+ jest.useRealTimers();
58
+ });
59
+
60
+ describe('ImageLightbox', () => {
61
+ it('renders into the page\'s portal for what covers the page', () => {
62
+ const portal = document.createElement('div');
63
+ portal.id = 'component-portal';
64
+ document.body.appendChild(portal);
65
+ open();
66
+ expect(portal.contains(lightbox())).toBe(true);
67
+ });
68
+
69
+ it('renders into the body on a page without that portal', () => {
70
+ open();
71
+ expect(lightbox()?.parentElement).toBe(document.body);
72
+ });
73
+
74
+ it('opens on the image it is told to', () => {
75
+ open({ initialIndex: 1 });
76
+ expect(shown()).toBe('https://cdn.cntrl.site/b.jpg');
77
+ expect(lightbox()!.querySelector('img')!.alt).toBe('B');
78
+ });
79
+
80
+ it('steps forward around from the last image to the first', () => {
81
+ open({ initialIndex: 1 });
82
+ step('next');
83
+ expect(shown()).toBe('https://cdn.cntrl.site/c.jpg');
84
+ step('next');
85
+ expect(shown()).toBe('https://cdn.cntrl.site/a.jpg');
86
+ });
87
+
88
+ it('steps back around from the first image to the last', () => {
89
+ open();
90
+ step('prev');
91
+ expect(shown()).toBe('https://cdn.cntrl.site/c.jpg');
92
+ });
93
+
94
+ it('has nowhere to step with a single image', () => {
95
+ open({ images: IMAGES.slice(0, 1) });
96
+ expect(shown()).toBe('https://cdn.cntrl.site/a.jpg');
97
+ expect(stepZone('next')).toBeNull();
98
+ expect(stepZone('prev')).toBeNull();
99
+ });
100
+
101
+ it.each([
102
+ ['Escape', () => fireEvent.keyDown(window, { key: 'Escape' })],
103
+ ['a click on the backdrop', () => fireEvent.click(lightbox()!)],
104
+ ['the close icon', () => fireEvent.click(document.querySelector('button[aria-label="Close"]')!)]
105
+ ])('closes on %s once it has faded out', (_name, close) => {
106
+ const onClose = jest.fn();
107
+ open({ onClose });
108
+ close();
109
+ expect(onClose).not.toHaveBeenCalled();
110
+ act(() => { jest.advanceTimersByTime(FADE_MS); });
111
+ expect(onClose).toHaveBeenCalledTimes(1);
112
+ });
113
+
114
+ it('holds the page still while it is up', () => {
115
+ document.body.style.overflow = 'auto';
116
+ const { unmount } = open();
117
+ expect(document.body.style.overflow).toBe('hidden');
118
+ unmount();
119
+ expect(document.body.style.overflow).toBe('auto');
120
+ document.body.style.overflow = '';
121
+ });
122
+
123
+ describe('told where its images are on the page', () => {
124
+ // the mocked screen fits a 2:1 image at 0,150 1000x500; each origin is a tenth of that size
125
+ const origins = IMAGES.map((_, index) => {
126
+ const origin = document.createElement('button');
127
+ const picture = document.createElement('img');
128
+ Object.defineProperty(picture, 'naturalWidth', { value: 200 });
129
+ Object.defineProperty(picture, 'naturalHeight', { value: 100 });
130
+ origin.append(picture);
131
+ const place = { top: 200, left: 100 + index * 110, width: 100, height: 50 };
132
+ origin.getBoundingClientRect = () => place as DOMRect;
133
+ return origin;
134
+ });
135
+ const originOf = (index: number) => origins[index] ?? null;
136
+ const picture = () => lightbox()!.querySelector('img')!;
137
+ const frames = (count: number) => act(() => {
138
+ jest.advanceTimersByTime(count * 16);
139
+ });
140
+
141
+ it('opens the image out of its place, which keeps its own image, and never fades it', () => {
142
+ open({ originOf, initialIndex: 1 });
143
+ expect(picture().style.transform).toBe('translate(210px, 50px) scale(0.1, 0.1)');
144
+ expect(picture().style.transition).toBe('none');
145
+ expect(picture().parentElement!.style.opacity).toBe('1');
146
+ expect(origins.map(origin => origin.style.opacity)).toEqual(['', '', '']);
147
+
148
+ frames(3);
149
+ expect(origins.map(origin => origin.style.opacity)).toEqual(['', '', '']);
150
+ expect(picture().style.transform).toBe('');
151
+ expect(picture().style.transition).toContain('transform');
152
+ expect(picture().parentElement!.style.opacity).toBe('1');
153
+ });
154
+
155
+ it('closes the image shown back into its own place', () => {
156
+ const onClose = jest.fn();
157
+ open({ originOf, onClose });
158
+ frames(3);
159
+ step('next');
160
+
161
+ fireEvent.keyDown(window, { key: 'Escape' });
162
+ // not yet loaded, the second image is fitted to the whole screen: 1000x800 at 0,0
163
+ expect(picture().style.transform).toBe('translate(210px, 200px) scale(0.1, 0.0625)');
164
+ expect(picture().parentElement!.style.opacity).toBe('1');
165
+ expect(onClose).not.toHaveBeenCalled();
166
+
167
+ act(() => {
168
+ jest.advanceTimersByTime(FADE_MS);
169
+ });
170
+ expect(onClose).toHaveBeenCalledTimes(1);
171
+ });
172
+
173
+ it('fades as it does without them for a reader who asked for less motion', () => {
174
+ window.matchMedia = jest.fn().mockReturnValue({ matches: true });
175
+ open({ originOf });
176
+ expect(picture().style.transform).toBe('');
177
+ fireEvent.keyDown(window, { key: 'Escape' });
178
+ expect(picture().parentElement!.style.opacity).toBe('0');
179
+ delete (window as { matchMedia?: unknown }).matchMedia;
180
+ });
181
+
182
+ it('fades out an image that has no place on the page', () => {
183
+ open({ originOf: index => (index === 0 ? origins[0] : null) });
184
+ frames(3);
185
+ step('next');
186
+ fireEvent.keyDown(window, { key: 'Escape' });
187
+ expect(picture().style.transform).toBe('');
188
+ expect(picture().parentElement!.style.opacity).toBe('0');
189
+ });
190
+ });
191
+
192
+ it('sizes its close icon for each layout, larger on the narrower ones', () => {
193
+ open();
194
+ expect(css()).toMatch(/\.image-lightbox-close \{\s*width: 8\.1vw;/);
195
+ expect(css()).toMatch(/@media \(min-width: 768px\) \{\s*\.image-lightbox-close-row \{\s*height: 2\.6vw;\s*\}\s*\.image-lightbox-close \{\s*width: 3\.90\d+vw;/);
196
+ expect(css()).toMatch(/@media \(min-width: 1024px\) \{\s*\.image-lightbox-close-row \{\s*height: 1vw;\s*\}\s*\.image-lightbox-close \{\s*width: 1\.25vw;/);
197
+ });
198
+
199
+ it('sizes its close icon as on the desktop on a layout a project has added', () => {
200
+ open({}, [{ id: 'wide', title: 'Wide', startsWith: 0, exemplary: 1920 }]);
201
+ expect(css()).toMatch(/\.image-lightbox-close \{\s*width: 1\.25vw;/);
202
+ });
203
+ });