Skip to content

Commit c83f03d

Browse files
committed
fix(Lightbox): a caption that grows past two lines gets "more"
A gallery caption re-measured its clamp only when its box resized, a page attached, or the caption opened or closed. New text in a box that kept its two lines never got "more". The clamp now comes from Text's own truncation check, which also follows new text: useHeldTruncation, a variant of useTruncation internal to core, keeps the answer while the caption is open, so the toggle stays mounted, with its focus, as the caption closes. useTruncation's public options do not change, and only the held variant runs a layout effect, so Text and Heading run no new effect. Lightbox still measures the toggle's place and the open caption's scroll, now on new text too. A closed dialog lays its caption out at no size, so Lightbox measures the caption again as the dialog opens, before the first paint: the first frame that shows a clamped caption already ends it in "more". The changeset now says that a gallery's caption keeps 4.5:1, and the record lists a single photo's caption, which has no backing, as a gap in FR17.
1 parent 8d2a865 commit c83f03d

6 files changed

Lines changed: 271 additions & 25 deletions

File tree

‎.changeset/lightbox-gallery-caption-row.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,6 @@
44

55
[feat] A Lightbox gallery's caption sits in a band two lines tall under every photo, so the photo keeps one size and place from item to item. A photo with no caption keeps the band's space without its backing. A longer caption shows two lines, the second ending in a "more" button, which opens the whole caption over the photo. The whole caption is always the viewer's accessible description.
66

7-
The viewer is a media surface: its controls, caption and counter take the theme's dark surface tokens through `MediaTheme`. The caption is body `Text` whose lines start at one edge, "more" and "less" are a ghost `Button`, and the band clears the screen's bottom edge and its safe area. The caption sits on a backing that keeps it at 4.5:1 over any photo. A tap that opens the viewer paints no focus ring on its first control, and paging from a focused "more" or "less" keeps focus in the viewer.
7+
The viewer is a media surface: its controls, caption and counter take the theme's dark surface tokens through `MediaTheme`. The caption is body `Text` whose lines start at one edge, "more" and "less" are a ghost `Button`, and the band clears the screen's bottom edge and its safe area. A gallery's caption sits on a backing that keeps it at 4.5:1 over any photo. A tap that opens the viewer paints no focus ring on its first control, and paging from a focused "more" or "less" keeps focus in the viewer.
88

99
@vjeux

‎docs/specs/components/Lightbox/Lightbox.spec.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,9 @@ the requirement it misses and the person it affects.
8888
browser that places controls elsewhere pages from them.
8989
- **Tab containment (FR4).** Tab from the viewer's last control can move focus
9090
to the browser's own interface.
91+
- **Single photo's caption contrast (FR17).** A single photo's caption has no
92+
backing. Its white text over the backdrop measures 4.00:1 over a white
93+
page, under FR17's 4.5:1, so a low-vision reader can lose it there.
9194
- **Zoom reset key (AR3).** `0` does not return a zoomed photo to its fitted
9295
size.
9396
- **Zoom announcement (AR4).** A zoom change announces "zoomed in" or "zoomed

