@cloudlet/toast 1.4.0 → 1.5.0

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 (83) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +3 -0
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +19 -15
  5. package/dist/agent.js.map +1 -1
  6. package/dist/center-react.d.ts +286 -0
  7. package/dist/center-react.d.ts.map +1 -0
  8. package/dist/center-react.js +2 -0
  9. package/dist/center.d.ts +3 -0
  10. package/dist/center.d.ts.map +1 -0
  11. package/dist/center.js +1 -0
  12. package/dist/core/agent-port.d.ts +2 -0
  13. package/dist/core/agent-port.d.ts.map +1 -1
  14. package/dist/core/agent-port.js +3 -0
  15. package/dist/core/agent-port.js.map +1 -1
  16. package/dist/react/card.d.ts +4 -0
  17. package/dist/react/card.d.ts.map +1 -1
  18. package/dist/react/card.js +3 -8
  19. package/dist/react/card.js.map +1 -1
  20. package/dist/react/center-backdrop.d.ts +69 -0
  21. package/dist/react/center-backdrop.d.ts.map +1 -0
  22. package/dist/react/center-backdrop.js +81 -0
  23. package/dist/react/center-backdrop.js.map +1 -0
  24. package/dist/react/center-clear.d.ts +16 -0
  25. package/dist/react/center-clear.d.ts.map +1 -0
  26. package/dist/react/center-clear.js +24 -0
  27. package/dist/react/center-clear.js.map +1 -0
  28. package/dist/react/center-gestures.d.ts +47 -0
  29. package/dist/react/center-gestures.d.ts.map +1 -0
  30. package/dist/react/center-gestures.js +74 -0
  31. package/dist/react/center-gestures.js.map +1 -0
  32. package/dist/react/center-motion.d.ts +174 -0
  33. package/dist/react/center-motion.d.ts.map +1 -0
  34. package/dist/react/center-motion.js +344 -0
  35. package/dist/react/center-motion.js.map +1 -0
  36. package/dist/react/center.d.ts +15 -0
  37. package/dist/react/center.d.ts.map +1 -0
  38. package/dist/react/center.js +1287 -0
  39. package/dist/react/center.js.map +1 -0
  40. package/dist/react/focus.d.ts +7 -0
  41. package/dist/react/focus.d.ts.map +1 -0
  42. package/dist/react/focus.js +14 -0
  43. package/dist/react/focus.js.map +1 -0
  44. package/dist/react/gestures.d.ts +33 -2
  45. package/dist/react/gestures.d.ts.map +1 -1
  46. package/dist/react/gestures.js +181 -149
  47. package/dist/react/gestures.js.map +1 -1
  48. package/dist/react/host.d.ts.map +1 -1
  49. package/dist/react/host.js +287 -283
  50. package/dist/react/host.js.map +1 -1
  51. package/dist/react/motion.d.ts +18 -11
  52. package/dist/react/motion.d.ts.map +1 -1
  53. package/dist/react/motion.js +6 -3
  54. package/dist/react/motion.js.map +1 -1
  55. package/dist/react/reduced.d.ts +24 -0
  56. package/dist/react/reduced.d.ts.map +1 -0
  57. package/dist/react/reduced.js +35 -0
  58. package/dist/react/reduced.js.map +1 -0
  59. package/dist/react/zoom.d.ts +12 -0
  60. package/dist/react/zoom.d.ts.map +1 -0
  61. package/dist/react/zoom.js +21 -0
  62. package/dist/react/zoom.js.map +1 -0
  63. package/dist/react.d.ts +4 -0
  64. package/dist/react.d.ts.map +1 -1
  65. package/dist/styles.css +1 -1
  66. package/package.json +2 -1
  67. package/src/agent.ts +11 -6
  68. package/src/center-react.ts +300 -0
  69. package/src/center.ts +27 -0
  70. package/src/core/agent-port.ts +3 -0
  71. package/src/react/card.tsx +5 -6
  72. package/src/react/center-backdrop.tsx +151 -0
  73. package/src/react/center-clear.ts +56 -0
  74. package/src/react/center-gestures.ts +143 -0
  75. package/src/react/center-motion.ts +504 -0
  76. package/src/react/center.tsx +1557 -0
  77. package/src/react/focus.ts +18 -0
  78. package/src/react/gestures.ts +127 -37
  79. package/src/react/host.tsx +17 -5
  80. package/src/react/motion.ts +16 -9
  81. package/src/react/reduced.ts +52 -0
  82. package/src/react/zoom.ts +26 -0
  83. package/src/react.ts +4 -0
