@cntrl-site/sdk-nextjs 1.11.13 → 1.11.15

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.
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useScrollFade = exports.scrollFadeProgress = exports.SCROLL_FADE_ZOOM = exports.SCROLL_FADE_PROPERTY = void 0;
4
+ const react_1 = require("react");
5
+ // the share of an element left on the screen as it leaves the top at which it starts to fade: all
6
+ // of it, so it fades from the first pixel scrolled, as the editor draws it
7
+ const FADE_START = 1;
8
+ /** The property `useScrollFade` writes the fade to, from 0 to 1, for the element's styles to draw it. */
9
+ exports.SCROLL_FADE_PROPERTY = '--cntrl-scroll-fade';
10
+ /** How much larger a fading element is drawn once it has faded all the way. */
11
+ exports.SCROLL_FADE_ZOOM = 0.15;
12
+ /**
13
+ * How far an element leaving the screen's top has faded: nothing while all of it is on the screen,
14
+ * as much as has left it as it scrolls off, all of it once it is gone. An element taller than the
15
+ * screen counts the screen it fills instead, so it fades once its bottom is on the screen, over a
16
+ * screen's height of scrolling. An element yet to reach the screen's top, or entering from below,
17
+ * has not faded.
18
+ */
19
+ function scrollFadeProgress(top, bottom, screenHeight) {
20
+ const full = Math.min(bottom - top, screenHeight);
21
+ if (full <= 0)
22
+ return 0;
23
+ const left = bottom / full;
24
+ return Math.min(Math.max(1 - left / FADE_START, 0), 1);
25
+ }
26
+ exports.scrollFadeProgress = scrollFadeProgress;
27
+ /**
28
+ * Writes to the element how far it has faded leaving the screen, as the page scrolls or the element
29
+ * resizes, while enabled; nothing is drawn here, the element's styles draw the fade. Until it runs,
30
+ * as the page is first drawn, the element is unfaded.
31
+ */
32
+ function useScrollFade(element, isEnabled) {
33
+ (0, react_1.useEffect)(() => {
34
+ if (!element || !isEnabled)
35
+ return;
36
+ let frame = 0;
37
+ const update = () => {
38
+ frame = 0;
39
+ const { top, bottom } = element.getBoundingClientRect();
40
+ element.style.setProperty(exports.SCROLL_FADE_PROPERTY, String(scrollFadeProgress(top, bottom, window.innerHeight)));
41
+ };
42
+ const schedule = () => {
43
+ if (!frame)
44
+ frame = requestAnimationFrame(update);
45
+ };
46
+ update();
47
+ window.addEventListener('scroll', schedule, { passive: true });
48
+ window.addEventListener('resize', schedule);
49
+ const observer = new ResizeObserver(schedule);
50
+ observer.observe(element);
51
+ return () => {
52
+ cancelAnimationFrame(frame);
53
+ window.removeEventListener('scroll', schedule);
54
+ window.removeEventListener('resize', schedule);
55
+ observer.disconnect();
56
+ element.style.removeProperty(exports.SCROLL_FADE_PROPERTY);
57
+ };
58
+ }, [element, isEnabled]);
59
+ }
60
+ exports.useScrollFade = useScrollFade;
@@ -43,7 +43,7 @@ exports.textColumnsRule = textColumnsRule;
43
43
  /**
44
44
  * The box a quote's text or a table is drawn in, as a CSS rule for `selector`: padded inside, its
45
45
  * sides grown out past the columns the block is placed on by as much as they pad it, so what it
46
- * holds stays on them; rounded, and filled where it has a fill.
46
+ * holds stays on them; rounded, turned, and filled where it has a fill.
47
47
  */