‎packages/core/src/Lightbox/Lightbox.tsx‎

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import {useScrollLock} from '../hooks/useScrollLock';
5151
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
5252
import {useAttachment} from '../hooks/useAttachment';
5353
import {observeResize} from '../utils/sharedResizeObserver';
54+
import {observeContent} from '../utils/sharedMutationObserver';
5455
import {watchHitArea, writeHitInsets} from '../utils/hitArea';
5556
import {usePressTracker} from '../gestures/usePressTracker';
5657
import {mergeProps, rtlStyles} from '../utils';
@@ -94,6 +95,7 @@ import {
9495
import {useInteractionModalityTracking} from '../utils/interactionModality';
9596
import {MediaTheme} from '../theme/MediaTheme';
9697
import {Text} from '../Text/Text';
98+
import {useHeldTruncation} from '../Text/useTruncation';
9799
import {Button} from '../Button/Button';
98100

99101
registerEnglishFallback(english);
@@ -363,7 +365,7 @@ const styles = stylex.create({
363365
minWidth: 0,
364366
maxWidth: '100%',
365367
},
366-
// Text's two-line clamp.
368+
// Lets the clamped Text shrink inside the band.
367369
captionClamped: {
368370
flexShrink: 1,
369371
minWidth: 0,
@@ -853,13 +855,25 @@ export function Lightbox({
853855
// The toggle's width, which its place in the caption's last line takes.
854856
const [captionToggleWidth, setCaptionToggleWidth] = useState(0);
855857
// The current page's caption in its band, and whether two lines clamp it.
858+
// Text's truncation check also follows new text in a box that keeps its
859+
// size. While the caption is open it holds its closed answer, so the toggle
860+
// stays mounted, with its focus, as the caption closes.
856861
const bandCaptionRef = useRef<HTMLElement | null>(null);
857-
const [isCaptionClamped, setIsCaptionClamped] = useState(false);
862+
const captionTruncation = useHeldTruncation({
863+
maxLines: 2,
864+
isHeld: isCaptionOpen,
865+
});
866+
const isCaptionClamped = captionTruncation.isTruncated;
867+
const measureCaptionClamp = captionTruncation.measure;
868+
const bandCaptionMeasureRef = useMergedRefs(
869+
bandCaptionRef,
870+
captionTruncation.ref,
871+
);
858872
// How far below the caption's first line its last shown line starts.
859873
const [captionLastLineTop, setCaptionLastLineTop] = useState(0);
860874
// Whether the open caption scrolls inside its panel.
861875
const [isCaptionScrolling, setIsCaptionScrolling] = useState(false);
862-
const measureCaptionClamp = useCallback(() => {
876+
const measureCaptionLines = useCallback(() => {
863877
const caption = bandCaptionRef.current;
864878
if (caption != null) {
865879
const view = caption.ownerDocument.defaultView ?? window;
@@ -873,29 +887,36 @@ export function Lightbox({
873887
Number.isFinite(line) ? Math.max(0, lines - line) : 0,
874888
);
875889
}
876-
// An open caption shows every line. The toggle keeps the closed caption's
877-
// measurement, so it stays mounted, with its focus, as the caption closes.
878-
if (isCaptionOpen) {
879-
setIsCaptionScrolling(
880-
caption != null && caption.scrollHeight > caption.clientHeight + 1,
881-
);
882-
return;
883-
}
884-
setIsCaptionScrolling(false);
885-
setIsCaptionClamped(
886-
caption != null && caption.scrollHeight > caption.clientHeight + 1,
890+
setIsCaptionScrolling(
891+
isCaptionOpen &&
892+
caption != null &&
893+
caption.scrollHeight > caption.clientHeight + 1,
887894
);
888895
}, [isCaptionOpen]);
889-
// Syncs the clamp, the toggle's place and the open caption's scroll with
890-
// the caption's laid-out size. A resize, a font load and a new caption all
891-
// resize it, and paging attaches the next page's caption.
896+
// Syncs the toggle's place and the open caption's scroll with the caption's
897+
// laid-out size and its text. A resize and a font load resize it, new text
898+
// can keep its size, and paging attaches the next page's caption.
899+
// A closed dialog lays its caption out at no size, so the attachment runs
900+
// again as the dialog opens. showModal() above has run by then, and the
901+
// caption paints with its "more" from its first frame.
902+
const captionAttachKey = useMemo(
903+
() => ({measureCaptionLines, isOpen}),
904+
[measureCaptionLines, isOpen],
905+
);
892906
useAttachment(
893907
bandCaptionRef,
894908
element => {
909+
// The clamp too, at once, so the caption paints with its toggle.
895910
measureCaptionClamp();
896-
return observeResize(element, measureCaptionClamp);
911+
measureCaptionLines();
912+
const stopResize = observeResize(element, measureCaptionLines);
913+
const stopContent = observeContent(element, measureCaptionLines);
914+
return () => {
915+
stopResize();
916+
stopContent();
917+
};
897918
},
898-
measureCaptionClamp,
919+
captionAttachKey,
899920
);
900921
// The caption's toggle. Under a coarse pointer it takes taps out toward
901922
// 44 px. A finger's tap on it is its own, as UIKit gives a control's tap
@@ -1630,7 +1651,7 @@ export function Lightbox({
16301651
<Text
16311652
ref={
16321653
i === index
1633-
? bandCaptionRef
1654+
? bandCaptionMeasureRef
16341655
: undefined
16351656
}
16361657
id={i === index ? captionId : undefined}

‎packages/core/src/Lightbox/LightboxViewport.a11y.browser.spec.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,85 @@ for (const viewport of [
245245
});
246246
}
247247

248+
test(`the first frame that shows the clamped caption at open already ends it in "more"`, async ({
249+
page,
250+
}) => {
251+
await page.setViewportSize({width: 402, height: 874});
252+
await page.route(/picsum\.photos/, async route =>
253+
route.fulfill({contentType: 'image/svg+xml', body: PHOTO_SVG}),
254+
);
255+
await page.goto(
256+
`${storybook.origin}/iframe.html?id=core-lightbox--gallery-with-captions&viewMode=story`,
257+
);
258+
// Each frame from here on: whether the open viewer shows the current
259+
// caption, and whether its "more" is there. A frame's animation-frame
260+
// callbacks see what that frame paints.
261+
await page.evaluate(() => {
262+
const frames: {isShown: boolean; hasMore: boolean}[] = [];
263+
(window as unknown as {__captionFrames: typeof frames}).__captionFrames =
264+
frames;
265+
const read = () => {
266+
const caption = document.querySelector(
267+
'dialog[open] [data-current] [data-lightbox-caption]',
268+
);
269+
const text = caption?.querySelector('.astryx-text');
270+
const isShown = text != null && text.getBoundingClientRect().height > 0;
271+
frames.push({isShown, hasMore: caption?.querySelector('button') != null});
272+
if (frames.length < 600 && !frames.some(frame => frame.hasMore)) {
273+
requestAnimationFrame(read);
274+
}
275+
};
276+
requestAnimationFrame(read);
277+
});
278+
await page.getByRole('button', {name: 'Open gallery with captions'}).click();
279+
const dialog = page.getByRole('dialog');
280+
await expect(dialog.getByRole('button', {name: 'more'})).toBeVisible();
281+
const frames = await page.evaluate(
282+
() =>
283+
(
284+
window as unknown as {
285+
__captionFrames: {isShown: boolean; hasMore: boolean}[];
286+
}
287+
).__captionFrames,
288+
);
289+
const firstShown = frames.find(frame => frame.isShown);
290+
expect(firstShown, JSON.stringify(frames.slice(-6))).toEqual({
291+
isShown: true,
292+
hasMore: true,
293+
});
294+
});
295+
296+
test(`a caption whose text grows while its box keeps two lines gets "more" at the end of its second line`, async ({
297+
page,
298+
}) => {
299+
const dialog = await openCaptionGallery(page, {width: 402, height: 874});
300+
await dialog.getByRole('button', {name: 'Next'}).click();
301+
await expect(dialog.getByText('2 / 4')).toBeVisible();
302+
// The second page's caption fits its two lines, with no toggle.
303+
await expect(dialog.getByRole('button', {name: 'more'})).toHaveCount(0);
304+
const lines = await dialog.evaluate(element => {
305+
const text = element.querySelector(
306+
'[data-current] [data-lightbox-caption] .astryx-text',
307+
) as HTMLElement;
308+
const walker = document.createTreeWalker(text, NodeFilter.SHOW_TEXT);
309+
let last: Text | null = null;
310+
for (let node = walker.nextNode(); node != null; node = walker.nextNode()) {
311+
last = node as Text;
312+
}
313+
const before = text.getBoundingClientRect().height;
314+
// New text, past two lines, in a box that keeps its height.
315+
last?.appendData(
316+
' The trail climbs past the old mill, crosses the river on stepping stones, and winds back through the beeches to the car park at the top of the hill.',
317+
);
318+
return {before, after: text.getBoundingClientRect().height};
319+
});
320+
expect(lines.after, JSON.stringify(lines)).toBeCloseTo(lines.before, 0);
321+
await expect(dialog.getByRole('button', {name: 'more'})).toBeVisible();
322+
await expect(async () => {
323+
expectToggleEndsLastLine(await readToggle(dialog));
324+
}).toPass({timeout: 3_000});
325+
});
326+
248327
test(`a clamped caption's "more" still ends its second line after the viewport narrows (402 → 360)`, async ({
249328
page,
250329
}) => {

‎packages/core/src/Text/useTruncation.test.tsx‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,18 @@
88
import {act, render, screen, waitFor} from '@testing-library/react';
99
import {afterEach, describe, it, expect, vi} from 'vitest';
1010
import {useCallback} from 'react';
11-
import {useTruncation} from './useTruncation';
11+
import type * as layoutEffects from '../hooks/useIsomorphicLayoutEffect';
12+
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
13+
import {useHeldTruncation, useTruncation} from './useTruncation';
14+
15+
// The shipped layout effect, observable: a test counts who runs one.
16+
vi.mock('../hooks/useIsomorphicLayoutEffect', async importOriginal => {
17+
const actual = await importOriginal<typeof layoutEffects>();
18+
return {
19+
...actual,
20+
useIsomorphicLayoutEffect: vi.fn(actual.useIsomorphicLayoutEffect),
21+
};
22+
});
1223

1324
function Probe({text}: {text: string}) {
1425
const truncation = useTruncation({maxLines: 1});
@@ -164,6 +175,75 @@ describe('useTruncation', () => {
164175
});
165176
});
166177

178+
describe('useHeldTruncation', () => {
179+
function HeldProbe({isHeld, height}: {isHeld: boolean; height: number}) {
180+
const truncation = useHeldTruncation({maxLines: 2, isHeld});
181+
return (
182+
<>
183+
<span ref={truncation.ref} data-height={height}>
184+
text
185+
</span>
186+
<output data-testid="truncated">
187+
{String(truncation.isTruncated)}
188+
</output>
189+
</>
190+
);
191+
}
192+
193+
// jsdom lays nothing out: the text's content height is its scrollHeight,
194+
// which each case sets through the element's data-height.
195+
function stubHeights() {
196+
const scrollHeight = vi
197+
.spyOn(HTMLElement.prototype, 'scrollHeight', 'get')
198+
.mockImplementation(function (this: HTMLElement) {
199+
return Number(this.dataset.height ?? 0);
200+
});
201+
const offsetHeight = vi
202+
.spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
203+
.mockImplementation(function (this: HTMLElement) {
204+
return this.dataset.height == null ? 0 : 48;
205+
});
206+
return () => {
207+
scrollHeight.mockRestore();
208+
offsetHeight.mockRestore();
209+
};
210+
}
211+
212+
// Text and Heading run plain useTruncation in every instance, so only the
213+
// held variant may add a step to each render.
214+
it('adds a layout effect only to the held variant, never to useTruncation', () => {
215+
const layoutEffect = vi.mocked(useIsomorphicLayoutEffect);
216+
layoutEffect.mockClear();
217+
render(<Probe text="a status line" />);
218+
expect(layoutEffect).not.toHaveBeenCalled();
219+
render(<HeldProbe isHeld={false} height={40} />);
220+
expect(layoutEffect).toHaveBeenCalled();
221+
});
222+
223+
it('keeps its last answer while held, and measures again on release', async () => {
224+
const restore = stubHeights();
225+
try {
226+
const {rerender} = render(<HeldProbe isHeld={false} height={120} />);
227+
await waitFor(() =>
228+
expect(screen.getByTestId('truncated')).toHaveTextContent('true'),
229+
);
230+
// Held, the text shows every line: no measurement changes the answer.
231+
rerender(<HeldProbe isHeld={true} height={48} />);
232+
await act(async () => {
233+
await Promise.resolve();
234+
});
235+
expect(screen.getByTestId('truncated')).toHaveTextContent('true');
236+
// Released over text that now fits, it measures again.
237+
rerender(<HeldProbe isHeld={false} height={40} />);
238+
await waitFor(() =>
239+
expect(screen.getByTestId('truncated')).toHaveTextContent('false'),
240+
);
241+
} finally {
242+
restore();
243+
}
244+
});
245+
});
246+
167247
describe('content observation', () => {
168248
afterEach(() => {
169249
vi.unstubAllGlobals();

0 commit comments

Comments
 (0)