@@ -0,0 +1,1557 @@
1
+ import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, version } from 'react';
2
+ import type { MouseEvent as ReactMouseEvent, ReactElement, ReactNode, RefObject } from 'react';
3
+ import { createPortal } from 'react-dom';
4
+ import type {
5
+ NotificationCenterLabels, NotificationCenterOpenOptions, NotificationCenterPart, NotificationCenterProps, NotificationItem, NotificationParts,
6
+ UseNotificationCenterResult,
7
+ } from '../center-react.js';
8
+ import { glyph, glyphs } from './card.js';
9
+ import { appleEngine, BACKDROP_BLURS, BACKDROP_LAYERS, BACKDROP_SCROLL, CenterBackdropLayers, resolveBackdrop, resolveCenterBackdrop, useReducedTransparency, useScrollTint } from './center-backdrop.js';
10
+ import { attachCenterGestures } from './center-gestures.js';
11
+ import { useTwoStepClear } from './center-clear.js';
12
+ import type { TwoStepClear } from './center-clear.js';
13
+ import { cascadeDelay, createCenterMotion, LAG_CARDS, resolveCenterMotion, restClip, stackLook, stackVisual } from './center-motion.js';
14
+ import type { CenterMotion, StackBox } from './center-motion.js';
15
+ import { focusIfVisible } from './focus.js';
16
+ import { watchReducedMotion } from './reduced.js';
17
+
18
+ // The notification center's panel and the hook for the app's buttons. The panel shows the app's
19
+ // own list of notifications: it keeps no notification of its own and never changes the list;
20
+ // dismissing, clearing, actions and reading go back to the app through callbacks, and each new
21
+ // array is laid out against the previous one. It is a non-modal dialog portalled into
22
+ // `document.body`; a closed center renders nothing once its drawer has left, and so do the server
23
+ // and the first client render.
24
+ //
25
+ // The drawer slides in from its edge and out on one interruptible position spring, the cards
26
+ // trailing each other; a card that arrives while the center is open grows in at the top, one the
27
+ // app took out leaves as an inert copy while the others move to their places. Every frame is
28
+ // written through the panel's own CSSOM rules, never a style attribute. A closing panel is inert
29
+ // and hidden from assistive technology at once; it leaves the document when its drawer has left.
30
+ //
31
+ // Two fingers or a finger towards the edge drag the drawer shut; away from the edge on a card they
32
+ // ask the app to dismiss it (react/center-gestures.ts). The list scrolls natively.
33
+ //
34
+ // Notifications with one `group` form a group: two or more are a stack that a click expands into
35
+ // its cards under a heading row, and "Show less" collapses again. Its cards spread out of the stack
36
+ // and gather back into it on the stack's springs, from where they are and as fast as they go, so a
37
+ // click mid-way turns them; the heading row and the button under the stack swap with a blur. Every
38
+ // group is collapsed again when the center opens.
39
+ //
40
+ // A center has as many buttons as the app spreads the hook's props on. While it is open the panel
41
+ // owns Escape (focus in it, on one of its buttons or on the body) and a primary press outside it
42
+ // and its buttons closes it, letting the press through to the page. Focus goes to its heading when
43
+ // it opens; when it closes from inside, back to the button that opened it, else to what had focus
44
+ // before, else to its first button. A notification that arrives while it is open is spoken in its
45
+ // own polite live region.
46
+
47
+ const kinds: Record<string, string> = { success: 'Success', error: 'Error', info: 'Info', warning: 'Warning', loading: 'In progress' };
48
+ const MINUTE = 60_000;
49
+ const HOUR = 60 * MINUTE;
50
+ const DAY = 24 * HOUR;
51
+ /** A card's time is redrawn this often while the center is open. */
52
+ const TICK = 30_000;
53
+ /** Arrivals are spoken together after this quiet window, as in the Toaster's announcer. */
54
+ const ANNOUNCE = 300;
55
+ /**
56
+ * A swiped card's fling is used by a copy that leaves this soon after the swipe asked to dismiss it,
57
+ * also once the card has sprung back to its place.
58
+ */
59
+ const FLING_WINDOW = 600;
60
+
61
+ const dates = new Map<string, Intl.DateTimeFormat>();
62
+ /** "Nov 23" in the document's language; an unknown language falls back to the default one. */
63
+ function shortDate(time: number, lang: string): string {
64
+ let format = dates.get(lang);
65
+ if (!format) {
66
+ try { format = new Intl.DateTimeFormat(lang || undefined, { month: 'short', day: 'numeric' }); }
67
+ catch { format = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' }); }
68
+ dates.set(lang, format);
69
+ }
70
+ return format.format(time);
71
+ }
72
+ const relative = (lang: string) => (time: number, now: number) => {
73
+ if (!Number.isFinite(time)) return '';
74
+ const age = Math.max(0, now - time);
75
+ if (age < MINUTE) return 'now';
76
+ if (age < HOUR) return `${Math.floor(age / MINUTE)}m`;
77
+ if (age < DAY) return `${Math.floor(age / HOUR)}h`;
78
+ if (age < 7 * DAY) return `${Math.floor(age / DAY)}d`;
79
+ return shortDate(time, lang);
80
+ };
81
+
82
+ export const defaultCenterLabels: NotificationCenterLabels = {
83
+ title: 'Notifications', close: 'Close notifications', clear: 'Clear notification', empty: 'No notifications',
84
+ kind: kind => kinds[kind] ?? '', unread: 'Unread', time: relative(''),
85
+ group: key => key, more: (label, count) => `${label} · ${count} more`, stack: (label, count) => `${label}, ${count} notifications`,
86
+ showLess: 'Show less',
87
+ clearGroup: 'Clear', clearGroupConfirm: count => `Clear ${count}`, clearStack: label => `Clear ${label}`,
88
+ clearAll: 'Clear all', clearAllConfirm: count => `Clear ${count}`,
89
+ };
90
+
91
+ /**
92
+ * What the hook and the panel share for one center: the panel's id for `aria-controls`, the
93
+ * center's buttons, the one whose click opened it (for focus to come back to), and its state.
94
+ */
95
+ interface CenterLink {
96
+ readonly id: string;
97
+ readonly buttons: Set<HTMLElement>;
98
+ opener: HTMLElement | null;
99
+ readonly isOpen: () => boolean;
100
+ readonly request: (open: boolean) => void;
101
+ }
102
+ /** By the hook's `setOpen`, the one function of its result that never changes. */
103
+ const links = new WeakMap<object, CenterLink>();
104
+
105
+ /** The center's buttons: the elements a hook's ref holds. One that left the document is not a button. */
106
+ function centerButtons(link: CenterLink): HTMLElement[] {
107
+ return [...link.buttons].filter(element => element.isConnected);
108
+ }
109
+ /** The same, in the document's order. */
110
+ function buttonsInOrder(link: CenterLink): HTMLElement[] {
111
+ return centerButtons(link).sort((a, b) => a.compareDocumentPosition(b) & a.DOCUMENT_POSITION_FOLLOWING ? -1 : 1);
112
+ }
113
+
114
+ /**
115
+ * The ref and the click of one `useNotificationCenter()`. Every element the ref is given is a
116
+ * button of the center until the ref lets it go, so the same props work on several buttons.
117
+ *
118
+ * React takes an element back by calling the ref with `null`, which does not say which element, and
119
+ * a ref function of the app that changes at every render lets the button go and gives it back in
120
+ * the same commit. So a `null` is settled once the commit is over: the elements that came back
121
+ * stay; else the hook's only button goes, or all of them when as many `null`s came as it holds
122
+ * buttons; short of that the one that left is told from the others by having left the document, or,
123
+ * when the others came back in the commit, by not coming back. A ref of the app that never passes `null` on leaves its element to that last rule alone.
124
+ *
125
+ * React 19 and later call the cleanup a ref returns in place of `null`, which names the element: the
126
+ * hook's own ref returns one there, so a button that keeps its place in the document but loses the
127
+ * props is let go at once. React 18 would warn about the returned function, so it gets none.
128
+ */
129
+ function connectButtons(link: CenterLink) {
130
+ const own = link.buttons;
131
+ /** `null`s heard in this commit that no element has come back for. */
132
+ let released = 0;
133
+ /** Elements given back in this commit after a `null`: the app's ref changes at every render. */
134
+ const returned = new Set<HTMLElement>();
135
+ let settling = false;
136
+ const settle = () => {
137
+ settling = false;
138
+ for (const element of [...own]) {
139
+ if (element.isConnected) continue;
140
+ own.delete(element);
141
+ released -= 1;
142
+ }
143
+ if (released > 0 && released >= own.size) own.clear();
144
+ else if (released > 0 && returned.size) {
145
+ // Every button that stayed came back: the ones that did not are those the `null`s let go.
146
+ const others = [...own].filter(element => !returned.has(element));
147
+ if (others.length === released) for (const element of others) own.delete(element);
148
+ }
149
+ released = 0;
150
+ returned.clear();
151
+ };
152
+ const ref = (element: HTMLElement | null): (() => void) | undefined => {
153
+ if (!element) {
154
+ released += 1;
155
+ if (!settling) queueMicrotask(settle);
156
+ settling = true;
157
+ return undefined;
158
+ }
159
+ // A button that is out of a live document has left for good: the center holds on to none. Its
160
+ // `null` in this commit, if it sent one, is settled with it.
161
+ if (element.isConnected) {
162
+ for (const other of [...own]) {
163
+ if (other.isConnected) continue;
164
+ own.delete(other);
165
+ released = Math.max(0, released - 1);
166
+ }
167
+ }
168
+ if (own.has(element)) released = Math.max(0, released - 1);
169
+ if (settling) returned.add(element);
170
+ own.add(element);
171
+ return cleanups ? () => { own.delete(element); } : undefined;
172
+ };
173
+ // React hands the click its event; a call without one is the hook's only button's.
174
+ const onClick = (event?: { readonly currentTarget: EventTarget | null }) => {
175
+ if (link.isOpen()) { link.request(false); return; }
176
+ const pressed = event?.currentTarget as HTMLElement | null | undefined;
177
+ link.opener = pressed ? own.has(pressed) ? pressed : null : own.size === 1 ? [...own][0]! : null;
178
+ link.request(true);
179
+ };
180
+ return { ref, onClick };
181
+ }
182
+
183
+ /** React 19 and later call a ref's returned cleanup in place of the ref with `null`. */
184
+ const cleanups = Number.parseInt(version, 10) >= 19;
185
+
186
+ /** The panel's id: React's `useId`, without the characters a CSS selector would need escaped. */
187
+ function usePanelId(): string {
188
+ return `cloudlet-center-${useId().replace(/[^\w-]/gu, '')}`;
189
+ }
190
+
191
+ /**
192
+ * The center's open state and the props of the app's buttons that open and close it: uncontrolled
193
+ * (`defaultOpen`) or controlled (`open` with `onOpenChange`).
194
+ */
195
+ export function useNotificationCenter(options?: NotificationCenterOpenOptions): UseNotificationCenterResult {
196
+ const [inner, setInner] = useState(() => options?.defaultOpen === true);
197
+ const controlled = typeof options?.open === 'boolean';
198
+ const open = controlled ? options!.open! : inner;
199
+ const state = useRef({ open, controlled, onOpenChange: options?.onOpenChange });
200
+ // Read by the callbacks, which never change: the latest props.
201
+ state.current = { open, controlled, onOpenChange: options?.onOpenChange };
202
+ const id = usePanelId();
203
+ const [link] = useState<CenterLink>(() => {
204
+ // A request already made in this task: one press can reach the close button and the press
205
+ // outside, and is asked once. It never stands for the app's answer, which may be no (a
206
+ // controlled `open` the app keeps): the next task reads the open state from the props again.
207
+ let pending: { readonly open: boolean } | null = null;
208
+ const isOpen = () => pending ? pending.open : state.current.open;
209
+ const request = (next: boolean) => {
210
+ if (next === isOpen()) return;
211
+ const current = state.current;
212
+ const made = { open: next };
213
+ pending = made;
214
+ if (!current.controlled) setInner(next);
215
+ current.onOpenChange?.(next);
216
+ // Queued after React's own render of the change, so the props say it by then.
217
+ queueMicrotask(() => { if (pending === made) pending = null; });
218
+ };
219
+ return { id, buttons: new Set(), opener: null, isOpen, request };
220
+ });
221
+ const { ref, onClick } = useMemo(() => connectButtons(link), [link]);
222
+ links.set(link.request, link);
223
+ return useMemo(() => ({
224
+ open,
225
+ setOpen: link.request,
226
+ triggerProps: { ref, 'aria-expanded': open, 'aria-controls': open ? link.id : undefined, 'aria-haspopup': 'dialog' as const, onClick },
227
+ }), [open, link, ref, onClick]);
228
+ }
229
+
230
+ const subscribeMount = () => () => {};
231
+ const clientMounted = () => true;
232
+ const serverMounted = () => false;
233
+
234
+ /**
235
+ * The notification center's panel. Mount it once, anywhere under the app; it portals itself. Its
236
+ * open state comes from `center` (`useNotificationCenter()`), else from its own `open`,
237
+ * `defaultOpen` and `onOpenChange`.
238
+ */
239
+ export function NotificationCenter(props: NotificationCenterProps): ReactElement | null {
240
+ const own = useNotificationCenter({ open: props.open, defaultOpen: props.defaultOpen, onOpenChange: props.onOpenChange });
241
+ const state = props.center ?? own;
242
+ // A center of another shape than the hook's result keeps its own `open` and `setOpen`.
243
+ const link = links.get(state.setOpen) ?? links.get(own.setOpen)!;
244
+ const open = state.open === true;
245
+ const mounted = useSyncExternalStore(subscribeMount, clientMounted, serverMounted);
246
+ // The panel stays while its drawer leaves; it goes when the closing spring has settled.
247
+ const [shown, setShown] = useState(false);
248
+ if (open && !shown) setShown(true);
249
+ const onClosed = useCallback(() => setShown(false), []);
250
+ // A center already open at the first client render is placed, not animated in.
251
+ const placeOpen = useRef(true);
252
+ useLayoutEffect(() => { if (mounted) placeOpen.current = false; });
253
+ if (!mounted || !(shown || open)) return null;
254
+ return createPortal(<Panel {...props} link={link} setOpen={state.setOpen} open={open} instant={placeOpen.current} onClosed={onClosed} />, document.body);
255
+ }
256
+
257
+ /** One notification as the panel lays it out. */
258
+ interface Entry {
259
+ readonly id: string;
260
+ readonly item: NotificationItem;
261
+ /** Milliseconds since the epoch; NaN for a time that is not one. */
262
+ readonly time: number;
263
+ /** The item's `group`; null without a nonempty one. */
264
+ readonly group: string | null;
265
+ }
266
+ /** Entries that share a group key, or one entry that stands alone (`key: null`). */
267
+ interface Group {
268
+ readonly key: string | null;
269
+ /** Newest first. */
270
+ readonly entries: readonly Entry[];
271
+ /** Only a group of two entries or more is ever expanded. */
272
+ readonly expanded: boolean;
273
+ }
274
+
275
+ const timeOf = (time: unknown) => typeof time === 'number' ? time : time instanceof Date ? time.getTime() : Number.NaN;
276
+ /**
277
+ * The list newest first (of two at the same time, or without one, the earlier in the array first);
278
+ * an item without a string id, or with the id of an earlier one, is left out.
279
+ */
280
+ function arrange(notifications: readonly NotificationItem[]): Entry[] {
281
+ const seen = new Set<string>();
282
+ const entries: { entry: Entry; index: number }[] = [];
283
+ (Array.isArray(notifications) ? notifications : []).forEach((item, index) => {
284
+ if (!item || typeof item !== 'object' || typeof item.id !== 'string' || seen.has(item.id)) return;
285
+ seen.add(item.id);
286
+ const group = typeof item.group === 'string' && item.group ? item.group : null;
287
+ entries.push({ entry: { id: item.id, item, time: timeOf(item.time), group }, index });
288
+ });
289
+ const key = (time: number) => Number.isNaN(time) ? -Infinity : time;
290
+ entries.sort((a, b) => key(b.entry.time) - key(a.entry.time) || a.index - b.index);
291
+ return entries.map(({ entry }) => entry);
292
+ }
293
+ /** The entries gathered by their group, each group where its newest entry stands. */
294
+ function gather(entries: readonly Entry[], expanded: ReadonlySet<string>): Group[] {
295
+ const groups: { key: string | null; entries: Entry[] }[] = [];
296
+ const byKey = new Map<string, Entry[]>();
297
+ for (const entry of entries) {
298
+ if (entry.group === null) { groups.push({ key: null, entries: [entry] }); continue; }
299
+ const members = byKey.get(entry.group);
300
+ if (members) { members.push(entry); continue; }
301
+ const fresh = [entry];
302
+ byKey.set(entry.group, fresh);
303
+ groups.push({ key: entry.group, entries: fresh });
304
+ }
305
+ return groups.map(group => ({ ...group, expanded: group.key !== null && group.entries.length >= 2 && expanded.has(group.key) }));
306
+ }
307
+
308
+ /** Controls that act once: a double click must not run an action or a clear twice. */
309
+ const ONE_SHOT = '[data-cloudlet-control="action"], [data-cloudlet-control="clear"], '
310
+ // A double click on a two-step button arms it and no more.
311
+ + '[data-cloudlet-control="clear-all"], [data-cloudlet-control="group-clear"], [data-cloudlet-control="stack-clear"]';
312
+
313
+ function subscribeScheme(listener: () => void) {
314
+ const media = globalThis.matchMedia?.('(prefers-color-scheme: dark)');
315
+ media?.addEventListener('change', listener);
316
+ return () => media?.removeEventListener('change', listener);
317
+ }
318
+ const darkScheme = () => globalThis.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false;
319
+
320
+ /** Adds the application's `classNames` part to an own `cloudlet-*` class, never replacing it. */
321
+ type PartClass = (part: NotificationCenterPart, own: string) => string;
322
+ function partClasses(classNames: NotificationCenterProps['classNames']): PartClass {
323
+ return (part, own) => {
324
+ const extra = classNames?.[part];
325
+ return typeof extra === 'string' && extra.trim() ? `${own} ${extra.trim()}` : own;
326
+ };
327
+ }
328
+
329
+ type PanelProps = NotificationCenterProps & {
330
+ readonly link: CenterLink;
331
+ readonly setOpen: (open: boolean) => void;
332
+ readonly open: boolean;
333
+ /** Place the drawer open without motion when the panel mounts. */
334
+ readonly instant: boolean;
335
+ /** The closing spring settled: the panel can leave the document. */
336
+ readonly onClosed: () => void;
337
+ };
338
+
339
+ /** What a card's controls ask the app for; null where the app gave no callback for it. */
340
+ interface Requests {
341
+ readonly dismiss: ((id: string) => void) | null;
342
+ readonly clear: ((ids: readonly string[]) => void) | null;
343
+ readonly action: (id: string, actionId: string) => void;
344
+ }
345
+
346
+ function Panel(props: PanelProps) {
347
+ const { link, side, theme, dir, labels: custom, classNames, nonce, open, notifications } = props;
348
+ const rootRef = useRef<HTMLDivElement>(null);
349
+ // The app's reduced transparency (an ancestor's attribute) or `tint` draw the tone in place of blur.
350
+ const backdrop = resolveBackdrop(props.backdrop, useReducedTransparency(rootRef));
351
+ // The engine is read once, when the panel mounts.
352
+ const [apple] = useState(appleEngine);
353
+ const { layers, scrollTint } = resolveCenterBackdrop(props.motion?.overrides?.backdrop, apple);
354
+ const dark = useSyncExternalStore(subscribeScheme, darkScheme, () => false);
355
+ const headingRef = useRef<HTMLHeadingElement>(null);
356
+ const [now, setNow] = useState(Date.now);
357
+ useEffect(() => {
358
+ if (!open) return;
359
+ setNow(Date.now());
360
+ const timer = setInterval(() => setNow(Date.now()), TICK);
361
+ return () => clearInterval(timer);
362
+ }, [open]);
363
+ // The callbacks of the latest render, behind functions that never change.
364
+ const latest = useRef(props);
365
+ latest.current = props;
366
+ const requests = useMemo(() => ({
367
+ dismiss: (id: string) => {
368
+ const { onDismiss, onClear } = latest.current;
369
+ if (onDismiss) onDismiss(id); else onClear?.([id]);
370
+ },
371
+ clear: (ids: readonly string[]) => {
372
+ const { onDismiss, onClear } = latest.current;
373
+ if (onClear) onClear(ids); else if (onDismiss) for (const id of ids) onDismiss(id);
374
+ },
375
+ action: (id: string, actionId: string) => latest.current.onAction?.(id, actionId),
376
+ }), []);
377
+ const can: Requests = {
378
+ dismiss: props.onDismiss || props.onClear ? requests.dismiss : null,
379
+ clear: props.onClear || props.onDismiss ? requests.clear : null,
380
+ action: requests.action,
381
+ };
382
+ const entries = useMemo(() => arrange(notifications), [notifications]);
383
+ // Expanded groups, all collapsed again at each opening.
384
+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());
385
+ const [wasOpen, setWasOpen] = useState(open);
386
+ if (wasOpen !== open) {
387
+ setWasOpen(open);
388
+ if (open && expanded.size) setExpanded(new Set());
389
+ }
390
+ // A group that left or shrank to one notification is no longer expanded when it comes back.
391
+ const stale = [...expanded].filter(key => entries.filter(entry => entry.group === key).length < 2);
392
+ if (stale.length) setExpanded(new Set([...expanded].filter(key => !stale.includes(key))));
393
+ const groups = useMemo(() => gather(entries, expanded), [entries, expanded]);
394
+ const keys = useMotionKeys(entries);
395
+
396
+ const doc = document;
397
+ const { styleRef, stackRef, listRef, exitsRef, leave, texts, folding, setBlur } = useDrawerMotion(props, rootRef, keys, can.dismiss !== null);
398
+ useScrollTint(open, backdrop === 'blur' && scrollTint, rootRef, setBlur);
399
+ useCenterBehaviour(open, props.instant, link, props.setOpen, rootRef, headingRef);
400
+ const groupKey = useGroupKeys(groups);
401
+ const toggle = useGroupToggle(groups, setExpanded, rootRef, groupKey);
402
+ const lostFocus = useRefocus(groups, groupKey, keys, rootRef, headingRef);
403
+ // The two-step buttons shown in this render: Clear all from two notifications, and per group of
404
+ // two or more its heading row's Clear (expanded) or its stack's clear button (collapsed).
405
+ const clearable = can.clear !== null && entries.length >= 2;
406
+ const present = can.clear === null ? [] : groups.flatMap(group => group.key === null || group.entries.length < 2 ? [] : [`${group.expanded ? 'group' : 'stack'}:${group.key}`]);
407
+ if (clearable) present.push(ALL);
408
+ const twoStep = useTwoStepClear(present, open);
409
+ useArrivals(open, entries, keys, rootRef);
410
+ useRead(open, entries, latest);
411
+ const lang = doc.documentElement.lang;
412
+ const labels: NotificationCenterLabels = { ...defaultCenterLabels, time: relative(lang), ...custom };
413
+ function format<Args extends readonly unknown[]>(formatter: (...args: Args) => string, fallback: (...args: Args) => string, ...args: Args): string {
414
+ try {
415
+ const text = formatter(...args);
416
+ if (typeof text !== 'string') throw new TypeError('Label formatter must return a string');
417
+ return text;
418
+ } catch {
419
+ return fallback(...args);
420
+ }
421
+ }
422
+ const sideValue = side === 'left' ? 'left' : 'right';
423
+ const themeValue = theme === 'light' || theme === 'dark' ? theme : 'system';
424
+ const direction = dir ?? (doc.documentElement.dir === 'rtl' ? 'rtl' : 'ltr');
425
+ const part = partClasses(classNames);
426
+ const id = link.id;
427
+
428
+ const onClickCapture = (event: ReactMouseEvent) => {
429
+ const target = (event.target as Element).closest('button');
430
+ if (target?.matches(ONE_SHOT) && event.detail > 1) {
431
+ event.preventDefault();
432
+ event.stopPropagation();
433
+ }
434
+ };
435
+ const confirmAll = format(labels.clearAllConfirm, defaultCenterLabels.clearAllConfirm, entries.length);
436
+ const armedGroup = twoStep.armed?.replace(/^(?:group|stack):/u, '');
437
+ const armedCount = twoStep.armed === null || twoStep.armed === ALL ? 0 : groups.find(group => group.key === armedGroup)?.entries.length ?? 0;
438
+ // What the armed button would clear, said once by the polite status as the Island's Clear all does.
439
+ const status = twoStep.armed === null ? '' : twoStep.armed === ALL ? confirmAll : format(labels.clearGroupConfirm, defaultCenterLabels.clearGroupConfirm, armedCount);
440
+ const card = (entry: Entry, extra: { lag?: number; place?: StackPlace; level: 'h3' | 'h4'; when?: ReactElement }) =>
441
+ <Card key={`h:${entry.id}`} entry={entry} motionKey={keys.of(entry.id)} requests={can} render={props.renderNotification}
442
+ part={part} lostFocus={lostFocus} leave={leave}
443
+ kind={typeof entry.item.kind === 'string' ? format(labels.kind, defaultCenterLabels.kind, entry.item.kind) : ''}
444
+ time={format(labels.time, relative(lang), entry.time, now)} labels={labels} {...extra} />;
445
+
446
+ // A closing panel is gone for assistive technology at once (and inert, set with its drawer).
447
+ return <div ref={rootRef} id={id} className={part('center', 'cloudlet-host cloudlet-center')} role="dialog" aria-labelledby={`${id}-title`}
448
+ aria-hidden={open ? undefined : true}
449
+ data-cloudlet-center="" data-side={sideValue} data-theme={themeValue} data-resolved-theme={themeValue === 'system' ? dark ? 'dark' : 'light' : themeValue}
450
+ data-backdrop={backdrop} data-backdrop-layers={backdrop === 'blur' ? layers : undefined} dir={direction} onClickCapture={onClickCapture}>
451
+ <style ref={styleRef} nonce={nonce} data-cloudlet-center-motion="" />
452
+ <CenterBackdropLayers backdrop={backdrop} layers={layers} />
453
+ <div className="cloudlet-center-column">
454
+ <div className={part('header', 'cloudlet-center-header')}>
455
+ <h2 ref={headingRef} id={`${id}-title`} tabIndex={-1} className={part('heading', 'cloudlet-center-heading')}>{labels.title}</h2>
456
+ {clearable && <TwoStepButton control="clear-all" id={ALL} twoStep={twoStep} className={part('clear-all', 'cloudlet-clear cloudlet-center-clear-all')}
457
+ label={labels.clearAll} confirm={confirmAll} onClear={() => {
458
+ // The cards leave and the empty line takes their place: focus waits on the heading.
459
+ headingRef.current?.focus({ preventScroll: true });
460
+ can.clear?.(entries.map(entry => entry.id));
461
+ }} />}
462
+ <span role="status" className="cloudlet-live">{status}</span>
463
+ <button type="button" data-cloudlet-control="dismiss" className={part('dismiss', 'cloudlet-close cloudlet-center-dismiss')} aria-label={labels.close}
464
+ onClick={() => props.setOpen(false)}>{glyph('m4.5 4.5 7 7m0-7-7 7')}</button>
465
+ </div>
466
+ {/* No Tab stop of its own (Firefox gives every scroller one): every card holds its clear
467
+ button, so Tab reaches and scrolls the list card by card, right after the close button. */}
468
+ <div className="cloudlet-center-scroll" tabIndex={-1}>
469
+ <div ref={stackRef} className="cloudlet-center-stack">
470
+ {groups.length
471
+ ? <ul ref={listRef} className={part('list', 'cloudlet-center-list')}>{groups.map((group, index) => {
472
+ const lag = Math.min(index, LAG_CARDS);
473
+ if (group.key === null || group.entries.length < 2) return card(group.entries[0]!, { lag, level: 'h3' });
474
+ const label = format(labels.group, defaultCenterLabels.group, group.key);
475
+ const count = group.entries.length;
476
+ const clear = can.clear;
477
+ return <GroupItem key={`g:${group.key}`} group={group} motionKey={groupKey(group.key)} lag={lag} part={part} card={card}
478
+ name={format(labels.stack, defaultCenterLabels.stack, label, count)} label={label}
479
+ more={format(labels.more, defaultCenterLabels.more, label, count - 1)} showLess={labels.showLess} toggle={toggle}
480
+ clear={labels.clearGroup} clearStack={format(labels.clearStack, defaultCenterLabels.clearStack, label)}
481
+ confirm={format(labels.clearGroupConfirm, defaultCenterLabels.clearGroupConfirm, count)} twoStep={twoStep} lostFocus={lostFocus}
482
+ texts={texts} folding={folding} onClear={clear && (() => clear(group.entries.map(entry => entry.id)))} />;
483
+ })}</ul>
484
+ : <Empty className={part('empty', 'cloudlet-center-empty')} texts={texts}>{labels.empty}</Empty>}
485
+ {/* Cards that left the list leave from here as inert copies, outside the list and its order. */}
486
+ <div ref={exitsRef} className="cloudlet-center-exits" aria-hidden="true" />
487
+ </div>
488
+ </div>
489
+ </div>
490
+ </div>;
491
+ }
492
+
493
+ /**
494
+ * Motion keys by notification id: a card's key names its CSSOM rule and its motion channels, and
495
+ * ids are the app's own strings, which these never need escaping for. The key of an id that left
496
+ * the list is forgotten after the commit; one that comes back gets a new key.
497
+ */
498
+ interface MotionKeys {
499
+ readonly of: (id: string) => string;
500
+ /** The listed id a key stands for. */
501
+ readonly idOf: (key: string) => string | null;
502
+ }
503
+ function useMotionKeys(entries: readonly Entry[]): MotionKeys {
504
+ const [map] = useState(() => new Map<string, string>());
505
+ const [back] = useState(() => new Map<string, string>());
506
+ useLayoutEffect(() => {
507
+ const present = new Set(entries.map(entry => entry.id));
508
+ for (const [id, key] of map) if (!present.has(id)) { map.delete(id); back.delete(key); }
509
+ }, [entries, map, back]);
510
+ return useMemo(() => ({
511
+ of(id: string) {
512
+ let key = map.get(id);
513
+ if (key === undefined) { map.set(id, key = String(++nextMotionKey)); back.set(key, id); }
514
+ return key;
515
+ },
516
+ idOf: (key: string) => back.get(key) ?? null,
517
+ }), [map, back]);
518
+ }
519
+
520
+ /** The id of the header's Clear all among the two-step buttons; a group's are `group:` and `stack:` with its key. */
521
+ const ALL = 'all';
522
+
523
+ /**
524
+ * A two-step text button: both labels share one cell, so it keeps its width when it arms; armed it
525
+ * takes the error tint and its label says what the next press clears.
526
+ */
527
+ function TwoStepButton({ control, id, twoStep, className, label, confirm, onClear }: {
528
+ control: string; id: string; twoStep: TwoStepClear; className: string; label: string; confirm: string; onClear: () => void;
529
+ }) {
530
+ const armed = twoStep.armed === id;
531
+ return <button type="button" data-cloudlet-control={control} className={className} data-armed={armed}
532
+ onClick={() => twoStep.press(id, onClear)} onBlur={() => twoStep.disarm(id)}>
533
+ <span aria-hidden={armed || undefined}>{label}</span><span aria-hidden={!armed || undefined}>{confirm}</span>
534
+ </button>;
535
+ }
536
+
537
+ /** A card's place in a collapsed stack: its top card, one of the two edges under it, or hidden behind them. */
538
+ type StackPlace = 'top' | 'edge' | 'hidden';
539
+ /** Edges under the top card of a collapsed stack, at most. */
540
+ const EDGES = 2;
541
+
542
+ /**
543
+ * The panel's text that comes and goes with a group (its heading row, the button under its stack)
544
+ * and the empty line: shown with a blur once the panel stands (`reveal`), and leaving as an inert
545
+ * copy that blurs out where it stood (`leave`).
546
+ */
547
+ interface TextMotion { readonly reveal: (element: HTMLElement) => void; readonly leave: (element: HTMLElement) => void }
548
+ function useText<T extends HTMLElement>(texts: TextMotion): RefObject<T | null> {
549
+ const ref = useRef<T>(null);
550
+ useLayoutEffect(() => {
551
+ const element = ref.current;
552
+ if (!element) return;
553
+ texts.reveal(element);
554
+ return () => texts.leave(element);
555
+ }, [texts]);
556
+ return ref;
557
+ }
558
+ /** The reveal is done: the attribute goes, so a later change of the motion setting does not replay it. */
559
+ const revealed = (event: { target: EventTarget; currentTarget: Element }) => {
560
+ if (event.target === event.currentTarget) event.currentTarget.removeAttribute('data-cloudlet-reveal');
561
+ };
562
+
563
+ function Empty({ className, texts, children }: { className: string; texts: TextMotion; children: ReactNode }) {
564
+ const ref = useText<HTMLParagraphElement>(texts);
565
+ return <p ref={ref} className={className} data-cloudlet-lag="0" onAnimationEnd={revealed}>{children}</p>;
566
+ }
567
+
568
+ /** Elements that act on their own: a click on them in a group never turns its motion. */
569
+ const CONTROLS = 'button, a[href], input, textarea, select, label, summary, [contenteditable], [tabindex]';
570
+
571
+ /**
572
+ * A group of two notifications or more. Collapsed, it is a stack: the top card in full with its
573
+ * actions and fields inert, up to two edges under it with nothing to read, the rest hidden behind
574
+ * them, and a button that expands it, as a click anywhere on the stack does. Expanded, a heading
575
+ * row (the group's name with its count, and "Show less") stands over all its cards; both buttons
576
+ * collapse it, and so does a click on its cards while they are still spreading out of the stack.
577
+ * Its cards stay the same elements, in the same nested list, either way.
578
+ */
579
+ function GroupItem({ group, motionKey: key, lag, part, card, name, label, more, showLess, toggle, clear, clearStack, confirm, twoStep, lostFocus, texts, folding, onClear }: {
580
+ group: Group; motionKey: string; lag: number; part: PartClass;
581
+ card: (entry: Entry, extra: { place?: StackPlace; level: 'h3' | 'h4'; when?: ReactElement }) => ReactElement;
582
+ name: string; label: string; more: string; showLess: string; toggle: (key: string, expanded: boolean, from: Element) => void;
583
+ clear: string; clearStack: string; confirm: string; twoStep: TwoStepClear; lostFocus: RefObject<string | null>;
584
+ /** Null without a clear callback: the group has no two-step buttons. */
585
+ texts: TextMotion; folding: (key: string) => boolean; onClear: (() => void) | null;
586
+ }) {
587
+ const { expanded, entries } = group;
588
+ const groupKey = group.key!;
589
+ const set = (value: boolean) => (event: ReactMouseEvent) => toggle(groupKey, value, event.currentTarget);
590
+ const itemRef = useRef<HTMLLIElement>(null);
591
+ const last = useRef(entries);
592
+ last.current = entries;
593
+ // A group cleared with focus in its heading row hands focus on as its last card would: to what follows it.
594
+ useLayoutEffect(() => () => {
595
+ const item = itemRef.current;
596
+ if (lostFocus.current === null && item?.contains(item.ownerDocument.activeElement)) lostFocus.current = last.current[last.current.length - 1]!.id;
597
+ }, [lostFocus]);
598
+ const stackId = `stack:${groupKey}`;
599
+ const stackArmed = twoStep.armed === stackId;
600
+ // In place of the top card's time on hover and focus; armed, it grows into a pill that says what it clears.
601
+ const stackClear = onClear && <button type="button" data-cloudlet-control="stack-clear" data-armed={stackArmed}
602
+ className={part('stack-clear', 'cloudlet-close cloudlet-card-clear cloudlet-center-stack-clear')} aria-label={stackArmed ? confirm : clearStack}
603
+ onClick={event => { event.stopPropagation(); twoStep.press(stackId, onClear); }} onBlur={() => twoStep.disarm(stackId)}>
604
+ {glyph('m4.5 4.5 7 7m0-7-7 7')}<span className="cloudlet-center-stack-clear-label" aria-hidden="true"><span>{confirm}</span></span>
605
+ </button>;
606
+ // A click on a collapsed stack, its top card or an edge, expands it; the button below is its keyboard way.
607
+ // The second click of a double click that collapsed the group lands here: it expands nothing. While
608
+ // the cards of an expanded group still spread out, a click on them (not on a control) turns them back.
609
+ const onListClick = (event: ReactMouseEvent) => {
610
+ if (event.detail > 1) return;
611
+ if (!expanded) set(true)(event);
612
+ else if (folding(key) && !event.currentTarget.contains((event.target as Element).closest(CONTROLS))) set(false)(event);
613
+ };
614
+ return <li ref={itemRef} className={part('group', 'cloudlet-center-group')} data-expanded={String(expanded)}
615
+ data-peeks={expanded ? undefined : Math.min(entries.length - 1, EDGES)} data-cloudlet-motion-key={key} data-cloudlet-lag={lag}>
616
+ <div role="group" aria-label={name} className="cloudlet-center-group-box">
617
+ {expanded && <GroupHeader className={part('group-header', 'cloudlet-center-group-header')} texts={texts}>
618
+ <h3 className="cloudlet-center-group-heading">
619
+ <button type="button" data-cloudlet-control="group-title" className={part('group-title', 'cloudlet-center-group-title')}
620
+ aria-expanded="true" onClick={set(false)}>
621
+ <span className="cloudlet-center-group-label">{label}</span> <span className="cloudlet-center-group-count">{entries.length}</span>
622
+ </button>
623
+ </h3>
624
+ <button type="button" data-cloudlet-control="show-less" className={part('show-less', 'cloudlet-action cloudlet-center-show-less')}
625
+ onClick={set(false)}>{showLess}</button>
626
+ {onClear && <TwoStepButton control="group-clear" id={`group:${groupKey}`} twoStep={twoStep} className={part('group-clear', 'cloudlet-clear cloudlet-center-group-clear')}
627
+ label={clear} confirm={confirm} onClear={onClear} />}
628
+ </GroupHeader>}
629
+ <ul className={part('group-list', 'cloudlet-center-group-list')} onClick={onListClick}>
630
+ {entries.map((entry, index) => card(entry, expanded ? { level: 'h4' }
631
+ : index > EDGES ? { place: 'hidden', level: 'h4' } : index ? { place: 'edge', level: 'h4' } : { place: 'top', level: 'h3', ...stackClear ? { when: stackClear } : {} }))}
632
+ </ul>
633
+ {!expanded && <MoreButton className={part('more', 'cloudlet-center-more')} texts={texts} onClick={set(true)}>{more}</MoreButton>}
634
+ </div>
635
+ </li>;
636
+ }
637
+
638
+ function GroupHeader({ className, texts, children }: { className: string; texts: TextMotion; children: ReactNode }) {
639
+ const ref = useText<HTMLDivElement>(texts);
640
+ return <div ref={ref} className={className} onAnimationEnd={revealed}>{children}</div>;
641
+ }
642
+
643
+ function MoreButton({ className, texts, onClick, children }: { className: string; texts: TextMotion; onClick: (event: ReactMouseEvent) => void; children: ReactNode }) {
644
+ const ref = useText<HTMLButtonElement>(texts);
645
+ return <button ref={ref} type="button" data-cloudlet-control="more" className={className} aria-expanded="false" onClick={onClick} onAnimationEnd={revealed}>{children}</button>;
646
+ }
647
+
648
+ /** A group's motion key (`g…`) names its CSSOM rule as a card's does; group keys are the app's strings. */
649
+ function useGroupKeys(groups: readonly Group[]) {
650
+ const keys = useRef(new Map<string, string>());
651
+ // Keys of groups that left are forgotten after the commit; a group that comes back gets a new one.
652
+ useLayoutEffect(() => {
653
+ const present = new Set(groups.map(group => group.key));
654
+ for (const key of keys.current.keys()) if (!present.has(key)) keys.current.delete(key);
655
+ }, [groups]);
656
+ return useCallback((key: string) => {
657
+ let value = keys.current.get(key);
658
+ if (value === undefined) keys.current.set(key, value = `g${++nextMotionKey}`);
659
+ return value;
660
+ }, []);
661
+ }
662
+
663
+ /**
664
+ * Expanding and collapsing a group as the person, at once. When the pressed control leaves with the
665
+ * change (or anything else in the group lost focus with it), focus goes to the group's name in its
666
+ * heading when it expanded and to the button under the stack when it collapsed; focus that stayed
667
+ * where it was is left alone, so a press of the pointer outside the group's controls moves nothing.
668
+ */
669
+ function useGroupToggle(groups: readonly Group[], setExpanded: (change: (expanded: ReadonlySet<string>) => ReadonlySet<string>) => void,
670
+ rootRef: RefObject<HTMLDivElement | null>, groupKey: (key: string) => string) {
671
+ const pending = useRef<{ key: string; expanded: boolean } | null>(null);
672
+ const listed = useRef(groups);
673
+ listed.current = groups;
674
+ useLayoutEffect(() => {
675
+ const target = pending.current;
676
+ pending.current = null;
677
+ const root = rootRef.current;
678
+ if (!target || !root) return;
679
+ const active = root.ownerDocument.activeElement;
680
+ if (active && active !== root.ownerDocument.body && active.isConnected) return;
681
+ const item = root.querySelector(`.cloudlet-center-list > [data-cloudlet-motion-key="${target.key}"]`);
682
+ focusIfVisible(item?.querySelector<HTMLElement>(target.expanded ? '.cloudlet-center-group-title' : '.cloudlet-center-more'));
683
+ });
684
+ return useCallback((key: string, expanded: boolean, from: Element) => {
685
+ const group = listed.current.find(item => item.key === key);
686
+ // Only a group of two or more expands, and only a change counts.
687
+ if (!group || group.entries.length < 2 || group.expanded === expanded) return;
688
+ const doc = from.ownerDocument;
689
+ const focused = !!from.closest('.cloudlet-center-group')?.contains(doc.activeElement);
690
+ setExpanded(current => {
691
+ const next = new Set(current);
692
+ if (expanded) next.add(key); else next.delete(key);
693
+ return next;
694
+ });
695
+ if (focused) pending.current = { key: groupKey(key), expanded };
696
+ }, [setExpanded, groupKey]);
697
+ }
698
+
699
+ /** A finite time outside the range of a date has no machine-readable form. */
700
+ function isoTime(time: number): string | undefined {
701
+ const date = new Date(time);
702
+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
703
+ }
704
+
705
+ let nextMotionKey = 0;
706
+
707
+ /** The status icon of a known kind, or the item's own icon; null without either. */
708
+ function StatusIcon({ item, part }: { item: NotificationItem; part: PartClass }) {
709
+ const { kind, icon } = item;
710
+ const known = kind === 'loading' || (typeof kind === 'string' && Object.hasOwn(glyphs, kind));
711
+ if ((icon === undefined || icon === null || icon === false) && !known) return null;
712
+ return <div className={part('icon', 'cloudlet-icon')} data-kind={kind} aria-hidden="true">
713
+ {icon !== undefined && icon !== null && icon !== false
714
+ ? <span className="cloudlet-glyph">{icon}</span>
715
+ : kind === 'loading'
716
+ ? <svg viewBox="0 0 16 16" className="cloudlet-glyph cloudlet-spinner"><circle cx="8" cy="8" r="5.5" strokeDasharray="22 13" /></svg>
717
+ : <svg viewBox="0 0 16 16" className="cloudlet-glyph"><path d={glyphs[kind as keyof typeof glyphs]} /></svg>}
718
+ </div>;
719
+ }
720
+
721
+ /**
722
+ * One card. In a collapsed stack (`place`) the top card shows the stack's clear button in place of its
723
+ * own (`when`) and keeps its actions inert, out of Tab and the accessibility tree, while its title and
724
+ * description read; an edge, and a card hidden behind the edges, is inert and hidden altogether. `lag`
725
+ * only on the list's own items: a group trails as one. `render` draws the content from the default parts.
726
+ */
727
+ function Card({ entry, motionKey: key, requests, render, part, lostFocus, leave, lag, place, level, when, kind, time, labels }: {
728
+ entry: Entry; motionKey: string; requests: Requests; render: NotificationCenterProps['renderNotification']; part: PartClass;
729
+ lostFocus: RefObject<string | null>;
730
+ leave: (key: string, item: HTMLLIElement) => void; lag?: number | undefined; place?: StackPlace | undefined; level: 'h3' | 'h4';
731
+ /** The top card of a collapsed stack: the stack's clear button in place of the card's own. */
732
+ when?: ReactElement | undefined;
733
+ kind: string; time: string; labels: NotificationCenterLabels;
734
+ }) {
735
+ const titleId = `${useId()}-title`;
736
+ const itemRef = useRef<HTMLLIElement>(null);
737
+ const { id, item } = entry;
738
+ // A layout cleanup runs before the item leaves the document: it can still see focus inside it,
739
+ // and its look, for the copy that leaves in its place.
740
+ useLayoutEffect(() => () => {
741
+ const element = itemRef.current;
742
+ if (element?.contains(element.ownerDocument.activeElement)) lostFocus.current = id;
743
+ if (element) leave(key, element);
744
+ }, [id, key, lostFocus, leave]);
745
+ // Native `inert` (React 18 has no prop for it), on every commit: the app's content may change.
746
+ useLayoutEffect(() => {
747
+ const element = itemRef.current;
748
+ if (!element) return;
749
+ element.toggleAttribute('inert', place === 'edge' || place === 'hidden');
750
+ for (const actions of element.querySelectorAll('.cloudlet-actions')) actions.toggleAttribute('inert', place === 'top');
751
+ });
752
+ const unread = item.read === false;
753
+ const Title = level;
754
+ const dismiss = () => requests.dismiss?.(id);
755
+ const action = (actionId: string) => requests.action(id, actionId);
756
+ const icon = <StatusIcon item={item} part={part} />;
757
+ const title = <Title id={titleId} tabIndex={-1} className={part('title', 'cloudlet-title')}>{item.title}</Title>;
758
+ const hasDescription = item.description !== undefined && item.description !== null && item.description !== false && item.description !== '';
759
+ const description = hasDescription ? <div className={part('description', 'cloudlet-description')}>
760
+ {typeof item.description === 'string' || typeof item.description === 'number' ? <p>{item.description}</p> : item.description}
761
+ </div> : null;
762
+ const buttons = Array.isArray(item.actions) ? item.actions.filter(button => button && typeof button.id === 'string') : [];
763
+ const actions = buttons.length ? <div className={part('actions', 'cloudlet-actions')}>
764
+ {buttons.map((button, index) => <button key={button.id} type="button" data-cloudlet-control="action"
765
+ className={index ? part('action', 'cloudlet-action') : `${part('action', 'cloudlet-action')} cloudlet-primary`}
766
+ onClick={() => action(button.id)}>{button.label}</button>)}
767
+ </div> : null;
768
+ const clock = <span className="cloudlet-when">
769
+ <time className={part('time', 'cloudlet-time')} dateTime={isoTime(entry.time)}>{time}</time>
770
+ {!place && requests.dismiss && <button type="button" data-cloudlet-control="clear" className={part('clear', 'cloudlet-close cloudlet-card-clear')}
771
+ aria-label={labels.clear} aria-describedby={titleId} onClick={dismiss}>{glyph('m4.5 4.5 7 7m0-7-7 7')}</button>}
772
+ {place === 'top' && when}
773
+ </span>;
774
+ const iconShown = item.icon !== undefined && item.icon !== null && item.icon !== false
775
+ || item.kind === 'loading' || (typeof item.kind === 'string' && Object.hasOwn(glyphs, item.kind));
776
+ const content = <>
777
+ <div className="cloudlet-card-head">
778
+ <div className="cloudlet-heading">{icon}{title}</div>
779
+ {clock}
780
+ </div>
781
+ {(description || actions) && <div className={part('body', 'cloudlet-body')} data-kind={item.kind}>{description}{actions}</div>}
782
+ </>;
783
+ const parts: NotificationParts = { icon: iconShown ? icon : null, title, description, actions, time: clock, titleId, dismiss, action, content };
784
+ return <li ref={itemRef} className={part('card', place === 'edge' ? `cloudlet-card ${part('edge', 'cloudlet-center-edge')}` : 'cloudlet-card')}
785
+ data-kind={item.kind} data-read={unread ? 'false' : undefined} data-icon={iconShown ? undefined : 'none'}
786
+ data-cloudlet-motion-key={key} data-cloudlet-lag={lag} data-cloudlet-place={place} aria-hidden={place === 'edge' || place === 'hidden' ? true : undefined}>
787
+ {/* Read before the title: the kind, then whether it is unread. */}
788
+ {kind && <span className="cloudlet-live">{kind}</span>}
789
+ {unread && <><span className="cloudlet-live">{labels.unread}</span><span className={part('unread', 'cloudlet-center-unread')} aria-hidden="true" /></>}
790
+ {render ? render(item, parts) : content}
791
+ </li>;
792
+ }
793
+
794
+ /** Scoped CSSOM rules of the panel's own `<style>`: the only place its motion is written. */
795
+ function ruleSet(sheet: CSSStyleSheet | null | undefined, scope: string) {
796
+ const rules = new Map<string, CSSStyleDeclaration>();
797
+ return {
798
+ get(name: string, selector: string): CSSStyleDeclaration | null {
799
+ let style = rules.get(name);
800
+ if (!style && sheet) {
801
+ const index = sheet.insertRule(`${scope}${selector} {}`, sheet.cssRules.length);
802
+ rules.set(name, style = (sheet.cssRules[index] as CSSStyleRule).style);
803
+ }
804
+ return style ?? null;
805
+ },
806
+ drop(name: string) {
807
+ const style = rules.get(name);
808
+ if (!style || !sheet) return;
809
+ rules.delete(name);
810
+ for (let index = 0; index < sheet.cssRules.length; index++) {
811
+ if ((sheet.cssRules[index] as CSSStyleRule).style === style) { sheet.deleteRule(index); return; }
812
+ }
813
+ },
814
+ clear() {
815
+ rules.clear();
816
+ if (sheet) while (sheet.cssRules.length) sheet.deleteRule(0);
817
+ },
818
+ };
819
+ }
820
+ type Rules = ReturnType<typeof ruleSet>;
821
+ /** Writes `value`, or removes the property for its resting value (`''`). */
822
+ function put(style: CSSStyleDeclaration | null, property: string, value: string) {
823
+ if (!style) return;
824
+ if (value) style.setProperty(property, value); else style.removeProperty(property);
825
+ }
826
+ const clamp01 = (value: number) => Math.min(1, Math.max(0, value));
827
+ const round = (value: number) => Math.round(value * 100) / 100;
828
+
829
+ /**
830
+ * What a leaving card's copy needs, captured while the card is still in the document; a card hidden
831
+ * behind a stack's edges leaves without one.
832
+ */
833
+ interface Leaving { readonly key: string; readonly item: HTMLLIElement; readonly copy: HTMLElement | null; readonly top: number; readonly left: number; readonly width: number }
834
+ /** A heading row, a button under a stack or the empty line that left: its copy blurs out where it stood. */
835
+ interface LeavingText { readonly element: HTMLElement; readonly copy: HTMLElement; readonly top: number; readonly left: number; readonly width: number; readonly opacity: number }
836
+ const REST_LOOK = { y: 0, s: 1, c: 0, vy: 0, vs: 0, clipping: false } as const;
837
+
838
+ /**
839
+ * The drawer's motion: one position spring (and the reduced-motion fade), the trail of the cards,
840
+ * a card growing in at the top, the copy of a cleared card leaving, the others moving to their new
841
+ * places (FLIP from the layout positions of the previous commit), and the backdrop's layers
842
+ * following the position. Reduced motion (the system, the prop, `data-reduced-motion` on an ancestor) turns all of
843
+ * it into short opacity changes, live: the column and the backdrop's layers fade, never the root,
844
+ * whose opacity would cut the blur off from the page.
845
+ */
846
+ function useDrawerMotion(props: PanelProps, rootRef: RefObject<HTMLDivElement | null>, keys: MotionKeys, swipeable: boolean) {
847
+ const styleRef = useRef<HTMLStyleElement>(null);
848
+ const stackRef = useRef<HTMLDivElement>(null);
849
+ const listRef = useRef<HTMLUListElement>(null);
850
+ const exitsRef = useRef<HTMLDivElement>(null);
851
+ const latest = useRef({ props, keys, swipeable });
852
+ const motionRef = useRef<CenterMotion | null>(null);
853
+ const live = useRef<{
854
+ rules: Rules; positions: Places; measured: boolean; leaving: Leaving[]; texts: LeavingText[]; sync: () => void;
855
+ /** Motion keys of every listed record at the last commit. */
856
+ listed: Set<string>;
857
+ /** What the writer needs to know of the cards in groups (refreshed with the places). */
858
+ kinds: CardKinds;
859
+ /** The cards each group last moved, for a click that turns them while they go. */
860
+ folds: Map<string, readonly string[]>;
861
+ /** Release speeds (px per second) of swiped cards and when they were let go, for the copies that leave in their place. */
862
+ flings: Map<string, { readonly velocity: number; readonly direction: 1 | -1; readonly at: number }>; now: () => number; width: () => number; travel: () => number; cancelSwipe: () => void;
863
+ refresh: () => Places;
864
+ } | null>(null);
865
+ useLayoutEffect(() => { latest.current = { props, keys, swipeable }; });
866
+
867
+ useLayoutEffect(() => {
868
+ const root = rootRef.current!;
869
+ const doc = root.ownerDocument;
870
+ const view = doc.defaultView!;
871
+ const rules = ruleSet(styleRef.current?.sheet, `#${root.id}`);
872
+ let width = root.offsetWidth || root.getBoundingClientRect().width;
873
+ let overrides = latest.current.props.motion?.overrides;
874
+ let constants = resolveCenterMotion(overrides);
875
+ const writeConstants = () => {
876
+ const style = rules.get('root', '');
877
+ put(style, '--cloudlet-center-swap', `${constants.swap}ms`);
878
+ put(style, '--cloudlet-center-swap-blur', `${constants.swapBlur}px`);
879
+ put(style, '--cloudlet-center-reduced', `${constants.reduced}ms`);
880
+ put(style, '--cloudlet-center-stack-step', `${constants.stack.step}px`);
881
+ put(style, '--cloudlet-center-stack-shrink', String(constants.stack.shrink));
882
+ put(style, '--cloudlet-center-stack-reveal', `${constants.stack.reveal}ms`);
883
+ put(style, '--cloudlet-center-stack-blur', `${constants.stack.blur}px`);
884
+ };
885
+ const kinds: CardKinds = { grouped: new Set(), edges: new Set(), hidden: new Set() };
886
+ /** What was last written: the backdrop's layers, its blur layers apart, the column ('' for nothing). */
887
+ let backdropFade = '';
888
+ let blurFade = '';
889
+ let columnFade = '';
890
+ const opacityOf = (value: number) => value >= 1 ? '' : String(round(clamp01(value) * 1000) / 1000);
891
+ /**
892
+ * The backdrop's layers fade with the drawer's position and, under reduced motion, the panel's
893
+ * fade: each layer on its own, never its container or the root. At 0 they are hidden, so a
894
+ * closed or leaving center computes no blur; at 1 nothing is written. The blur layers take a
895
+ * rule of their own only while the page's scroll hides them (`blur` below 1).
896
+ */
897
+ const writeBackdrop = () => {
898
+ const shown = clamp01(motion.value('p')) * clamp01(motion.value('fade'));
899
+ const fade = opacityOf(shown);
900
+ if (fade !== backdropFade) {
901
+ backdropFade = fade;
902
+ const style = rules.get('backdrop', BACKDROP_LAYERS);
903
+ put(style, 'opacity', fade);
904
+ put(style, 'visibility', fade === '0' ? 'hidden' : '');
905
+ }
906
+ const scroll = clamp01(motion.value('blur'));
907
+ const blur = scroll >= 1 ? '' : String(round(shown * scroll * 1000) / 1000);
908
+ if (blur !== blurFade) {
909
+ blurFade = blur;
910
+ const style = rules.get('blur', BACKDROP_BLURS);
911
+ put(style, 'opacity', blur);
912
+ put(style, 'visibility', blur === '0' ? 'hidden' : '');
913
+ }
914
+ };
915
+ /** Reduced motion fades the column (and through writeBackdrop the backdrop's layers). */
916
+ const writeFade = () => {
917
+ const fade = opacityOf(motion.value('fade'));
918
+ if (fade !== columnFade) { columnFade = fade; put(rules.get('column', ' > .cloudlet-center-column'), 'opacity', fade); }
919
+ writeBackdrop();
920
+ };
921
+ const writeDrawer = () => {
922
+ const p = motion.value('p');
923
+ const sign = latest.current.props.side === 'left' ? -1 : 1;
924
+ const x = (1 - p) * (width + constants.travel) * sign;
925
+ for (let index = 0; index <= LAG_CARDS; index++) {
926
+ const offset = x * (1 + index * constants.lag);
927
+ put(rules.get(`lag${index}`, ` [data-cloudlet-lag="${index}"]`), 'translate', Math.abs(offset) < 0.01 ? '' : `${round(offset)}px 0`);
928
+ }
929
+ writeBackdrop();
930
+ // The header appears in the second half of the way.
931
+ const header = clamp01(p * 1.6 - 0.5);
932
+ put(rules.get('header', ' .cloudlet-center-header'), 'opacity', header >= 1 ? '' : String(round(header * 1000) / 1000));
933
+ };
934
+ const writeCard = (key: string) => {
935
+ const x = motion.value(`x:${key}`);
936
+ const y = motion.value(`y:${key}`);
937
+ const scale = motion.value(`s:${key}`);
938
+ // A card swiped sideways fades with its travel, down to 30 %.
939
+ const opacity = motion.value(`o:${key}`) * (1 - Math.min(0.7, Math.abs(x) / Math.max(1, width)));
940
+ const style = rules.get(`card${key}`, ` [data-cloudlet-motion-key="${key}"]`);
941
+ const still = Math.abs(x) < 0.01 && Math.abs(y) < 0.01 && scale === 1;
942
+ put(style, 'transform', still ? '' : Math.abs(x) < 0.01
943
+ ? `translateY(${round(y)}px) scale(${Math.round(scale * 10000) / 10000})`
944
+ : `translate(${round(x)}px, ${round(y)}px) scale(${Math.round(scale * 10000) / 10000})`);
945
+ put(style, 'opacity', opacity >= 1 ? '' : String(Math.round(opacity * 1000) / 1000));
946
+ // A card growing in at the top stays over the cards still moving down out of its way (a group
947
+ // keeps its own order: each card over the next).
948
+ put(style, 'z-index', scale !== 1 && !key.startsWith('x') && !kinds.grouped.has(key) ? '1' : '');
949
+ // A card moving in a group is clipped from its top by its channel; at rest an edge's own clip
950
+ // (the CSS) holds, and a copy keeps the clip it left with.
951
+ const clip = motion.value(`c:${key}`);
952
+ const copy = key.startsWith('x');
953
+ const clipping = copy || motion.moving(`c:${key}`);
954
+ put(style, 'clip-path', clipping && (clip > 0.01 || (!copy && kinds.edges.has(key))) ? `inset(${round(clip)}px -48px -48px)` : '');
955
+ // A card hidden behind the edges shows while it fades out into its place.
956
+ put(style, 'visibility', kinds.hidden.has(key) && opacity < 1 ? 'visible' : '');
957
+ };
958
+ const write = (changed: ReadonlySet<string>) => {
959
+ const cards = new Set<string>();
960
+ for (const key of changed) {
961
+ if (key === 'p') writeDrawer();
962
+ else if (key === 'fade') writeFade();
963
+ else if (key === 'blur') writeBackdrop();
964
+ else cards.add(key.slice(2));
965
+ }
966
+ for (const key of cards) writeCard(key);
967
+ };
968
+ let gestures: ReturnType<typeof attachCenterGestures> | null = null;
969
+ const calm = watchReducedMotion(root, () => latest.current.props.reducedMotion === true, next => {
970
+ root.dataset.reducedMotion = String(next);
971
+ // Calm turns the swipes off, a running one too.
972
+ if (next) gestures?.cancel();
973
+ motion.setReducedMotion(next);
974
+ });
975
+ root.dataset.reducedMotion = String(calm.reduced);
976
+ const motion = createCenterMotion({
977
+ now: () => view.performance.now(),
978
+ requestFrame: callback => view.requestAnimationFrame ? view.requestAnimationFrame(callback) : view.setTimeout(() => callback(view.performance.now()), 16),
979
+ cancelFrame: frame => view.cancelAnimationFrame ? view.cancelAnimationFrame(frame) : view.clearTimeout(frame),
980
+ write, reducedMotion: calm.reduced, timeScale: latest.current.props.motion?.timeScale, constants,
981
+ });
982
+ motionRef.current = motion;
983
+ writeConstants();
984
+ if (latest.current.props.instant) motion.place(true);
985
+ // The first frame: the drawer at its starting place, before anything paints (under reduced
986
+ // motion it stays in place and fades instead).
987
+ if (!calm.reduced) writeDrawer();
988
+ const flings = new Map<string, { velocity: number; direction: 1 | -1; at: number }>();
989
+ gestures = attachCenterGestures(root, {
990
+ motion, width: () => width, travel: () => constants.travel,
991
+ edge: () => latest.current.props.side === 'left' ? -1 : 1,
992
+ open: () => latest.current.props.open,
993
+ close: () => latest.current.props.setOpen(false),
994
+ idOf: key => latest.current.swipeable ? latest.current.keys.idOf(key) : null,
995
+ dismiss: id => {
996
+ const { onDismiss, onClear } = latest.current.props;
997
+ if (onDismiss) onDismiss(id); else onClear?.([id]);
998
+ },
999
+ fling: (key, velocity, direction) => {
1000
+ const at = view.performance.now();
1001
+ for (const [other, swiped] of flings) if (at - swiped.at >= FLING_WINDOW) flings.delete(other);
1002
+ flings.set(key, { velocity, direction, at });
1003
+ },
1004
+ now: () => view.performance.now(),
1005
+ });
1006
+ const state = {
1007
+ now: () => view.performance.now(), flings, width: () => width, travel: () => constants.travel, cancelSwipe: () => gestures?.cancel(),
1008
+ rules, positions: new Map() as Places, measured: false, leaving: [] as Leaving[], texts: [] as LeavingText[], listed: new Set<string>(),
1009
+ kinds, folds: new Map<string, readonly string[]>(),
1010
+ /** Measures the places again, and writes each collapsed stack's top card height for its edges' clip. */
1011
+ refresh: () => {
1012
+ const next = places(listRef.current, stackRef.current);
1013
+ kinds.grouped.clear(); kinds.edges.clear(); kinds.hidden.clear();
1014
+ for (const [key, place] of next) {
1015
+ if (place.box) kinds.grouped.add(key);
1016
+ if (place.box?.kind === 'edge' || place.box?.kind === 'hidden') kinds.edges.add(key);
1017
+ if (place.box?.kind === 'hidden') kinds.hidden.add(key);
1018
+ if (place.first !== undefined) put(rules.get(`card${key}`, ` [data-cloudlet-motion-key="${key}"]`), '--cloudlet-center-stack-top', place.expanded ? '' : `${round(place.first)}px`);
1019
+ }
1020
+ return next;
1021
+ },
1022
+ sync: () => {
1023
+ const next = latest.current.props.motion?.overrides;
1024
+ if (next !== overrides) { overrides = next; constants = resolveCenterMotion(next); motion.setConstants(constants); writeConstants(); }
1025
+ motion.setTimeScale(latest.current.props.motion?.timeScale);
1026
+ calm.sync();
1027
+ },
1028
+ };
1029
+ live.current = state;
1030
+ // The column's width sets the travel; the list's size changes outside a commit refresh the places.
1031
+ const observer = view.ResizeObserver ? new view.ResizeObserver(() => {
1032
+ const measuredWidth = root.offsetWidth;
1033
+ if (measuredWidth && measuredWidth !== width) { width = measuredWidth; writeDrawer(); }
1034
+ state.positions = state.refresh();
1035
+ }) : null;
1036
+ observer?.observe(root);
1037
+ if (stackRef.current) observer?.observe(stackRef.current);
1038
+ return () => {
1039
+ observer?.disconnect();
1040
+ gestures?.dispose();
1041
+ gestures = null;
1042
+ calm.dispose();
1043
+ motion.dispose();
1044
+ motionRef.current = null;
1045
+ live.current = null;
1046
+ rules.clear();
1047
+ exitsRef.current?.replaceChildren();
1048
+ delete root.dataset.reducedMotion;
1049
+ };
1050
+ }, [rootRef]);
1051
+
1052
+ // Opening and closing retarget the one spring from where the drawer is and how fast it moves.
1053
+ const { open, onClosed } = props;
1054
+ useLayoutEffect(() => {
1055
+ rootRef.current?.toggleAttribute('inert', !open);
1056
+ // Closed from elsewhere under a finger: the finger lets go of nothing.
1057
+ if (!open) live.current?.cancelSwipe();
1058
+ motionRef.current?.setOpen(open, open ? undefined : onClosed);
1059
+ }, [open, onClosed, rootRef]);
1060
+
1061
+ // Every commit: props that tune the motion, the copies of the cards that left, the new places.
1062
+ useLayoutEffect(() => {
1063
+ const state = live.current;
1064
+ const motion = motionRef.current;
1065
+ if (!state || !motion) return;
1066
+ state.sync();
1067
+ const exits = exitsRef.current;
1068
+ const { notifications } = latest.current.props;
1069
+ // Not an array (an app's `data?.items` while it loads): nothing is listed, as `arrange` reads it.
1070
+ const listed = new Set((Array.isArray(notifications) ? notifications : []).flatMap(item => {
1071
+ const key = item && typeof item.id === 'string' ? latest.current.keys.of(item.id) : null;
1072
+ return key === null ? [] : [key];
1073
+ }));
1074
+ for (const leaving of state.leaving.splice(0)) {
1075
+ // Still in the document: StrictMode's simulated unmount, not a card that left. Still listed:
1076
+ // the card moved into or out of a group, or behind a collapsed stack; its channels stay.
1077
+ if (leaving.item.isConnected || !exits || listed.has(leaving.key)) continue;
1078
+ const { copy } = leaving;
1079
+ if (!copy) {
1080
+ motion.forget(leaving.key);
1081
+ state.rules.drop(`card${leaving.key}`);
1082
+ continue;
1083
+ }
1084
+ const key = `x${leaving.key}`;
1085
+ let from: { x: number; y: number; scale: number; opacity: number; clip?: number } = { x: motion.value(`x:${leaving.key}`), y: motion.value(`y:${leaving.key}`), scale: motion.value(`s:${leaving.key}`), opacity: motion.value(`o:${leaving.key}`) };
1086
+ // A card of a group leaves from where it looks (an edge lower, narrower and clipped), and its
1087
+ // copy shrinks from that place.
1088
+ let rest: StackLookValue | undefined;
1089
+ const box = state.positions.get(leaving.key);
1090
+ if (box?.box && box.origin !== undefined) {
1091
+ const geometry = motion.constants.stack;
1092
+ const copyBox: StackBox = { kind: 'plain', top: leaving.top, height: box.box.height, list: 0, first: 0, level: 0 };
1093
+ const inStack = (visual: ReturnType<typeof stackVisual>) => ({ ...visual, top: visual.top + box.origin!, bottom: visual.bottom + box.origin! });
1094
+ const look = stackLook(copyBox, inStack(stackVisual(box.box, { ...REST_LOOK, y: from.y, s: from.scale, c: motion.value(`c:${leaving.key}`), clipping: motion.moving(`c:${leaving.key}`) }, geometry)), geometry);
1095
+ rest = stackLook(copyBox, inStack(stackVisual(box.box, REST_LOOK, geometry)), geometry);
1096
+ from = { ...from, y: look.y, scale: look.s, clip: look.c };
1097
+ }
1098
+ // A swiped card flies on away from the edge, past the column, with the speed it was let go with,
1099
+ // from wherever its spring back has taken it.
1100
+ const swiped = state.flings.get(leaving.key);
1101
+ state.flings.delete(leaving.key);
1102
+ const fling = swiped && state.now() - swiped.at < FLING_WINDOW
1103
+ ? { to: swiped.direction * (state.width() + state.travel()), velocity: swiped.velocity } : undefined;
1104
+ motion.forget(leaving.key);
1105
+ state.rules.drop(`card${leaving.key}`);
1106
+ copy.setAttribute('data-cloudlet-motion-key', key);
1107
+ const style = state.rules.get(`card${key}`, ` [data-cloudlet-motion-key="${key}"]`);
1108
+ put(style, 'top', `${leaving.top}px`);
1109
+ put(style, 'left', `${leaving.left}px`);
1110
+ put(style, 'width', `${leaving.width}px`);
1111
+ exits.append(copy);
1112
+ motion.exit(key, from, () => {
1113
+ copy.remove();
1114
+ motion.forget(key);
1115
+ state.rules.drop(`card${key}`);
1116
+ }, fling, rest);
1117
+ }
1118
+ // The heading rows, buttons under stacks and the empty line that left blur out as copies.
1119
+ for (const text of state.texts.splice(0)) {
1120
+ if (text.element.isConnected || !exits) continue;
1121
+ const key = `t${++nextMotionKey}`;
1122
+ const { copy } = text;
1123
+ copy.setAttribute('data-cloudlet-motion-key', key);
1124
+ const style = state.rules.get(`card${key}`, ` [data-cloudlet-motion-key="${key}"]`);
1125
+ put(style, 'top', `${text.top}px`);
1126
+ put(style, 'left', `${text.left}px`);
1127
+ put(style, 'width', `${text.width}px`);
1128
+ put(style, 'opacity', text.opacity >= 1 ? '' : String(round(text.opacity)));
1129
+ copy.setAttribute('data-cloudlet-unreveal', '');
1130
+ exits.append(copy);
1131
+ const view = exits.ownerDocument.defaultView!;
1132
+ let timer = 0;
1133
+ const done = () => { view.clearTimeout(timer); copy.remove(); state.rules.drop(`card${key}`); };
1134
+ copy.addEventListener('animationend', done, { once: true });
1135
+ // Without CSS animations (or once the panel is gone) the copy still goes.
1136
+ timer = view.setTimeout(done, (motion.reduced ? motion.constants.reduced : motion.constants.stack.reveal) + 100);
1137
+ }
1138
+ const next = state.refresh();
1139
+ if (state.measured) {
1140
+ const geometry = motion.constants.stack;
1141
+ const folds = new Map<string, string[]>();
1142
+ for (const [key, place] of next) {
1143
+ const before = state.positions.get(key);
1144
+ // A record that was listed already (a card that moved in or out of a group) is placed; only
1145
+ // an arrival grows in, unless it lands hidden behind a stack's edges.
1146
+ if (before === undefined) {
1147
+ if (latest.current.props.open && !state.listed.has(key) && place.box?.kind !== 'hidden') motion.enter(key);
1148
+ continue;
1149
+ }
1150
+ if (before.parent !== place.parent) continue;
1151
+ if (!place.box || !before.box) {
1152
+ if (before.top !== place.top) motion.shift(key, before.top - place.top);
1153
+ continue;
1154
+ }
1155
+ // A card of a group: from where it looks in its old place to its new place, on the stack's
1156
+ // springs when the group turned or the card changed places, else on the reflow's.
1157
+ const from = before.box;
1158
+ const to = place.box;
1159
+ if (from.kind === 'hidden' && to.kind === 'hidden') continue;
1160
+ const group = next.get(place.parent);
1161
+ const was = state.positions.get(place.parent);
1162
+ const turned = group?.expanded !== was?.expanded;
1163
+ const same = from.kind === to.kind && from.level === to.level;
1164
+ if (!turned && same && from.top === to.top && from.height === to.height && from.list === to.list && (to.kind === 'plain' || from.first === to.first)) continue;
1165
+ const spring = turned ? group?.expanded ? geometry.expand : geometry.collapse : same && to.kind === 'plain' ? motion.constants.reflow : geometry.collapse;
1166
+ const fade = to.kind === 'hidden' ? 'out' : from.kind === 'hidden' ? 'in' : undefined;
1167
+ motion.fold(key, look => stackLook(to, stackVisual(from, look, geometry), geometry), {
1168
+ spring, clip: restClip(to), fade, delay: cascadeDelay(spring, Math.min(place.index ?? 0, LAG_CARDS) * geometry.cascade),
1169
+ });
1170
+ let moved = folds.get(place.parent);
1171
+ if (!moved) folds.set(place.parent, moved = []);
1172
+ moved.push(key);
1173
+ }
1174
+ for (const [group, keys] of folds) state.folds.set(group, keys);
1175
+ }
1176
+ // A group that left (it was cleared, or shrank to one card) has no copy: its cards have theirs.
1177
+ for (const key of state.positions.keys()) {
1178
+ if (key.startsWith('g') && !next.has(key)) { motion.forget(key); state.rules.drop(`card${key}`); state.folds.delete(key); }
1179
+ }
1180
+ state.positions = next;
1181
+ state.listed = listed;
1182
+ state.measured = true;
1183
+ });
1184
+
1185
+ /** From a card's layout cleanup: copy it while it is still in the document. */
1186
+ const leave = useCallback((key: string, item: HTMLLIElement) => {
1187
+ const state = live.current;
1188
+ if (!state || !motionRef.current) return;
1189
+ const stack = stackRef.current;
1190
+ let copy: HTMLElement | null = null;
1191
+ const place = item.dataset.cloudletPlace;
1192
+ if (place !== 'hidden') {
1193
+ copy = item.cloneNode(true) as HTMLElement;
1194
+ // The clear button stays in place of the time on the copy if it was showing.
1195
+ if (item.matches(':hover, :focus-within')) copy.setAttribute('data-cloudlet-swapped', '');
1196
+ copy.removeAttribute('data-cloudlet-place');
1197
+ // An edge's copy keeps its look: a shade off the card, nothing to read.
1198
+ if (place === 'edge') copy.setAttribute('data-cloudlet-edge', '');
1199
+ inertCopy(copy);
1200
+ }
1201
+ const { top, left } = offsetIn(item, stack);
1202
+ // A card leaves once: the latest capture replaces an earlier one. StrictMode's simulated unmount
1203
+ // of a card that just mounted captures it after this commit's copies were made, and that capture
1204
+ // waits for the next commit; were it the one where the card leaves, two copies under one key
1205
+ // would share its exit, and the one whose completion was replaced would stay for good.
1206
+ state.leaving = state.leaving.filter(leaving => leaving.key !== key);
1207
+ state.leaving.push({ key, item, copy, top, left, width: item.offsetWidth });
1208
+ }, []);
1209
+
1210
+ /** Text that comes with a group or the empty line: a blur in, unless the panel is only being drawn; its leaving copy. */
1211
+ const texts = useMemo<TextMotion>(() => ({
1212
+ reveal(element) {
1213
+ if (live.current?.measured) element.setAttribute('data-cloudlet-reveal', '');
1214
+ },
1215
+ leave(element) {
1216
+ const state = live.current;
1217
+ const view = element.ownerDocument.defaultView;
1218
+ if (!state || !view) return;
1219
+ const copy = element.cloneNode(true) as HTMLElement;
1220
+ copy.removeAttribute('data-cloudlet-reveal');
1221
+ inertCopy(copy);
1222
+ const opacity = Number(view.getComputedStyle(element).opacity);
1223
+ const { top, left } = offsetIn(element, stackRef.current);
1224
+ // As a card's: the latest capture of one element replaces an earlier one.
1225
+ state.texts = state.texts.filter(text => text.element !== element);
1226
+ state.texts.push({ element, copy, top, left, width: element.offsetWidth, opacity: Number.isFinite(opacity) ? opacity : 1 });
1227
+ },
1228
+ }), []);
1229
+
1230
+ /** True while the cards a group last moved are still on their way. */
1231
+ const folding = useCallback((key: string) => {
1232
+ const motion = motionRef.current;
1233
+ const keys = live.current?.folds.get(key);
1234
+ return !!motion && !!keys && keys.some(card => motion.moving(`y:${card}`) || motion.moving(`s:${card}`));
1235
+ }, []);
1236
+
1237
+ /** Shows or hides the backdrop's blur layers apart from the drawer (the scroll tint). */
1238
+ const setBlur = useCallback((shown: boolean) => { motionRef.current?.setBlur(shown, BACKDROP_SCROLL.fade); }, []);
1239
+
1240
+ return { styleRef, stackRef, listRef, exitsRef, leave, texts, folding, motionRef, setBlur };
1241
+ }
1242
+
1243
+ /** What the writer knows of the cards in groups: which are in one, which lie as edges (or hidden), which are hidden. */
1244
+ interface CardKinds { readonly grouped: Set<string>; readonly edges: Set<string>; readonly hidden: Set<string> }
1245
+ type StackLookValue = { readonly y: number; readonly s: number; readonly c: number };
1246
+
1247
+ /**
1248
+ * Layout places (offsetTop and offsetHeight, untouched by transforms) by motion key: the list's own
1249
+ * items (cards and groups) in the list, and the cards of a group in the group's own terms (`box`,
1250
+ * px from the top of its `li`, which lies at `origin` in the stack), so a group that moves moves its
1251
+ * cards with it and they only move for what changed inside it. A group records whether it is
1252
+ * expanded and the height of its first card (`first`).
1253
+ */
1254
+ interface Place {
1255
+ readonly top: number;
1256
+ readonly parent: string;
1257
+ readonly expanded?: boolean;
1258
+ readonly first?: number;
1259
+ readonly box?: StackBox;
1260
+ readonly index?: number;
1261
+ readonly origin?: number;
1262
+ }
1263
+ type Places = Map<string, Place>;
1264
+ function places(list: HTMLUListElement | null, stack: HTMLElement | null): Places {
1265
+ const result: Places = new Map();
1266
+ if (!list) return result;
1267
+ for (const item of list.children as HTMLCollectionOf<HTMLElement>) {
1268
+ const key = item.dataset.cloudletMotionKey;
1269
+ if (!key) continue;
1270
+ const nested = item.querySelector<HTMLElement>(':scope > .cloudlet-center-group-box > .cloudlet-center-group-list');
1271
+ if (!nested) { result.set(key, { top: item.offsetTop, parent: '' }); continue; }
1272
+ const cards = [...nested.children as HTMLCollectionOf<HTMLElement>];
1273
+ const first = cards[0]?.offsetHeight ?? 0;
1274
+ result.set(key, { top: item.offsetTop, parent: '', expanded: item.dataset.expanded === 'true', first });
1275
+ const origin = offsetIn(item, stack).top;
1276
+ const listTop = offsetIn(nested, stack).top - origin;
1277
+ cards.forEach((card, index) => {
1278
+ const cardKey = card.dataset.cloudletMotionKey;
1279
+ if (!cardKey) return;
1280
+ const place = card.dataset.cloudletPlace;
1281
+ const kind = place === 'edge' ? 'edge' : place === 'hidden' ? 'hidden' : 'plain';
1282
+ const box: StackBox = { kind, top: listTop + card.offsetTop, height: card.offsetHeight, list: listTop, first, level: kind === 'plain' ? 0 : kind === 'edge' ? index : EDGES };
1283
+ result.set(cardKey, { top: card.offsetTop, parent: key, box, index, origin });
1284
+ });
1285
+ }
1286
+ return result;
1287
+ }
1288
+
1289
+ /** An element's layout offset inside `container` (an offset ancestor), untouched by transforms. */
1290
+ function offsetIn(element: HTMLElement, container: HTMLElement | null): { top: number; left: number } {
1291
+ let top = 0;
1292
+ let left = 0;
1293
+ for (let node: HTMLElement | null = element; node && node !== container; node = node.offsetParent as HTMLElement | null) {
1294
+ top += node.offsetTop;
1295
+ left += node.offsetLeft;
1296
+ }
1297
+ return { top, left };
1298
+ }
1299
+
1300
+ /** A copy that only looks: no ids, roles, tab stops or ARIA, inert. */
1301
+ function inertCopy(copy: HTMLElement) {
1302
+ for (const element of [copy, ...copy.querySelectorAll('*')]) {
1303
+ for (const name of [...element.getAttributeNames()]) {
1304
+ if (name === 'id' || name === 'role' || name === 'tabindex' || name === 'for' || name === 'name' || name.startsWith('aria-')) element.removeAttribute(name);
1305
+ }
1306
+ }
1307
+ copy.setAttribute('inert', '');
1308
+ }
1309
+
1310
+ /**
1311
+ * Escape, a press outside and focus in and out of the panel while it is open. Focus goes to the
1312
+ * heading at each opening (not when the panel is placed open on its first client render) and, when
1313
+ * the center closes while focus is inside the panel or on the body, to the first of these a person
1314
+ * can reach: the button whose click opened it, what had focus before it opened, the center's first
1315
+ * button in the document. A closing panel (its drawer still leaving) hears nothing.
1316
+ */
1317
+ function useCenterBehaviour(open: boolean, instant: boolean, link: CenterLink, setOpen: (open: boolean) => void,
1318
+ rootRef: RefObject<HTMLDivElement | null>, headingRef: RefObject<HTMLHeadingElement | null>) {
1319
+ const restored = useRef<HTMLElement | null>(null);
1320
+ const first = useRef(instant);
1321
+ const close = useRef(setOpen);
1322
+ close.current = setOpen;
1323
+ // The rendered state: a cleanup that runs with the panel still open is StrictMode's simulated
1324
+ // unmount (the effect runs again at once) or the panel leaving while open.
1325
+ const shown = useRef(open);
1326
+ shown.current = open;
1327
+ /** Where focus came from at this opening; StrictMode's second run of the effect is the same opening. */
1328
+ const opening = useRef<{ readonly previous: HTMLElement | null; readonly opener: HTMLElement | null } | null>(null);
1329
+ /** A restore waiting to see whether the panel was only unmounted for show. */
1330
+ const waiting = useRef<(() => void) | null>(null);
1331
+ useLayoutEffect(() => {
1332
+ if (!open) return;
1333
+ waiting.current = null;
1334
+ const root = rootRef.current!;
1335
+ const doc = root.ownerDocument;
1336
+ const view = doc.defaultView!;
1337
+ let from = opening.current;
1338
+ if (!from) {
1339
+ const active = doc.activeElement;
1340
+ // The button whose click opened it; the app's own `setOpen(true)` opens with none.
1341
+ from = opening.current = {
1342
+ previous: active instanceof view.HTMLElement && active !== doc.body && !root.contains(active) ? active : null,
1343
+ opener: link.opener,
1344
+ };
1345
+ if (!first.current) headingRef.current?.focus({ preventScroll: true });
1346
+ }
1347
+ first.current = false;
1348
+ const { previous, opener } = from;
1349
+ const owned = (target: EventTarget | null) =>
1350
+ target instanceof view.Node && (root.contains(target) || centerButtons(link).some(button => button.contains(target)));
1351
+ // Captured on the document, so the center hears Escape first and nothing behind it does.
1352
+ const onKeyDown = (event: KeyboardEvent) => {
1353
+ if (event.key !== 'Escape' || event.isComposing || event.keyCode === 229) return;
1354
+ const target = event.target;
1355
+ if (target !== doc.body && target !== doc.documentElement && !owned(target)) return;
1356
+ event.stopPropagation();
1357
+ close.current(false);
1358
+ };
1359
+ // A primary press outside the panel and every button of the center (each of them toggles it with
1360
+ // its click); the press itself goes on to the page.
1361
+ const onPointerDown = (event: PointerEvent) => {
1362
+ if (event.button !== 0 || event.ctrlKey) return;
1363
+ const path = event.composedPath();
1364
+ if (path.includes(root) || centerButtons(link).some(button => path.includes(button))) return;
1365
+ close.current(false);
1366
+ };
1367
+ doc.addEventListener('keydown', onKeyDown, true);
1368
+ doc.addEventListener('pointerdown', onPointerDown, true);
1369
+ return () => {
1370
+ doc.removeEventListener('keydown', onKeyDown, true);
1371
+ doc.removeEventListener('pointerdown', onPointerDown, true);
1372
+ // A layout cleanup runs while the panel is still in the document (closing or unmounting).
1373
+ const inside = () => {
1374
+ const focused = doc.activeElement;
1375
+ return !focused || focused === doc.body || root.contains(focused);
1376
+ };
1377
+ const restore = () => [opener, previous, ...buttonsInOrder(link)].find(element => focusIfVisible(element)) ?? null;
1378
+ if (!shown.current) {
1379
+ opening.current = null;
1380
+ if (inside()) restored.current = restore();
1381
+ return;
1382
+ }
1383
+ // Still open: StrictMode runs the effect again at once and the panel keeps focus; a panel that
1384
+ // leaves while open gives it back once it has gone.
1385
+ if (!inside()) return;
1386
+ const later = () => {
1387
+ if (waiting.current !== later) return;
1388
+ waiting.current = null;
1389
+ opening.current = null;
1390
+ if (inside()) restore();
1391
+ };
1392
+ waiting.current = later;
1393
+ queueMicrotask(later);
1394
+ };
1395
+ }, [open, link, rootRef, headingRef]);
1396
+ // React puts focus back where it was before a commit when that element is still in the document:
1397
+ // the closing panel stays for its drawer to leave, so the restored focus is re-applied after it.
1398
+ useLayoutEffect(() => {
1399
+ const target = restored.current;
1400
+ restored.current = null;
1401
+ // The button that opened the center is remembered for as long as it is open.
1402
+ if (!open) link.opener = null;
1403
+ if (open || !target) return;
1404
+ if (rootRef.current?.contains(target.ownerDocument.activeElement)) focusIfVisible(target);
1405
+ }, [open, link, rootRef]);
1406
+ }
1407
+
1408
+ /**
1409
+ * A card that leaves while focus is in it hands focus to the card that followed it in its group, or
1410
+ * to the first control of the list's next item (a group cleared from its heading row or its stack
1411
+ * reports its last card), else to the panel's heading; a card that only moved (into a group, out of
1412
+ * one when it shrank) keeps focus on its own clear button. A card behind a collapsed stack stands for
1413
+ * the stack: focus goes to the button under it. The card reports itself from its layout cleanup;
1414
+ * this runs after the commit.
1415
+ */
1416
+ function useRefocus(groups: readonly Group[], groupKey: (key: string) => string, keys: MotionKeys,
1417
+ rootRef: RefObject<HTMLDivElement | null>, headingRef: RefObject<HTMLHeadingElement | null>): RefObject<string | null> {
1418
+ const lostFocus = useRef<string | null>(null);
1419
+ const listed = useRef(groups);
1420
+ useLayoutEffect(() => {
1421
+ const lost = lostFocus.current;
1422
+ const previous = listed.current;
1423
+ const before = previous.flatMap(group => group.entries);
1424
+ lostFocus.current = null;
1425
+ listed.current = groups;
1426
+ const root = rootRef.current;
1427
+ if (lost === null || !root) return;
1428
+ const doc = root.ownerDocument;
1429
+ if (doc.activeElement && doc.activeElement !== doc.body) return;
1430
+ const groupOf = new Map(groups.flatMap(group => group.entries.map(entry => [entry.id, group] as const)));
1431
+ const stayed = groupOf.has(lost);
1432
+ const next = stayed ? lost
1433
+ : before.slice(before.findIndex(entry => entry.id === lost) + 1).find(entry => groupOf.has(entry.id))?.id;
1434
+ const group = next === undefined ? undefined : groupOf.get(next);
1435
+ let target: HTMLElement | null | undefined = null;
1436
+ if (next !== undefined && group) {
1437
+ // The card itself when it stayed or follows in the same group; else the next item of the list
1438
+ // takes focus on its first control: a card's clear button, a collapsed stack's clear button,
1439
+ // an expanded group's name. A card that moved behind a collapsed stack stands for it: its button.
1440
+ const from = previous.find(item => item.entries.some(entry => entry.id === lost))?.key ?? null;
1441
+ const card = stayed || group.key === null || group.entries.length < 2 || group.key === from
1442
+ ? root.querySelector(`.cloudlet-center-list [data-cloudlet-motion-key="${keys.of(next)}"]:not([data-cloudlet-place])`) : null;
1443
+ const item = group.key === null ? null : root.querySelector(`.cloudlet-center-list > [data-cloudlet-motion-key="${groupKey(group.key)}"]`);
1444
+ // A card without a clear button (no dismiss callback, a custom card) takes focus on its title.
1445
+ target = card ? card.querySelector<HTMLElement>('[data-cloudlet-control="clear"]') ?? card.querySelector<HTMLElement>('.cloudlet-title')
1446
+ : item?.querySelector<HTMLElement>(stayed ? '.cloudlet-center-more, .cloudlet-center-group-title'
1447
+ : '.cloudlet-center-stack-clear, .cloudlet-center-group-title, .cloudlet-center-more');
1448
+ }
1449
+ if (!focusIfVisible(target)) headingRef.current?.focus({ preventScroll: true });
1450
+ }, [groups, groupKey, keys, rootRef, headingRef]);
1451
+ return lostFocus;
1452
+ }
1453
+
1454
+ /** An empty, visually hidden, atomic live region, as the Toaster's announcer makes them. */
1455
+ function liveRegion(doc: Document, priority: 'polite' | 'assertive'): HTMLElement {
1456
+ const element = doc.createElement('div');
1457
+ element.className = 'cloudlet-announcer';
1458
+ element.setAttribute('aria-live', priority);
1459
+ element.setAttribute('aria-atomic', 'true');
1460
+ return element;
1461
+ }
1462
+
1463
+ /** The text a screen reader hears for a card that arrived: its title and description as shown. */
1464
+ function cardText(card: Element | null): string {
1465
+ if (!card) return '';
1466
+ const parts = [card.querySelector('.cloudlet-title'), card.querySelector('.cloudlet-description')];
1467
+ const text = parts.map(part => part?.textContent?.trim() ?? '').filter(Boolean);
1468
+ return (text.length ? text : [card.textContent?.trim() ?? '']).join('. ').replace(/\s+/gu, ' ');
1469
+ }
1470
+
1471
+ /**
1472
+ * Speaks the notifications that arrive while the center is open, after a quiet window, in a polite
1473
+ * region inserted at each opening and again on the next frame (VoiceOver in Safari ignores a region
1474
+ * changed right after its only insertion). What was listed when it opened stays silent, and a
1475
+ * closed center (its drawer still leaving, too) has no region at all.
1476
+ */
1477
+ function useArrivals(open: boolean, entries: readonly Entry[], keys: MotionKeys, rootRef: RefObject<HTMLDivElement | null>) {
1478
+ const heard = useRef(new Set<string>());
1479
+ const listed = useRef(entries);
1480
+ const waiting = useRef<string[]>([]);
1481
+ const flushRef = useRef<() => void>(() => {});
1482
+ useLayoutEffect(() => { listed.current = entries; });
1483
+ useEffect(() => {
1484
+ if (!open) return;
1485
+ heard.current = new Set(listed.current.map(entry => entry.id));
1486
+ const root = rootRef.current!;
1487
+ const doc = root.ownerDocument;
1488
+ const view = doc.defaultView!;
1489
+ const region = liveRegion(doc, 'polite');
1490
+ region.dataset.cloudletCenterAnnouncer = '';
1491
+ root.after(region);
1492
+ const frame = view.requestAnimationFrame?.(() => { if (region.isConnected) root.after(region); });
1493
+ let timer: number | undefined;
1494
+ flushRef.current = () => {
1495
+ if (timer !== undefined) return;
1496
+ timer = view.setTimeout(() => {
1497
+ timer = undefined;
1498
+ const ids = waiting.current.splice(0);
1499
+ if (doc.visibilityState === 'hidden') return;
1500
+ const present = new Set(listed.current.map(entry => entry.id));
1501
+ const lines = ids.filter(id => present.has(id))
1502
+ .map(id => cardText(root.querySelector(`.cloudlet-center-list [data-cloudlet-motion-key="${keys.of(id)}"]`))).filter(Boolean);
1503
+ if (!lines.length) return;
1504
+ let text = lines.join('. ');
1505
+ // The same text again would leave the region unchanged and silent.
1506
+ if (region.textContent === text) text += ' ';
1507
+ region.replaceChildren(doc.createTextNode(text));
1508
+ }, ANNOUNCE);
1509
+ };
1510
+ return () => {
1511
+ flushRef.current = () => {};
1512
+ waiting.current = [];
1513
+ view.clearTimeout(timer);
1514
+ if (frame !== undefined) view.cancelAnimationFrame(frame);
1515
+ region.remove();
1516
+ };
1517
+ }, [open, keys, rootRef]);
1518
+ useEffect(() => {
1519
+ if (!open) return;
1520
+ let arrived = false;
1521
+ for (const entry of entries) {
1522
+ if (heard.current.has(entry.id)) continue;
1523
+ heard.current.add(entry.id);
1524
+ waiting.current.push(entry.id);
1525
+ arrived = true;
1526
+ }
1527
+ if (arrived) flushRef.current();
1528
+ }, [open, entries]);
1529
+ }
1530
+
1531
+ /**
1532
+ * Reports the unread notifications the person has seen to `onRead`: after a commit with the center
1533
+ * open on a visible page, the unread ids listed then, each once per opening (an app that keeps one
1534
+ * unread is not asked again until the center opens again). A page that becomes visible again reports
1535
+ * what it missed.
1536
+ */
1537
+ function useRead(open: boolean, entries: readonly Entry[], latest: RefObject<NotificationCenterProps>) {
1538
+ const reported = useRef(new Set<string>());
1539
+ /** The opening `reported` belongs to; StrictMode's second run of the effect is the same opening. */
1540
+ const opened = useRef(false);
1541
+ const [visible, setVisible] = useState(0);
1542
+ useEffect(() => {
1543
+ if (!open) { opened.current = false; return; }
1544
+ if (!opened.current) reported.current = new Set();
1545
+ opened.current = true;
1546
+ const onVisibility = () => { if (document.visibilityState !== 'hidden') setVisible(count => count + 1); };
1547
+ document.addEventListener('visibilitychange', onVisibility);
1548
+ return () => document.removeEventListener('visibilitychange', onVisibility);
1549
+ }, [open]);
1550
+ useEffect(() => {
1551
+ if (!open || document.visibilityState === 'hidden') return;
1552
+ const ids = entries.filter(entry => entry.item.read === false && !reported.current.has(entry.id)).map(entry => entry.id);
1553
+ if (!ids.length) return;
1554
+ for (const id of ids) reported.current.add(id);
1555
+ latest.current?.onRead?.(ids);
1556
+ }, [open, entries, visible, latest]);
1557
+ }