@charcuterie/ui 4.28.2 → 4.28.3

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.
Files changed (38) hide show
  1. package/dist/Avatar/Avatar.d.ts.map +1 -1
  2. package/dist/Avatar/Avatar.js +6 -15
  3. package/dist/Avatar/Avatar.js.map +1 -1
  4. package/dist/PortraitTiles/PortraitAvatar.d.ts +5 -0
  5. package/dist/PortraitTiles/PortraitAvatar.d.ts.map +1 -1
  6. package/dist/PortraitTiles/PortraitAvatar.js +9 -6
  7. package/dist/PortraitTiles/PortraitAvatar.js.map +1 -1
  8. package/dist/markdownEditorCodeMirror/finishParsing.testHelpers.d.ts +29 -0
  9. package/dist/markdownEditorCodeMirror/finishParsing.testHelpers.d.ts.map +1 -0
  10. package/dist/markdownEditorCodeMirror/finishParsing.testHelpers.js +38 -0
  11. package/dist/markdownEditorCodeMirror/finishParsing.testHelpers.js.map +1 -0
  12. package/dist/motion.testHelpers.d.ts +35 -0
  13. package/dist/motion.testHelpers.d.ts.map +1 -0
  14. package/dist/motion.testHelpers.js +44 -0
  15. package/dist/motion.testHelpers.js.map +1 -0
  16. package/dist/useImageFailure.d.ts +52 -0
  17. package/dist/useImageFailure.d.ts.map +1 -0
  18. package/dist/useImageFailure.js +71 -0
  19. package/dist/useImageFailure.js.map +1 -0
  20. package/dist/waitForImages.testHelpers.d.ts +33 -0
  21. package/dist/waitForImages.testHelpers.d.ts.map +1 -0
  22. package/dist/waitForImages.testHelpers.js +48 -0
  23. package/dist/waitForImages.testHelpers.js.map +1 -0
  24. package/package.json +1 -1
  25. package/src/Avatar/Avatar.test.tsx +54 -1
  26. package/src/Avatar/Avatar.tsx +7 -19
  27. package/src/GroupedList/GroupedList.test.tsx +22 -17
  28. package/src/Motion/useListMotion.test.tsx +21 -15
  29. package/src/Motion/usePresence.test.tsx +76 -24
  30. package/src/Motion/useValueChangeMotion.test.tsx +12 -9
  31. package/src/Overlay/overlayReturnFocus.test.tsx +18 -20
  32. package/src/PortraitTiles/PortraitAvatar.tsx +10 -5
  33. package/src/PortraitTiles/PortraitTiles.test.tsx +219 -17
  34. package/src/markdownEditorCodeMirror/MarkdownView.test.tsx +32 -11
  35. package/src/markdownEditorCodeMirror/finishParsing.testHelpers.ts +47 -0
  36. package/src/motion.testHelpers.ts +46 -0
  37. package/src/useImageFailure.ts +93 -0
  38. package/src/waitForImages.testHelpers.ts +61 -0
@@ -1,10 +1,16 @@
1
1
  import { composeStories } from "@storybook/react"
2
+ import type { ReactNode } from "react"
3
+ import { useLayoutEffect, useState } from "react"
4
+ import { createRoot, hydrateRoot } from "react-dom/client"
5
+ import { renderToString } from "react-dom/server"
2
6
  import { expect, userEvent, waitFor } from "storybook/test"
3
7
  import { test } from "vitest"
4
8
 
5
9
  import { expectNoAxeViolations } from "../expectNoAxeViolations.testHelpers.ts"
6
10
  import { mountStory } from "../mountStory.testHelpers.ts"
7
11
  import { expectAgentDrivable } from "../testing/index.ts"
12
+ import { waitForImagesToFinish } from "../waitForImages.testHelpers.ts"
13
+ import { PortraitAvatar } from "./PortraitAvatar.tsx"
8
14
  import * as stories from "./PortraitTiles.stories.tsx"
9
15
 