48
48
  function boxRule(selector, box) {
49
49
  return `
@@ -51,6 +51,7 @@ function boxRule(selector, box) {
51
51
  padding: ${[box.boxPaddingTop, box.boxPaddingRight, box.boxPaddingBottom, box.boxPaddingLeft].map(vw_1.vw).join(' ')};
52
52
  margin: 0 -${(0, vw_1.vw)(box.boxPaddingRight)} 0 -${(0, vw_1.vw)(box.boxPaddingLeft)};
53
53
  border-radius: ${(0, vw_1.vw)(box.boxRadius)};
54
+ rotate: ${box.boxRotation ? `${box.boxRotation}deg` : 'none'};
54
55
  background-color: transparent;
55
56
  }
56
57
  ${box.boxBackground ? colorRule(selector, 'background-color', box.boxBackground) : ''}
@@ -9,7 +9,9 @@ const sdk_1 = require("@cntrl-site/sdk");
9
9
  const react_1 = require("react");
10
10
  const style_1 = __importDefault(require("styled-jsx/style"));
11
11
  const useCntrlContext_1 = require("../../provider/useCntrlContext");
12
+ const useScrollFade_1 = require("../../common/useScrollFade");
12
13
  const blockPlacement_1 = require("../StructuredBlockItem/blockPlacement");
14
+ const textStylesRule_1 = require("../StructuredBlockItem/textStylesRule");
13
15
  const blocksMap_1 = require("../StructuredBlockItem/blocksMap");
14
16
  const TEXT_KINDS = ['title', 'subtitle', 'date'];
15
17
  // an element a header stored before its kind was ordered goes last, not first
@@ -20,9 +22,11 @@ function orderOf(order, kind) {
20
22
  /**
21
23
  * A content-based section's header, drawn first. Variant A draws the key image full width with the
22
24
  * other elements on its bottom edge, the image covering a share of the viewport's height if set to,
23
- * and staying put on the screen while the header scrolls over it if set to; variant B flows the
25
+ * staying put on the screen while the header scrolls over it if set to, and zooming in a little and
26
+ * fading out as it scrolls off the screen if set to, the header's fill showing as it fades; variant B flows the
24
27
  * shown elements in order, each placed as in the stack. The variant, the order and what is shown
25
- * are a layout's, so every element is drawn once and arranged per layout.
28
+ * are a layout's, so every element is drawn once and arranged per layout. The elements stack in the
29
+ * header by their own z-indexes, so the text can go under the image.
26
30
  */
27
31
  const StructuredHeader = ({ header, blocks, readingWidth }) => {
28
32
  const reactId = (0, react_1.useId)();
@@ -31,6 +35,9 @@ const StructuredHeader = ({ header, blocks, readingWidth }) => {
31
35
  const image = elementOf('image');
32
36
  const imageUrl = (image === null || image === void 0 ? void 0 : image.type) === sdk_1.StructuredBlockType.HeaderImage ? image.commonParams.url : '';
33
37
  const hasImage = Boolean(imageUrl);
38
+ const [imageElement, setImageElement] = (0, react_1.useState)(null);
39
+ const isFading = hasImage && Object.values(header.layoutParams).some(params => params.variant === 'A' && params.fadeOnScroll);
40
+ (0, useScrollFade_1.useScrollFade)(imageElement, isFading);
34
41
  const texts = TEXT_KINDS.flatMap((kind) => {
35
42
  const block = elementOf(kind);
36
43
  return block ? [{ kind, block }] : [];
@@ -39,10 +46,10 @@ const StructuredHeader = ({ header, blocks, readingWidth }) => {
39
46
  const stackClass = `structured-header-stack-${header.id}`;
40
47
  const elementClass = (block) => `structured-header-element-${block.id}`;
41
48
  const pinClass = (block, part = '') => `structured-header-pin${part}-${block.id}`;
42
- const renderElement = (block, extra) => {
49
+ const renderElement = (block, extra, ref) => {
43
50
  var _a;
44
51
  const BlockComponent = (_a = blocksMap_1.blocksMap[block.type]) !== null && _a !== void 0 ? _a : blocksMap_1.UnknownBlock;
45
- return ((0, jsx_runtime_1.jsxs)("div", { className: elementClass(block), children: [(0, jsx_runtime_1.jsx)(BlockComponent, { block: block, readingWidth: readingWidth }), extra] }, block.id));
52
+ return ((0, jsx_runtime_1.jsxs)("div", { ref: ref, className: elementClass(block), children: [(0, jsx_runtime_1.jsx)(BlockComponent, { block: block, readingWidth: readingWidth }), extra] }, block.id));
46
53
  };
47
54
  // a sticky backdrop, the way a section's fixed background is drawn: a screen-tall frame stuck
48
55
  // inside a track a screen longer at each end, clipped to the header; the picture itself only
@@ -70,21 +77,26 @@ const StructuredHeader = ({ header, blocks, readingWidth }) => {
70
77
  }
71
78
  `;
72
79
  const elementStyles = (kind, block) => (0, sdk_1.getLayoutStyles)(layouts, [header.layoutParams, block.area, block.layoutParams], ([layoutParams, area, blockLayoutParams]) => {
73
- var _a;
80
+ var _a, _b;
74
81
  const isBackdrop = kind === 'image' && layoutParams.variant === 'A';
75
82
  const isHidden = !isBackdrop && layoutParams.hiddenElements.includes(kind);
76
83
  const isCover = isBackdrop && layoutParams.imageFit === 'cover';
77
84
  const isSticky = isBackdrop && Boolean(layoutParams.stickyImage);
85
+ // the fading picture zooms inside the image's box, and whichever picture shows fades with the box
86
+ const isFaded = isBackdrop && Boolean(layoutParams.fadeOnScroll);
87
+ const fade = `var(${useScrollFade_1.SCROLL_FADE_PROPERTY}, 0)`;
78
88
  // every value is written on every layout: the media queries stack upward, so a layout's
79
89
  // backdrop or cover would otherwise carry into the larger layouts drawn another way
80
90
  return (`
81
91
  .${elementClass(block)} {
82
92
  display: ${isHidden ? 'none' : 'block'};
83
93
  position: relative;
94
+ z-index: ${(_a = area === null || area === void 0 ? void 0 : area.zIndex) !== null && _a !== void 0 ? _a : 0};
84
95
  order: ${orderOf(layoutParams.order, kind)};
85
96
  ${isBackdrop
86
97
  ? `width: 100%; left: 0; height: ${isCover ? '100%' : 'auto'}; padding: 0;`
87
98
  : (0, blockPlacement_1.blockPlacement)(area, blockLayoutParams)}
99
+ ${kind === 'image' ? `overflow: ${isFaded ? 'clip' : 'visible'}; opacity: ${isFaded ? `calc(1 - ${fade})` : 1};` : ''}
88
100
  }
89
101
  .${elementClass(block)} .structured-caption-${block.id} {
90
102
  display: ${isBackdrop ? 'none' : 'block'};
@@ -105,12 +117,16 @@ const StructuredHeader = ({ header, blocks, readingWidth }) => {
105
117
  .${pinClass(block, '-frame')} {
106
118
  background-size: ${isCover ? 'cover' : '100% auto'};
107
119
  background-position: ${isCover ? 'center' : 'top center'};
108
- opacity: ${(_a = blockLayoutParams === null || blockLayoutParams === void 0 ? void 0 : blockLayoutParams.opacity) !== null && _a !== void 0 ? _a : 1};
120
+ opacity: ${(_b = blockLayoutParams === null || blockLayoutParams === void 0 ? void 0 : blockLayoutParams.opacity) !== null && _b !== void 0 ? _b : 1};
121
+ }
122
+ .${elementClass(block)} .structured-header-image-${block.id},
123
+ .${pinClass(block, '-frame')} {
124
+ transform: ${isFaded ? `scale(calc(1 + ${useScrollFade_1.SCROLL_FADE_ZOOM} * ${fade}))` : 'none'};
109
125
  }`
110
126
  : ''}
111
127
  `);
112
128
  });
113
- return ((0, jsx_runtime_1.jsxs)("div", { className: headerClass, children: [image && renderElement(image, hasImage && renderPin(image)), (0, jsx_runtime_1.jsx)("div", { className: stackClass, children: texts.map(({ block }) => renderElement(block)) }), (0, jsx_runtime_1.jsx)(style_1.default, { id: `${reactId}-header-${header.id}`, children: `
129
+ return ((0, jsx_runtime_1.jsxs)("div", { className: headerClass, children: [image && renderElement(image, hasImage && renderPin(image), setImageElement), (0, jsx_runtime_1.jsx)("div", { className: stackClass, children: texts.map(({ block }) => renderElement(block)) }), (0, jsx_runtime_1.jsx)(style_1.default, { id: `${reactId}-header-${header.id}`, children: `
114
130
  .${headerClass} {
115
131
  position: relative;
116
132
  width: 100%;
@@ -120,6 +136,8 @@ const StructuredHeader = ({ header, blocks, readingWidth }) => {
120
136
  var _a;
121
137
  const isA = layoutParams.variant === 'A';
122
138
  const isCover = isA && layoutParams.imageFit === 'cover';
139
+ // the fill is drawn only behind a fading image, and cleared on every other layout
140
+ const fill = isA && layoutParams.fadeOnScroll ? layoutParams.background : undefined;
123
141
  return (`
124
142
  .${headerClass} {
125
143
  display: ${isA ? 'block' : 'flex'};
@@ -128,7 +146,9 @@ const StructuredHeader = ({ header, blocks, readingWidth }) => {
128
146
  margin-top: ${(area === null || area === void 0 ? void 0 : area.paddingTop) ? `${area.paddingTop * 100}vw` : 0};
129
147
  height: ${isCover ? `${layoutParams.coverHeight * 100}vh` : 'auto'};
130
148
  height: ${isCover ? `${layoutParams.coverHeight * 100}svh` : 'auto'};
149
+ background-color: transparent;
131
150
  }
151
+ ${fill ? (0, textStylesRule_1.colorRule)(`.${headerClass}`, 'background-color', fill) : ''}
132
152
  .${stackClass} {
133
153
  ${isA
134
154
  ? `display: flex; flex-direction: column; position: ${hasImage ? 'absolute' : 'relative'}; left: 0; right: 0; bottom: 0;`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cntrl-site/sdk-nextjs",
3
- "version": "1.11.13",
3
+ "version": "1.11.15",
4
4
  "description": "SDK for Next.js",
5
5
  "author": "arsen@momdesign.nyc",
6
6
  "license": "MIT",
@@ -30,9 +30,9 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "@cntrl-site/color": "^1.0.0",
33
- "@cntrl-site/components": "^1.0.115",
33
+ "@cntrl-site/components": "^1.0.116",
34
34
  "@cntrl-site/effects": "^1.4.2",
35
- "@cntrl-site/sdk": "^1.29.11",
35
+ "@cntrl-site/sdk": "^1.29.12",
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,25 @@
1
+ import { scrollFadeProgress } from './useScrollFade';
2
+
3
+ describe('scrollFadeProgress', () => {
4
+ it('has not faded while all of the element is on the screen', () => {
5
+ expect(scrollFadeProgress(0, 600, 900)).toBe(0);
6
+ expect(scrollFadeProgress(100, 700, 900)).toBe(0);
7
+ });
8
+
9
+ it('fades from the first pixel scrolled off the screen\'s top, all the way once it is gone', () => {
10
+ expect(scrollFadeProgress(-150, 450, 900)).toBeCloseTo(0.25);
11
+ expect(scrollFadeProgress(-300, 300, 900)).toBeCloseTo(0.5);
12
+ expect(scrollFadeProgress(-600, 0, 900)).toBe(1);
13
+ expect(scrollFadeProgress(-700, -100, 900)).toBe(1);
14
+ });
15
+
16
+ it('counts the screen an element taller than it fills, not the element', () => {
17
+ expect(scrollFadeProgress(-1000, 1000, 900)).toBe(0);
18
+ expect(scrollFadeProgress(-1100, 900, 900)).toBe(0);
19
+ expect(scrollFadeProgress(-1550, 450, 900)).toBeCloseTo(0.5);
20
+ });
21
+
22
+ it('has not faded entering from below', () => {
23
+ expect(scrollFadeProgress(800, 1400, 900)).toBe(0);
24
+ });
25
+ });
@@ -0,0 +1,57 @@
1
+ import { useEffect } from 'react';
2
+
3
+ // the share of an element left on the screen as it leaves the top at which it starts to fade: all
4
+ // of it, so it fades from the first pixel scrolled, as the editor draws it
5
+ const FADE_START = 1;
6
+
7
+ /** The property `useScrollFade` writes the fade to, from 0 to 1, for the element's styles to draw it. */
8
+ export const SCROLL_FADE_PROPERTY = '--cntrl-scroll-fade';
9
+
10
+ /** How much larger a fading element is drawn once it has faded all the way. */
11
+ export const SCROLL_FADE_ZOOM = 0.15;
12
+
13
+ /**
14
+ * How far an element leaving the screen's top has faded: nothing while all of it is on the screen,
15
+ * as much as has left it as it scrolls off, all of it once it is gone. An element taller than the
16
+ * screen counts the screen it fills instead, so it fades once its bottom is on the screen, over a
17
+ * screen's height of scrolling. An element yet to reach the screen's top, or entering from below,
18
+ * has not faded.
19
+ */
20
+ export function scrollFadeProgress(top: number, bottom: number, screenHeight: number): number {
21
+ const full = Math.min(bottom - top, screenHeight);
22
+ if (full <= 0) return 0;
23
+ const left = bottom / full;
24
+ return Math.min(Math.max(1 - left / FADE_START, 0), 1);
25
+ }
26
+
27
+ /**
28
+ * Writes to the element how far it has faded leaving the screen, as the page scrolls or the element
29
+ * resizes, while enabled; nothing is drawn here, the element's styles draw the fade. Until it runs,
30
+ * as the page is first drawn, the element is unfaded.
31
+ */
32
+ export function useScrollFade(element: HTMLElement | null, isEnabled: boolean): void {
33
+ useEffect(() => {
34
+ if (!element || !isEnabled) return;
35
+ let frame = 0;
36
+ const update = () => {
37
+ frame = 0;
38
+ const { top, bottom } = element.getBoundingClientRect();
39
+ element.style.setProperty(SCROLL_FADE_PROPERTY, String(scrollFadeProgress(top, bottom, window.innerHeight)));
40
+ };
41
+ const schedule = () => {
42
+ if (!frame) frame = requestAnimationFrame(update);
43
+ };
44
+ update();
45
+ window.addEventListener('scroll', schedule, { passive: true });
46
+ window.addEventListener('resize', schedule);
47
+ const observer = new ResizeObserver(schedule);
48
+ observer.observe(element);
49
+ return () => {
50
+ cancelAnimationFrame(frame);
51
+ window.removeEventListener('scroll', schedule);
52
+ window.removeEventListener('resize', schedule);
53
+ observer.disconnect();
54
+ element.style.removeProperty(SCROLL_FADE_PROPERTY);
55
+ };
56
+ }, [element, isEnabled]);
57
+ }
@@ -44,7 +44,7 @@ export function textColumnsRule(
44
44
  /**
45
45
  * The box a quote's text or a table is drawn in, as a CSS rule for `selector`: padded inside, its
46
46
  * sides grown out past the columns the block is placed on by as much as they pad it, so what it
47
- * holds stays on them; rounded, and filled where it has a fill.
47
+ * holds stays on them; rounded, turned, and filled where it has a fill.
48
48
  */
49
49
  export function boxRule(selector: string, box: StructuredBlockBoxParams): string {
50
50
  return `
@@ -52,6 +52,7 @@ export function boxRule(selector: string, box: StructuredBlockBoxParams): string
52
52
  padding: ${[box.boxPaddingTop, box.boxPaddingRight, box.boxPaddingBottom, box.boxPaddingLeft].map(vw).join(' ')};
53
53
  margin: 0 -${vw(box.boxPaddingRight)} 0 -${vw(box.boxPaddingLeft)};
54
54
  border-radius: ${vw(box.boxRadius)};
55
+ rotate: ${box.boxRotation ? `${box.boxRotation}deg` : 'none'};
55
56
  background-color: transparent;
56
57
  }
57
58
  ${box.boxBackground ? colorRule(selector, 'background-color', box.boxBackground) : ''}
@@ -64,7 +64,8 @@ const quote = block(StructuredBlockType.Quote, 'quote', { ...paragraph('A quote'
64
64
  boxPaddingRight: 0.03,
65
65
  boxPaddingBottom: 0.02,
66
66
  boxPaddingLeft: 0.01,
67
- boxRadius: 0.01
67
+ boxRadius: 0.01,
68
+ boxRotation: -4
68
69
  });
69
70
  const date = block(StructuredBlockType.Date, 'date', { ...paragraph('23 Sep 2026'), date: '2026-09-23', format: 'D MMM YYYY' }, {
70
71
  ...textStyles,
@@ -206,6 +207,7 @@ describe('StructuredContent', () => {
206
207
  expect(container.querySelector('.structured-quote-box-quote')!.textContent!.trim()).toBe('A quote');
207
208
  // its sides grow out past the columns the text is placed on, which it stays on
208
209
  expect(css()).toMatch(/\.structured-quote-box-quote \{[^}]*padding: 2vw 3vw 2vw 1vw;[^}]*margin: 0 -3vw 0 -1vw;[^}]*border-radius: 1vw;/);
210
+ expect(css()).toMatch(/\.structured-quote-box-quote \{[^}]*rotate: -4deg;/);
209
211
  expect(css()).toMatch(/\.structured-quote-box-quote \{\s*background-color: oklch/);
210
212
  expect(container.querySelector('.structured-text-date')!.textContent!.trim()).toBe('23 Sep 2026');
211
213
  // a quote is a quotation of paragraphs, kept from the margins of both
@@ -284,6 +286,8 @@ describe('StructuredContent', () => {
284
286
  const { container } = draw({ ...section(false), structuredContent: [boxed] } as Section);
285
287
  expect(container.querySelector('.structured-table-box-boxed > .structured-table-boxed')).not.toBeNull();
286
288
  expect(css()).toMatch(/\.structured-table-box-boxed \{[^}]*padding: 1vw 2vw 1vw 2vw;[^}]*margin: 0 -2vw 0 -2vw;[^}]*border-radius: 0\.5vw;/);
289
+ // a box with no turn of its own is drawn upright on every layout, whatever another layout turns it by
290
+ expect(css()).toMatch(/\.structured-table-box-boxed \{[^}]*rotate: none;/);
287
291
  expect(css()).toMatch(/\.structured-table-box-boxed \{\s*background-color: oklch/);
288
292
  });
289
293
 
@@ -369,6 +373,15 @@ describe('StructuredContent', () => {
369
373
  expect(css()).toMatch(/\.structured-header-element-key-image \.structured-header-picture-key-image \{\s*object-fit: fill;/);
370
374
  });
371
375
 
376
+ it('stacks the header\'s elements by their own z-indexes on each layout, so its text can go under its image', () => {
377
+ const under = { ...title, area: { desktop: { ...onGrid, zIndex: 3 }, mobile: { ...onGrid, zIndex: 7 } } };
378
+ const keyImage = { ...headerImage, area: { desktop: { ...onGrid, zIndex: 5 }, mobile: { ...onGrid, zIndex: 5 } } };
379
+ draw({ ...section(true), structuredContent: [under, keyImage, ...stack] } as unknown as Section);
380
+ expect(css()).toMatch(/@media \(min-width: 800px\) \{[\s\S]*\.structured-header-element-title \{[^}]*z-index: 3;/);
381
+ expect(css()).toMatch(/\.structured-header-element-title \{[^}]*z-index: 7;/);
382
+ expect(css()).toMatch(/\.structured-header-element-key-image \{[^}]*z-index: 5;/);
383
+ });
384
+
372
385
  it('keeps a sticky key image still on the screen, as a fixed section background, on the layouts that stick it', () => {
373
386
  const sticky = { ...header, layoutParams: { ...header.layoutParams, desktop: { ...header.layoutParams.desktop, stickyImage: true } } };
374
387
  const { container } = draw({ ...section(true), header: sticky } as unknown as Section);
@@ -381,6 +394,83 @@ describe('StructuredContent', () => {
381
394
  expect(css()).toMatch(/\.structured-header-pin-key-image \{\s*display: none;/);
382
395
  });
383
396
 
397
+ describe('a key image fading on scroll', () => {
398
+ const fading = { ...header, layoutParams: { ...header.layoutParams, desktop: { ...header.layoutParams.desktop, fadeOnScroll: true } } };
399
+ let frames: FrameRequestCallback[];
400
+ const { requestAnimationFrame, cancelAnimationFrame } = window;
401
+
402
+ beforeEach(() => {
403
+ frames = [];
404
+ window.requestAnimationFrame = callback => frames.push(callback);
405
+ window.cancelAnimationFrame = () => {};
406
+ (window as { ResizeObserver?: unknown }).ResizeObserver = class { observe() {} disconnect() {} };
407
+ });
408
+
409
+ afterEach(() => {
410
+ Object.assign(window, { requestAnimationFrame, cancelAnimationFrame });
411
+ delete (window as { ResizeObserver?: unknown }).ResizeObserver;
412
+ });
413
+
414
+ const scrolled = (element: HTMLElement, top: number, bottom: number) => {
415
+ element.getBoundingClientRect = () => ({ top, bottom }) as DOMRect;
416
+ window.dispatchEvent(new Event('scroll'));
417
+ frames.splice(0).forEach(frame => frame(0));
418
+ return element.style.getPropertyValue('--cntrl-scroll-fade');
419
+ };
420
+
421
+ it('zooms it inside its box and fades it on the layouts that fade it, and draws it still on the others', () => {
422
+ draw({ ...section(true), header: fading } as unknown as Section);
423
+ // desktop, variant A: whichever picture shows, the image's own or its sticky copy
424
+ expect(css()).toMatch(/@media \(min-width: 800px\) \{[\s\S]*\.structured-header-element-key-image \{[^}]*overflow: clip; opacity: calc\(1 - var\(--cntrl-scroll-fade, 0\)\);/);
425
+ expect(css()).toMatch(/\.structured-header-element-key-image \.structured-header-image-key-image,\s*\.structured-header-pin-frame-key-image \{\s*transform: scale\(calc\(1 \+ 0\.15 \* var\(--cntrl-scroll-fade, 0\)\)\);/);
426
+ // mobile, variant B: written back, so the fade ends where the layout does
427
+ expect(css()).toMatch(/\.structured-header-element-key-image \{[^}]*overflow: visible; opacity: 1;/);
428
+ expect(css()).toMatch(/\.structured-header-pin-frame-key-image \{\s*transform: none;/);
429
+ });
430
+
431
+ it('fills the header behind its key image on the layouts that fade it, and leaves it clear on the others', () => {
432
+ const fill = 'oklch(0.9 0.02 80 / 1)';
433
+ const layoutCss = (layoutParams: object) => {
434
+ const { unmount } = draw({ ...section(true), header: { ...header, layoutParams } } as unknown as Section);
435
+ // the header's own styles: the smallest layout's bare, each larger one's in a query of its own
436
+ const headerCss = [...document.body.querySelectorAll('style')].map(style => style.textContent ?? '').find(text => text.includes('.structured-header-stack-header')) ?? '';
437
+ const rules = headerCss.split('@media').filter(rule => rule.includes('.structured-header-header {'));
438
+ unmount();
439
+ return {
440
+ desktop: rules.find(rule => rule.startsWith(' (min-width: 800px)')) ?? '',
441
+ mobile: rules.find(rule => !rule.startsWith(' (min-width')) ?? ''
442
+ };
443
+ };
444
+ // desktop fades its variant A image, mobile draws variant B: the fill is desktop's alone
445
+ const fading = layoutCss({
446
+ desktop: { ...header.layoutParams.desktop, fadeOnScroll: true, background: fill },
447
+ mobile: { ...header.layoutParams.mobile, fadeOnScroll: true, background: fill }
448
+ });
449
+ expect(fading.desktop).toMatch(/\.structured-header-header \{\s*background-color: oklch\(/);
450
+ expect(fading.mobile).toMatch(/\.structured-header-header \{[^}]*background-color: transparent;/);
451
+ expect(fading.mobile).not.toMatch(/background-color: oklch/);
452
+ // a fill kept from before the image stopped fading is not drawn
453
+ const still = layoutCss({ ...header.layoutParams, desktop: { ...header.layoutParams.desktop, background: fill } });
454
+ expect(still.desktop).not.toMatch(/background-color: oklch/);
455
+ });
456
+
457
+ it('fades it from the first pixel scrolled off the screen\'s top, all the way once it is gone, and back as the page scrolls back', () => {
458
+ const { container } = draw({ ...section(true), header: fading } as unknown as Section);
459
+ const element = container.querySelector<HTMLElement>('.structured-header-element-key-image')!;
460
+ expect(scrolled(element, 0, 600)).toBe('0');
461
+ expect(Number(scrolled(element, -300, 300))).toBeCloseTo(0.5);
462
+ expect(scrolled(element, -700, -100)).toBe('1');
463
+ expect(scrolled(element, 0, 600)).toBe('0');
464
+ });
465
+
466
+ it('leaves a key image no layout fades alone', () => {
467
+ const { container } = draw(section(true));
468
+ const element = container.querySelector<HTMLElement>('.structured-header-element-key-image')!;
469
+ expect(scrolled(element, -500, 100)).toBe('');
470
+ expect(css()).not.toMatch(/overflow: clip; opacity: calc/);
471
+ });
472
+ });
473
+
384
474
  it('draws a key image no layout sticks as it is', () => {
385
475
  draw(section(true));
386
476
  expect(css()).not.toMatch(/\.structured-header-pin-key-image \{\s*display: block;/);
@@ -6,10 +6,12 @@ import {
6
6
  StructuredBlockAny,
7
7
  StructuredBlockType
8
8
  } from '@cntrl-site/sdk';
9
- import { FC, ReactNode, useId } from 'react';
9
+ import { FC, ReactNode, useId, useState } from 'react';
10
10
  import JSXStyle from 'styled-jsx/style';
11
11
  import { useCntrlContext } from '../../provider/useCntrlContext';
12
+ import { SCROLL_FADE_PROPERTY, SCROLL_FADE_ZOOM, useScrollFade } from '../../common/useScrollFade';
12
13
  import { blockPlacement } from '../StructuredBlockItem/blockPlacement';
14
+ import { colorRule } from '../StructuredBlockItem/textStylesRule';
13
15
  import { blocksMap, UnknownBlock } from '../StructuredBlockItem/blocksMap';
14
16
 
15
17
  interface Props {
@@ -30,9 +32,11 @@ function orderOf(order: HeaderElementKind[], kind: HeaderElementKind): number {
30
32
  /**
31
33
  * A content-based section's header, drawn first. Variant A draws the key image full width with the
32
34
  * other elements on its bottom edge, the image covering a share of the viewport's height if set to,
33
- * and staying put on the screen while the header scrolls over it if set to; variant B flows the
35
+ * staying put on the screen while the header scrolls over it if set to, and zooming in a little and
36
+ * fading out as it scrolls off the screen if set to, the header's fill showing as it fades; variant B flows the
34
37
  * shown elements in order, each placed as in the stack. The variant, the order and what is shown
35
- * are a layout's, so every element is drawn once and arranged per layout.
38
+ * are a layout's, so every element is drawn once and arranged per layout. The elements stack in the
39
+ * header by their own z-indexes, so the text can go under the image.
36
40
  */
37
41
  export const StructuredHeader: FC<Props> = ({ header, blocks, readingWidth }) => {
38
42
  const reactId = useId();
@@ -41,6 +45,9 @@ export const StructuredHeader: FC<Props> = ({ header, blocks, readingWidth }) =>
41
45
  const image = elementOf('image');
42
46
  const imageUrl = image?.type === StructuredBlockType.HeaderImage ? (image as HeaderImageStructuredBlock).commonParams.url : '';
43
47
  const hasImage = Boolean(imageUrl);
48
+ const [imageElement, setImageElement] = useState<HTMLDivElement | null>(null);
49
+ const isFading = hasImage && Object.values(header.layoutParams).some(params => params.variant === 'A' && params.fadeOnScroll);
50
+ useScrollFade(imageElement, isFading);
44
51
  const texts = TEXT_KINDS.flatMap((kind) => {
45
52
  const block = elementOf(kind);
46
53
  return block ? [{ kind, block }] : [];
@@ -49,10 +56,10 @@ export const StructuredHeader: FC<Props> = ({ header, blocks, readingWidth }) =>
49
56
  const stackClass = `structured-header-stack-${header.id}`;
50
57
  const elementClass = (block: StructuredBlockAny) => `structured-header-element-${block.id}`;
51
58
  const pinClass = (block: StructuredBlockAny, part = '') => `structured-header-pin${part}-${block.id}`;
52
- const renderElement = (block: StructuredBlockAny, extra?: ReactNode) => {
59
+ const renderElement = (block: StructuredBlockAny, extra?: ReactNode, ref?: (element: HTMLDivElement | null) => void) => {
53
60
  const BlockComponent = blocksMap[block.type] ?? UnknownBlock;
54
61
  return (
55
- <div key={block.id} className={elementClass(block)}>
62
+ <div key={block.id} ref={ref} className={elementClass(block)}>
56
63
  <BlockComponent block={block} readingWidth={readingWidth} />
57
64
  {extra}
58
65
  </div>
@@ -97,16 +104,21 @@ export const StructuredHeader: FC<Props> = ({ header, blocks, readingWidth }) =>
97
104
  const isHidden = !isBackdrop && layoutParams.hiddenElements.includes(kind);
98
105
  const isCover = isBackdrop && layoutParams.imageFit === 'cover';
99
106
  const isSticky = isBackdrop && Boolean(layoutParams.stickyImage);
107
+ // the fading picture zooms inside the image's box, and whichever picture shows fades with the box
108
+ const isFaded = isBackdrop && Boolean(layoutParams.fadeOnScroll);
109
+ const fade = `var(${SCROLL_FADE_PROPERTY}, 0)`;
100
110
  // every value is written on every layout: the media queries stack upward, so a layout's
101
111
  // backdrop or cover would otherwise carry into the larger layouts drawn another way
102
112
  return (`
103
113
  .${elementClass(block)} {
104
114
  display: ${isHidden ? 'none' : 'block'};
105
115
  position: relative;
116
+ z-index: ${area?.zIndex ?? 0};
106
117
  order: ${orderOf(layoutParams.order, kind)};
107
118
  ${isBackdrop
108
119
  ? `width: 100%; left: 0; height: ${isCover ? '100%' : 'auto'}; padding: 0;`
109
120
  : blockPlacement(area, blockLayoutParams)}
121
+ ${kind === 'image' ? `overflow: ${isFaded ? 'clip' : 'visible'}; opacity: ${isFaded ? `calc(1 - ${fade})` : 1};` : ''}
110
122
  }
111
123
  .${elementClass(block)} .structured-caption-${block.id} {
112
124
  display: ${isBackdrop ? 'none' : 'block'};
@@ -128,6 +140,10 @@ export const StructuredHeader: FC<Props> = ({ header, blocks, readingWidth }) =>
128
140
  background-size: ${isCover ? 'cover' : '100% auto'};
129
141
  background-position: ${isCover ? 'center' : 'top center'};
130
142
  opacity: ${blockLayoutParams?.opacity ?? 1};
143
+ }
144
+ .${elementClass(block)} .structured-header-image-${block.id},
145
+ .${pinClass(block, '-frame')} {
146
+ transform: ${isFaded ? `scale(calc(1 + ${SCROLL_FADE_ZOOM} * ${fade}))` : 'none'};
131
147
  }`
132
148
  : ''}
133
149
  `);
@@ -135,7 +151,7 @@ export const StructuredHeader: FC<Props> = ({ header, blocks, readingWidth }) =>
135
151
  );
136
152
  return (
137
153
  <div className={headerClass}>
138
- {image && renderElement(image, hasImage && renderPin(image))}
154
+ {image && renderElement(image, hasImage && renderPin(image), setImageElement)}
139
155
  <div className={stackClass}>
140
156
  {texts.map(({ block }) => renderElement(block))}
141
157
  </div>
@@ -148,6 +164,8 @@ export const StructuredHeader: FC<Props> = ({ header, blocks, readingWidth }) =>
148
164
  ${getLayoutStyles(layouts, [header.layoutParams, header.area] as Record<string, any>[], ([layoutParams, area]) => {
149
165
  const isA = layoutParams.variant === 'A';
150
166
  const isCover = isA && layoutParams.imageFit === 'cover';
167
+ // the fill is drawn only behind a fading image, and cleared on every other layout
168
+ const fill: string | undefined = isA && layoutParams.fadeOnScroll ? layoutParams.background : undefined;
151
169
  return (`
152
170
  .${headerClass} {
153
171
  display: ${isA ? 'block' : 'flex'};
@@ -156,7 +174,9 @@ export const StructuredHeader: FC<Props> = ({ header, blocks, readingWidth }) =>
156
174
  margin-top: ${area?.paddingTop ? `${area.paddingTop * 100}vw` : 0};
157
175
  height: ${isCover ? `${layoutParams.coverHeight * 100}vh` : 'auto'};
158
176
  height: ${isCover ? `${layoutParams.coverHeight * 100}svh` : 'auto'};
177
+ background-color: transparent;
159
178
  }
179
+ ${fill ? colorRule(`.${headerClass}`, 'background-color', fill) : ''}
160
180
  .${stackClass} {
161
181
  ${isA
162
182
  ? `display: flex; flex-direction: column; position: ${hasImage ? 'absolute' : 'relative'}; left: 0; right: 0; bottom: 0;`