10
16
  const {
@@ -104,23 +110,23 @@ test("a picture that fails to load falls back to the initials", async () => {
104
110
  role: "group",
105
111
  })
106
112
 
107
- // A real 404 over the network, not a mocked error event, so it gets
108
- // longer than `waitFor`'s 1 s default: with four browser windows
109
- // sharing a CI runner the failure arrived after it.
110
- await waitFor(
111
- async () => {
112
- const broken = Array.from(
113
- group.querySelectorAll<HTMLImageElement>("img"),
114
- ).find((one) =>
115
- one.src.includes("charcuterie-missing-portrait"),
116
- )
117
-
118
- // Gone from the DOM entirely, replaced by the letter — not left
119
- // in place with a broken-image glyph in it.
120
- await expect(broken).toBeUndefined()
121
- },
122
- { timeout: 5000 },
123
- )
113
+ // A real 404 over the network, not a mocked error event, so the
114
+ // wait is for the browser's answer rather than for a clock. With
115
+ // four browser windows sharing a CI runner the 404 arrived after
116
+ // `waitFor`'s 1 s default, and a longer clock only moves the line.
117
+ await waitForImagesToFinish(group)
118
+
119
+ await waitFor(async () => {
120
+ const broken = Array.from(
121
+ group.querySelectorAll<HTMLImageElement>("img"),
122
+ ).find((one) =>
123
+ one.src.includes("charcuterie-missing-portrait"),
124
+ )
125
+
126
+ // Gone from the DOM entirely, replaced by the letter — not left
127
+ // in place with a broken-image glyph in it.
128
+ await expect(broken).toBeUndefined()
129
+ })
124
130
 
125
131
  const bailey = expectAgentDrivable(canvas, {
126
132
  name: "Bailey 860 points",
@@ -199,6 +205,202 @@ test("a fixed layout skips the query", async () => {
199
205
  * satisfies every check that the element rendered — which is exactly
200
206
  * how a token name that did not exist shipped in Docket.
201
207
  */
208
+ const MISSING_PICTURE = "/charcuterie-missing-portrait.png"
209
+
210
+ /** A picture that loads with no network and no fixture file. */
211
+ const WORKING_PICTURE = `data:image/svg+xml;utf8,${encodeURIComponent(
212
+ '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#2F6F4E"/></svg>',
213
+ )}`
214
+
215
+ /**
216
+ * A failure belongs to the URL that failed, not to the tile. An
217
+ * expired signed URL is replaced by a fresh one, and the tile has to
218
+ * try it: it used to keep a boolean, and showed the letter for the
219
+ * rest of its life.
220
+ */
221
+ test("a tile whose picture failed tries the next one it is given", async () => {
222
+ const host = document.createElement("div")
223
+
224
+ document.body.append(host)
225
+
226
+ const root = createRoot(host)
227
+
228
+ const renderPicture = (imageSrc: string) => {
229
+ root.render(
230
+ <PortraitAvatar
231
+ className=""
232
+ imageSrc={imageSrc}
233
+ initials="B"
234
+ />,
235
+ )
236
+ }
237
+
238
+ try {
239
+ renderPicture(MISSING_PICTURE)
240
+
241
+ await waitFor(async () => {
242
+ await expect(host.querySelector("img")).not.toBeNull()
243
+ })
244
+
245
+ await waitForImagesToFinish(host)
246
+
247
+ await waitFor(async () => {
248
+ await expect(host.querySelector("img")).toBeNull()
249
+ })
250
+
251
+ renderPicture(WORKING_PICTURE)
252
+
253
+ await waitFor(async () => {
254
+ await expect(host.querySelector("img")).not.toBeNull()
255
+ })
256
+
257
+ // It loaded, and it stays a picture.
258
+ await waitForImagesToFinish(host)
259
+
260
+ await expect(host.querySelector("img")).toHaveAttribute(
261
+ "src",
262
+ WORKING_PICTURE,
263
+ )
264
+ } finally {
265
+ root.unmount()
266
+
267
+ host.remove()
268
+ }
269
+ })
270
+
271
+ /**
272
+ * As for `Avatar`: a server-rendered picture can fail before
273
+ * `hydrateRoot` attaches `onError`, and React does not repeat the
274
+ * request, so the check has to happen when the ref is attached.
275
+ */
276
+ test("a picture that failed before hydration still falls back to the initials", async () => {
277
+ const picture = (
278
+ <PortraitAvatar
279
+ className=""
280
+ imageSrc={MISSING_PICTURE}
281
+ initials="B"
282
+ />
283
+ )
284
+
285
+ const host = document.createElement("div")
286
+
287
+ document.body.append(host)
288
+
289
+ host.innerHTML = renderToString(picture)
290
+
291
+ await waitForImagesToFinish(host)
292
+
293
+ await expect(host.querySelector("img")).not.toBeNull()
294
+
295
+ const root = hydrateRoot(host, picture)
296
+
297
+ try {
298
+ await waitFor(async () => {
299
+ await expect(host.querySelector("img")).toBeNull()
300
+ })
301
+
302
+ await expect(host).toHaveTextContent("B")
303
+ } finally {
304
+ root.unmount()
305
+
306
+ host.remove()
307
+ }
308
+ })
309
+
310
+ /** Two animation frames, as in `mountStory`: a barrier, not a clock. */
311
+ const settleFrames = () =>
312
+ new Promise<void>((resolve) => {
313
+ globalThis.requestAnimationFrame(() => {
314
+ globalThis.requestAnimationFrame(() => {
315
+ resolve()
316
+ })
317
+ })
318
+ })
319
+
320
+ const OTHER_WORKING_PICTURE = `data:image/svg+xml;utf8,${encodeURIComponent(
321
+ '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" fill="#6F2F4E"/></svg>',
322
+ )}`
323
+
324
+ /**
325
+ * Shows the first picture, and swaps to the second in a layout
326
+ * effect — in the same commit that hydrates it, so before the
327
+ * browser can finish decoding the first. `isBack` swaps back.
328
+ */
329
+ const SwitchingPicture = ({
330
+ isBack,
331
+ }: {
332
+ isBack: boolean
333
+ }): ReactNode => {
334
+ const [hasSwapped, setHasSwapped] = useState(false)
335
+
336
+ useLayoutEffect(() => {
337
+ setHasSwapped(true)
338
+ }, [])
339
+
340
+ return (
341
+ <PortraitAvatar
342
+ className=""
343
+ imageSrc={
344
+ hasSwapped && !isBack
345
+ ? OTHER_WORKING_PICTURE
346
+ : WORKING_PICTURE
347
+ }
348
+ initials="B"
349
+ />
350
+ )
351
+ }
352
+
353
+ /**
354
+ * The check that catches a failure from before hydration asks
355
+ * `decode()`, and `decode()` also rejects when a newer `src`
356
+ * supersedes the request. That rejection is not a failure. Read as
357
+ * one, it marked the first picture dead, and the tile showed the
358
+ * letter when it came back to that picture.
359
+ */
360
+ test("a picture that a new one superseded is not marked as failed", async () => {
361
+ const host = document.createElement("div")
362
+
363
+ document.body.append(host)
364
+
365
+ host.innerHTML = renderToString(
366
+ <SwitchingPicture isBack={false} />,
367
+ )
368
+
369
+ // Loaded before hydration, so the ref's check runs `decode()`.
370
+ await waitForImagesToFinish(host)
371
+
372
+ const root = hydrateRoot(
373
+ host,
374
+ <SwitchingPicture isBack={false} />,
375
+ )
376
+
377
+ try {
378
+ await waitFor(async () => {
379
+ await expect(
380
+ host.querySelector("img"),
381
+ ).toHaveAttribute("src", OTHER_WORKING_PICTURE)
382
+ })
383
+
384
+ // The second picture has loaded, the first one's decode has been
385
+ // superseded, and React has committed whatever that caused.
386
+ await waitForImagesToFinish(host)
387
+
388
+ await settleFrames()
389
+
390
+ root.render(<SwitchingPicture isBack />)
391
+
392
+ await waitFor(async () => {
393
+ await expect(
394
+ host.querySelector("img"),
395
+ ).toHaveAttribute("src", WORKING_PICTURE)
396
+ })
397
+ } finally {
398
+ root.unmount()
399
+
400
+ host.remove()
401
+ }
402
+ })
403
+
202
404
  test("each portrait wears a different hue, and a named one holds it", async () => {
203
405
  const { canvas } = await mountStory(Playground)
204
406
 
@@ -5,6 +5,7 @@ import { test } from "vitest"
5
5
  import { expectNoAxeViolations } from "../expectNoAxeViolations.testHelpers.ts"
6
6
  import { mountStory } from "../mountStory.testHelpers.ts"
7
7
  import { expectAgentDrivable } from "../testing/index.ts"
8
+ import { finishCodeMirrorParsing } from "./finishParsing.testHelpers.ts"
8
9
  import * as stories from "./MarkdownView.stories.tsx"
9
10
 
10
11
  const {
@@ -16,6 +17,26 @@ const {
16
17
  SameAsTheEditor,
17
18
  } = composeStories(stories)
18
19
 
20
+ /**
21
+ * `mountStory`, then every CodeMirror document in it parsed to the
22
+ * end, so the decorations each test reads are drawn before it reads
23
+ * them — see `finishCodeMirrorParsing` for why that is not already
24
+ * true on a loaded runner.
25
+ *
26
+ * The `findBy` and `waitFor` calls below predate this barrier and
27
+ * stay. After it they resolve on their first look; the ones that
28
+ * follow a tick still wait on the round trip through the consumer.
29
+ */
30
+ const mountParsed = async (
31
+ story: Parameters<typeof mountStory>[0],
32
+ ): ReturnType<typeof mountStory> => {
33
+ const mounted = await mountStory(story)
34
+
35
+ finishCodeMirrorParsing(mounted.canvasElement)
36
+
37
+ return mounted
38
+ }
39
+
19
40
  /**
20
41
  * The gap this component was built to close, as a red/green fact.
21
42
  *
@@ -26,7 +47,7 @@ const {
26
47
  * there is the fix.
27
48
  */
28
49
  test("there is no toolbar, not a hidden one", async () => {
29
- const { canvas } = await mountStory(Playground)
50
+ const { canvas } = await mountParsed(Playground)
30
51
 
31
52
  await expect(canvas.queryAllByRole("toolbar")).toEqual([])
32
53
 
@@ -47,7 +68,7 @@ test("there is no toolbar, not a hidden one", async () => {
47
68
  * asserted together.
48
69
  */
49
70
  test("it is an article whose headings are headings", async () => {
50
- const { canvas } = await mountStory(Playground)
71
+ const { canvas } = await mountParsed(Playground)
51
72
 
52
73
  const article = expectAgentDrivable(canvas, {
53
74
  name: "Description",
@@ -87,7 +108,7 @@ test("it is an article whose headings are headings", async () => {
87
108
  * the same task boxes, the same autolink.
88
109
  */
89
110
  test("it renders what the editor renders", async () => {
90
- const { canvas } = await mountStory(SameAsTheEditor)
111
+ const { canvas } = await mountParsed(SameAsTheEditor)
91
112
 
92
113
  // ⚠️ WAIT FOR THE COUNT, not for "a table".
93
114
  //
@@ -158,7 +179,7 @@ test("it renders what the editor renders", async () => {
158
179
  * copy and open.
159
180
  */
160
181
  test("a link is a real anchor in the tab order", async () => {
161
- const { canvas } = await mountStory(Interactive)
182
+ const { canvas } = await mountParsed(Interactive)
162
183
 
163
184
  // Markdown decorations arrive after the editor's asynchronous parse.
164
185
  // Wait for the link before checking its accessibility and keyboard behavior.
@@ -203,7 +224,7 @@ test("a link is a real anchor in the tab order", async () => {
203
224
  * on the editors.
204
225
  */
205
226
  test("a checkbox is inert until a consumer says where the tick goes", async () => {
206
- const { canvas } = await mountStory(AllStates)
227
+ const { canvas } = await mountParsed(AllStates)
207
228
 
208
229
  const inert = await canvas.findByRole("checkbox", {
209
230
  name: "Photograph the current cabling",
@@ -240,7 +261,7 @@ test("a checkbox is inert until a consumer says where the tick goes", async () =
240
261
  */
241
262
  test("hostile markdown renders as characters, not as behaviour", async () => {
242
263
  const { canvas, canvasElement } =
243
- await mountStory(HostileMarkdown)
264
+ await mountParsed(HostileMarkdown)
244
265
 
245
266
  // `findAllBy`: the links are CodeMirror decorations, drawn after the
246
267
  // first paint — the same race as the headings test above.
@@ -298,7 +319,7 @@ test("hostile markdown renders as characters, not as behaviour", async () => {
298
319
  * else noticing.
299
320
  */
300
321
  test("the text can be selected", async () => {
301
- const { canvas } = await mountStory(Playground)
322
+ const { canvas } = await mountParsed(Playground)
302
323
 
303
324
  const article = canvas.getByRole("article")
304
325
 
@@ -336,7 +357,7 @@ test("the text can be selected", async () => {
336
357
  * renders.
337
358
  */
338
359
  test("inline markup in link text does not drop the document to raw source", async () => {
339
- const { canvas } = await mountStory(NestedLinkText)
360
+ const { canvas } = await mountParsed(NestedLinkText)
340
361
 
341
362
  // The canary. This heading has nothing to do with links, and it
342
363
  // is what stopped rendering when the plugin died.
@@ -375,7 +396,7 @@ test.each([
375
396
  ])(
376
397
  "link text through %s is a reachable anchor",
377
398
  async (_case, name) => {
378
- const { canvas } = await mountStory(NestedLinkText)
399
+ const { canvas } = await mountParsed(NestedLinkText)
379
400
 
380
401
  // CodeMirror finishes its viewport decorations on a scheduled frame.
381
402
  // Wait for the accessible anchor rather than assuming mount means paint.
@@ -402,7 +423,7 @@ test.each([
402
423
  * survives a change to the base font size.
403
424
  */
404
425
  test("the document is set at prose leading", async () => {
405
- const { canvas } = await mountStory(Playground)
426
+ const { canvas } = await mountParsed(Playground)
406
427
 
407
428
  const article = canvas.getByRole("article")
408
429
 
@@ -421,7 +442,7 @@ test("the document is set at prose leading", async () => {
421
442
  * backticks comes out as a wall of emphasis nobody asked for.
422
443
  */
423
444
  test("a code span is smaller than the prose it sits in", async () => {
424
- const { canvas } = await mountStory(Playground)
445
+ const { canvas } = await mountParsed(Playground)
425
446
 
426
447
  const article = canvas.getByRole("article")
427
448
 
@@ -0,0 +1,47 @@
1
+ import { forceParsing } from "@codemirror/language"
2
+ import { EditorView } from "@codemirror/view"
3
+
4
+ /**
5
+ * Parse every CodeMirror document under `root` to its end, now, so the
6
+ * decorations a test asserts on are drawn before it looks.
7
+ *
8
+ * This is the readiness signal for anything CodeMirror decorates — a
9
+ * heading, a link, a task box, a table. Those are drawn from the
10
+ * syntax tree, and CodeMirror does **not** finish that tree on mount.
11
+ * It parses for about 20 ms when the state is created, and hands the
12
+ * rest to a background worker that waits at least 100 ms, and up to
13
+ * 500 ms, between slices. On a quiet machine the first 20 ms covers a
14
+ * story's document. On a shared CI runner the same 20 ms of wall time
15
+ * covers less of it, the worker takes over, and a `findBy` with
16
+ * Testing Library's 1 s default is a race against that schedule.
17
+ * `MarkdownView > a checkbox is inert until a consumer says where the
18
+ * tick goes` lost that race in the narrow window on 2026-10-13; three
19
+ * other tests in the file had already been given a `findBy` or a
20
+ * `waitFor` for the same reason.
21
+ *
22
+ * `forceParsing` runs the same parser to the end of the document and
23
+ * dispatches the finished tree, so the component's own decoration
24
+ * passes run exactly as they would after the worker — only without
25
+ * the wait. It is not a fake: nothing in the component is stubbed.
26
+ *
27
+ * The budget is unbounded because a story's document is a few dozen
28
+ * lines; a parse that does not finish is a hang the test's own
29
+ * timeout reports.
30
+ */
31
+ export const finishCodeMirrorParsing = (
32
+ root: ParentNode,
33
+ ): void => {
34
+ for (const element of root.querySelectorAll<HTMLElement>(
35
+ ".cm-editor",
36
+ )) {
37
+ const view = EditorView.findFromDOM(element)
38
+
39
+ if (view !== null) {
40
+ forceParsing(
41
+ view,
42
+ view.state.doc.length,
43
+ Number.POSITIVE_INFINITY,
44
+ )
45
+ }
46
+ }
47
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A motion length no test outlives: an hour.
3
+ *
4
+ * The motion tests assert what is true **while** something moves — an
5
+ * item still entering, a row still leaving, a slide still in flight —
6
+ * right after a `userEvent` call. Each of those calls is a round trip
7
+ * to the browser driver, and on a shared CI runner one round trip has
8
+ * no upper bound. A 600 ms or 1 500 ms "slow" motion only made the
9
+ * window wider. `useListMotion > an item that moves while it is still
10
+ * entering slides from where it is shown` lost it in the narrow window
11
+ * on 2026-11-14 (run 43611154547): two clicks took longer than the
12
+ * 600 ms enter, and the item had finished entering before the test
13
+ * looked.
14
+ *
15
+ * Held this long, a motion is still running when the test reads it,
16
+ * whatever the machine is doing. A test that needs the motion **over**
17
+ * says so with `finishMotion`, rather than waiting for a clock.
18
+ */
19
+ export const HELD_MOTION = "3600s"
20
+
21
+ /**
22
+ * End every finite animation and transition on `element` and beneath
23
+ * it, now.
24
+ *
25
+ * `Animation.finish()` jumps the animation to its end, and the browser
26
+ * then dispatches the same `animationend` or `transitionend` it would
27
+ * have dispatched at the natural end. The hooks under test listen for
28
+ * exactly those, so this exercises their real path — it only removes
29
+ * the wait. The events arrive on the next animation frame, so assert
30
+ * on what they cause with `waitFor`.
31
+ *
32
+ * Infinite animations, such as a spinner's, are skipped, because
33
+ * `finish()` throws on them and nothing waits for them to end.
34
+ */
35
+ export const finishMotion = (element: Element): void => {
36
+ for (const animation of element.getAnimations({
37
+ subtree: true,
38
+ })) {
39
+ if (
40
+ animation.effect?.getComputedTiming().endTime !==
41
+ Number.POSITIVE_INFINITY
42
+ ) {
43
+ animation.finish()
44
+ }
45
+ }
46
+ }
@@ -0,0 +1,93 @@
1
+ import type { RefCallback } from "react"
2
+ import { useCallback, useState } from "react"
3
+
4
+ /**
5
+ * Whether the photo at `src` has failed, and the two props an `<img>`
6
+ * needs so that every failure is noticed.
7
+ *
8
+ * Shared by `Avatar` and `PortraitTiles`, whose whole promise about a
9
+ * photo is the same: it is never the only thing, so a 404, an expired
10
+ * signed URL, or a wrong content type lands on the initials rather than
11
+ * on a broken-image glyph.
12
+ *
13
+ * ### The failed URL, not a boolean
14
+ *
15
+ * A `hasFailed` boolean has to be *reset* when `src` changes, which is
16
+ * an effect syncing a prop into state — the shape this library refuses
17
+ * ([decision](../../../docs/decisions/2026-07-29-logic-hooks-are-uncontrolled.md)).
18
+ * Storing the URL that failed makes the comparison derive the answer:
19
+ * a new URL gets its own attempt, and a re-render never resurrects a
20
+ * dead one. `PortraitTiles` kept a boolean, so a tile whose photo
21
+ * failed showed initials for the rest of its life, even after the
22
+ * caller passed a working URL.
23
+ *
24
+ * ### `onError` alone misses a failure that happened first
25
+ *
26
+ * React attaches `onError` before it sets `src` on an image it creates,
27
+ * so a client render never misses the event. A **server-rendered**
28
+ * image is different. The browser starts loading it while it parses
29
+ * the HTML, and it can fail before `hydrateRoot` attaches the listener.
30
+ * React does not set `src` again when it hydrates an image, so the
31
+ * `error` event is never repeated, and the broken glyph stays.
32
+ *
33
+ * The ref closes that gap. When React attaches it, an image that is
34
+ * already `complete` has already answered, so `decode()` is asked for
35
+ * the answer again: it rejects for a broken image and resolves for a
36
+ * loaded one. An image still loading is not `complete`, and its answer
37
+ * arrives through `onError` as usual.
38
+ *
39
+ * ⚠️ `decode()` **also rejects when a newer `src` supersedes it**, with
40
+ * the same `EncodingError` a broken image gets. So a rejection counts
41
+ * only while this ref is still the one attached — React runs the
42
+ * cleanup below when the ref detaches or `src` changes — and only
43
+ * while the element still shows that `src` and has finished with it.
44
+ * Without the guard, a picture that was swapped out mid-decode was
45
+ * marked dead, and coming back to it showed the initials.
46
+ */
47
+ export const useImageFailure = (
48
+ src: string | undefined,
49
+ ): {
50
+ hasFailed: boolean
51
+ imageProps: {
52
+ onError: () => void
53
+ ref: RefCallback<HTMLImageElement>
54
+ }
55
+ } => {
56
+ const [failedSrc, setFailedSrc] = useState<
57
+ string | undefined
58
+ >(undefined)
59
+
60
+ const onError = useCallback(() => {
61
+ setFailedSrc(src)
62
+ }, [src])
63
+
64
+ const ref = useCallback(
65
+ (image: HTMLImageElement | null) => {
66
+ if (image === null || !image.complete) {
67
+ return
68
+ }
69
+
70
+ let isAttached = true
71
+
72
+ image.decode().catch(() => {
73
+ if (
74
+ isAttached &&
75
+ image.complete &&
76
+ image.getAttribute("src") === src
77
+ ) {
78
+ setFailedSrc(src)
79
+ }
80
+ })
81
+
82
+ return () => {
83
+ isAttached = false
84
+ }
85
+ },
86
+ [src],
87
+ )
88
+
89
+ return {
90
+ hasFailed: src !== undefined && failedSrc === src,
91
+ imageProps: { onError, ref },
92
+ }
93
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Resolve once every `<img>` under `root` has **finished**: loaded, or
3
+ * failed.
4
+ *
5
+ * This is the readiness signal for a test about an image, and it has
6
+ * no clock of its own. A `waitFor` around "the broken photo is gone"
7
+ * puts Testing Library's 1 s default on the **network**: the browser
8
+ * has to ask the dev server for the file and hear back 404 before
9
+ * `onError` can run. On a quiet machine that is a few milliseconds.
10
+ * On a shared CI runner, with four browser windows and the whole
11
+ * suite going through one Vite server, it is whenever that server
12
+ * gets to it — `Avatar > a photo that fails falls back to the
13
+ * initials` failed in the ultrawide window on the first run of #427
14
+ * with the `<img>` still in place after 1.37 s, and passed on the
15
+ * re-run. `PortraitTiles` had already hit the same wall, and had
16
+ * been given five seconds instead of a signal.
17
+ *
18
+ * So the wait is on the browser's own answer instead: the `load` or
19
+ * `error` event, or `complete` when that answer arrived before the
20
+ * test looked. `complete` is `true` for a **broken** image as well as
21
+ * a loaded one, which is the property this relies on.
22
+ *
23
+ * The listeners are added after the component's own, so a component
24
+ * that handles `onError` has already run its handler by the time this
25
+ * resolves. What is left is the component's own re-render, which a
26
+ * plain `waitFor` covers — that is page work, not network.
27
+ *
28
+ * The only budget left is the test's own timeout. An image that never
29
+ * finishes, such as a `loading="lazy"` one off-screen, holds the test
30
+ * until then; no story in this library has one.
31
+ */
32
+ export const waitForImagesToFinish = async (
33
+ root: ParentNode,
34
+ ): Promise<void> => {
35
+ await Promise.all(
36
+ Array.from(root.querySelectorAll("img"), (image) =>
37
+ waitForImageToFinish(image),
38
+ ),
39
+ )
40
+ }
41
+
42
+ const waitForImageToFinish = (
43
+ image: HTMLImageElement,
44
+ ): Promise<void> =>
45
+ new Promise((resolve) => {
46
+ if (image.complete) {
47
+ resolve()
48
+
49
+ return
50
+ }
51
+
52
+ const finish = () => {
53
+ image.removeEventListener("error", finish)
54
+ image.removeEventListener("load", finish)
55
+
56
+ resolve()
57
+ }
58
+
59
+ image.addEventListener("error", finish)
60
+ image.addEventListener("load", finish)
61
+ })