@onekeyfe/react-native-native-overlay 6.7.0-alpha.475 → 6.8.0-11

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 (102) hide show
  1. package/README.md +119 -21
  2. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayEntryRootView.kt +60 -0
  3. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayHost.kt +37 -5
  4. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayPackage.kt +1 -1
  5. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastCardView.kt +869 -0
  6. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastSpec.kt +327 -0
  7. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterView.kt +574 -0
  8. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterViewManager.kt +54 -0
  9. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayView.kt +12 -0
  10. package/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayViewManager.kt +8 -0
  11. package/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayAccessibilityIsolationTest.kt +172 -0
  12. package/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayMotionTest.kt +42 -0
  13. package/android/src/test/java/com/onekey/nativeoverlay/NativeOverlaySheetInsetTest.kt +78 -0
  14. package/docs/SPEC.md +324 -33
  15. package/ios/NativeOverlayContainerView.swift +6 -0
  16. package/ios/NativeOverlayToastCardView.swift +572 -0
  17. package/ios/NativeOverlayToastSpec.swift +356 -0
  18. package/ios/NativeOverlayToasterView.swift +519 -0
  19. package/ios/NativeOverlayWindowManager.swift +244 -7
  20. package/ios/RCTNativeOverlayToasterComponentView.h +11 -0
  21. package/ios/RCTNativeOverlayToasterComponentView.mm +85 -0
  22. package/lib/module/NativeOverlayNativeComponent.ts +13 -0
  23. package/lib/module/NativeOverlayToasterNativeComponent.ts +24 -0
  24. package/lib/module/OverlayView.js +7 -1
  25. package/lib/module/OverlayView.js.map +1 -1
  26. package/lib/module/animation/anchoredOrigin.js +26 -0
  27. package/lib/module/animation/anchoredOrigin.js.map +1 -0
  28. package/lib/module/animation/resolveAnimation.js +26 -4
  29. package/lib/module/animation/resolveAnimation.js.map +1 -1
  30. package/lib/module/index.js +3 -0
  31. package/lib/module/index.js.map +1 -1
  32. package/lib/module/toast/OverlayToastHost.js +42 -0
  33. package/lib/module/toast/OverlayToastHost.js.map +1 -0
  34. package/lib/module/toast/OverlayToastHost.web.js +32 -0
  35. package/lib/module/toast/OverlayToastHost.web.js.map +1 -0
  36. package/lib/module/toast/OverlayToastStore.js +217 -0
  37. package/lib/module/toast/OverlayToastStore.js.map +1 -0
  38. package/lib/module/toast/toastBridge.js +65 -0
  39. package/lib/module/toast/toastBridge.js.map +1 -0
  40. package/lib/module/toast/toastDomContent.web.js +298 -0
  41. package/lib/module/toast/toastDomContent.web.js.map +1 -0
  42. package/lib/module/toast/toastDomRenderer.web.js +695 -0
  43. package/lib/module/toast/toastDomRenderer.web.js.map +1 -0
  44. package/lib/module/toast/toastStyles.web.js +97 -0
  45. package/lib/module/toast/toastStyles.web.js.map +1 -0
  46. package/lib/module/toast/types.js +2 -0
  47. package/lib/module/toast/types.js.map +1 -0
  48. package/lib/module/web/animateTransition.js +38 -12
  49. package/lib/module/web/animateTransition.js.map +1 -1
  50. package/lib/module/web/overlayLayers.js +5 -0
  51. package/lib/module/web/overlayLayers.js.map +1 -1
  52. package/lib/typescript/src/NativeOverlayNativeComponent.d.ts +13 -0
  53. package/lib/typescript/src/NativeOverlayNativeComponent.d.ts.map +1 -1
  54. package/lib/typescript/src/NativeOverlayToasterNativeComponent.d.ts +19 -0
  55. package/lib/typescript/src/NativeOverlayToasterNativeComponent.d.ts.map +1 -0
  56. package/lib/typescript/src/OverlayView.d.ts.map +1 -1
  57. package/lib/typescript/src/animation/anchoredOrigin.d.ts +7 -0
  58. package/lib/typescript/src/animation/anchoredOrigin.d.ts.map +1 -0
  59. package/lib/typescript/src/animation/resolveAnimation.d.ts +9 -3
  60. package/lib/typescript/src/animation/resolveAnimation.d.ts.map +1 -1
  61. package/lib/typescript/src/animation/types.d.ts +5 -1
  62. package/lib/typescript/src/animation/types.d.ts.map +1 -1
  63. package/lib/typescript/src/index.d.ts +5 -0
  64. package/lib/typescript/src/index.d.ts.map +1 -1
  65. package/lib/typescript/src/toast/OverlayToastHost.d.ts +6 -0
  66. package/lib/typescript/src/toast/OverlayToastHost.d.ts.map +1 -0
  67. package/lib/typescript/src/toast/OverlayToastHost.web.d.ts +6 -0
  68. package/lib/typescript/src/toast/OverlayToastHost.web.d.ts.map +1 -0
  69. package/lib/typescript/src/toast/OverlayToastStore.d.ts +47 -0
  70. package/lib/typescript/src/toast/OverlayToastStore.d.ts.map +1 -0
  71. package/lib/typescript/src/toast/toastBridge.d.ts +11 -0
  72. package/lib/typescript/src/toast/toastBridge.d.ts.map +1 -0
  73. package/lib/typescript/src/toast/toastDomContent.web.d.ts +15 -0
  74. package/lib/typescript/src/toast/toastDomContent.web.d.ts.map +1 -0
  75. package/lib/typescript/src/toast/toastDomRenderer.web.d.ts +8 -0
  76. package/lib/typescript/src/toast/toastDomRenderer.web.d.ts.map +1 -0
  77. package/lib/typescript/src/toast/toastStyles.web.d.ts +2 -0
  78. package/lib/typescript/src/toast/toastStyles.web.d.ts.map +1 -0
  79. package/lib/typescript/src/toast/types.d.ts +240 -0
  80. package/lib/typescript/src/toast/types.d.ts.map +1 -0
  81. package/lib/typescript/src/web/animateTransition.d.ts +12 -0
  82. package/lib/typescript/src/web/animateTransition.d.ts.map +1 -1
  83. package/lib/typescript/src/web/overlayLayers.d.ts.map +1 -1
  84. package/package.json +3 -2
  85. package/react-native.config.js +1 -0
  86. package/src/NativeOverlayNativeComponent.ts +13 -0
  87. package/src/NativeOverlayToasterNativeComponent.ts +24 -0
  88. package/src/OverlayView.tsx +7 -0
  89. package/src/animation/anchoredOrigin.ts +35 -0
  90. package/src/animation/resolveAnimation.ts +28 -7
  91. package/src/animation/types.ts +5 -1
  92. package/src/index.ts +24 -0
  93. package/src/toast/OverlayToastHost.tsx +62 -0
  94. package/src/toast/OverlayToastHost.web.tsx +29 -0
  95. package/src/toast/OverlayToastStore.ts +254 -0
  96. package/src/toast/toastBridge.ts +62 -0
  97. package/src/toast/toastDomContent.web.ts +351 -0
  98. package/src/toast/toastDomRenderer.web.ts +856 -0
  99. package/src/toast/toastStyles.web.ts +97 -0
  100. package/src/toast/types.ts +251 -0
  101. package/src/web/animateTransition.ts +54 -14
  102. package/src/web/overlayLayers.ts +7 -0
@@ -0,0 +1,856 @@
1
+ /* cspell:ignore dasharray dashoffset */
2
+ import { getOverlayLayerRoot, syncOverlayInert } from '../web/overlayLayers';
3
+
4
+ import { buildToastContent } from './toastDomContent.web';
5
+ import { ensureOverlayToastStyles } from './toastStyles.web';
6
+
7
+ import type {
8
+ IOverlayToastDismissReason,
9
+ IOverlayToastEvent,
10
+ IOverlayToastItem,
11
+ IOverlayToastPosition,
12
+ IOverlayToastRenderer,
13
+ IOverlayToastSpec,
14
+ IOverlayToasterConfig,
15
+ } from './types';
16
+
17
+ // The chrome constants of the renderer this replaces (sonner 1.4.41).
18
+ const VISIBLE_TOASTS = 3;
19
+ const VIEWPORT_OFFSET = 32;
20
+ const TOAST_WIDTH = 356;
21
+ const GAP = 14;
22
+ const SWIPE_THRESHOLD = 20;
23
+ const SWIPE_VELOCITY = 0.11; // px per ms
24
+ const TOUCH_START_THRESHOLD = 10;
25
+ const POINTER_START_THRESHOLD = 2;
26
+ // Equal to the exit transition.
27
+ const TIME_BEFORE_UNMOUNT = 200;
28
+ const DEFAULT_POSITION: IOverlayToastPosition = 'bottom-right';
29
+ const DEFAULT_OBSTRUCTION_GAP = 8;
30
+ const DEFAULT_OBSTRUCTION_ROOM = 88;
31
+ const OBSTRUCTION_SHIFT_MS = 220;
32
+ const SVG_NS = 'http://www.w3.org/2000/svg';
33
+
34
+ interface IToastNode {
35
+ id: string;
36
+ spec: IOverlayToastSpec;
37
+ revision: number;
38
+ generation: number;
39
+ position: IOverlayToastPosition;
40
+ li: HTMLLIElement;
41
+ content: HTMLElement;
42
+ mounted: boolean;
43
+ removed: boolean;
44
+ swiping: boolean;
45
+ swipeOut: boolean;
46
+ offsetBeforeRemove: number;
47
+ initialHeight: number;
48
+ closeTimer?: ReturnType<typeof setTimeout>;
49
+ unmountTimer?: ReturnType<typeof setTimeout>;
50
+ swipePointerId?: number;
51
+ }
52
+
53
+ interface IToastPress {
54
+ node: IToastNode;
55
+ x: number;
56
+ y: number;
57
+ startedAt: number;
58
+ moved: boolean;
59
+ }
60
+
61
+ interface IToastGroup {
62
+ position: IOverlayToastPosition;
63
+ ol: HTMLOListElement;
64
+ /** Newest first, leaving cards included until they unmount. */
65
+ toasts: IToastNode[];
66
+ /** Newest first, without leaving cards. */
67
+ heights: { id: string; height: number }[];
68
+ }
69
+
70
+ function getDocumentDirection(): 'ltr' | 'rtl' {
71
+ const attribute = document.documentElement.getAttribute('dir');
72
+ if (attribute === 'rtl' || attribute === 'ltr') {
73
+ return attribute;
74
+ }
75
+ return globalThis.getComputedStyle(document.documentElement).direction ===
76
+ 'rtl'
77
+ ? 'rtl'
78
+ : 'ltr';
79
+ }
80
+
81
+ function createCloseButton(label: string): HTMLButtonElement {
82
+ const button = document.createElement('button');
83
+ button.type = 'button';
84
+ button.setAttribute('aria-label', label);
85
+ button.setAttribute('data-close-button', '');
86
+ const svg = document.createElementNS(SVG_NS, 'svg');
87
+ const attributes: Record<string, string> = {
88
+ 'width': '12',
89
+ 'height': '12',
90
+ 'viewBox': '0 0 24 24',
91
+ 'fill': 'none',
92
+ 'stroke': 'currentColor',
93
+ 'stroke-width': '1.5',
94
+ 'stroke-linecap': 'round',
95
+ 'stroke-linejoin': 'round',
96
+ };
97
+ Object.entries(attributes).forEach(([name, value]) =>
98
+ svg.setAttribute(name, value)
99
+ );
100
+ [
101
+ ['18', '6', '6', '18'],
102
+ ['6', '6', '18', '18'],
103
+ ].forEach(([x1, y1, x2, y2]) => {
104
+ const line = document.createElementNS(SVG_NS, 'line');
105
+ line.setAttribute('x1', x1 ?? '');
106
+ line.setAttribute('y1', y1 ?? '');
107
+ line.setAttribute('x2', x2 ?? '');
108
+ line.setAttribute('y2', y2 ?? '');
109
+ svg.append(line);
110
+ });
111
+ button.append(svg);
112
+ return button;
113
+ }
114
+
115
+ /**
116
+ * Draws message toasts with plain DOM in the `toast` overlay layer. No React:
117
+ * the cards, their stacking, timers, swipe and transitions live here, and the
118
+ * stylesheet reproduces the previous renderer's chrome rule for rule.
119
+ */
120
+ export function createToastDomRenderer(
121
+ report: (event: IOverlayToastEvent) => void
122
+ ): IOverlayToastRenderer {
123
+ ensureOverlayToastStyles();
124
+
125
+ // Events raised while a sync is applying wait for it to finish: the store
126
+ // answers an event by syncing again.
127
+ let syncing = false;
128
+ const pendingEvents: IOverlayToastEvent[] = [];
129
+ const onEvent = (event: IOverlayToastEvent) => {
130
+ if (syncing) {
131
+ pendingEvents.push(event);
132
+ return;
133
+ }
134
+ report(event);
135
+ };
136
+
137
+ const nodes = new Map<string, IToastNode>();
138
+ const groups = new Map<IOverlayToastPosition, IToastGroup>();
139
+ const presses = new Map<number, IToastPress>();
140
+ const hoveredGroups = new Map<number, IToastGroup>();
141
+ let config: IOverlayToasterConfig = {};
142
+ let section: HTMLElement | null = null;
143
+ let keyboardExpanded = false;
144
+ let touchExpandedGroup: IToastGroup | undefined;
145
+ let destroyed = false;
146
+
147
+ const isExpanded = (): boolean =>
148
+ nodes.size > 1 &&
149
+ (keyboardExpanded || !!touchExpandedGroup || hoveredGroups.size > 0);
150
+
151
+ const positionOf = (spec: IOverlayToastSpec): IOverlayToastPosition =>
152
+ spec.position ?? config.position ?? DEFAULT_POSITION;
153
+
154
+ function ensureSection(): HTMLElement {
155
+ const root = getOverlayLayerRoot('toast');
156
+ if (!section) {
157
+ section = document.createElement('section');
158
+ section.setAttribute('aria-label', 'Notifications alt+T');
159
+ section.setAttribute('data-onekey-toast-section', '');
160
+ section.tabIndex = -1;
161
+ }
162
+ if (config.testID) {
163
+ section.setAttribute('data-testid', config.testID);
164
+ }
165
+ if (section.parentElement !== root) {
166
+ root.prepend(section);
167
+ syncOverlayInert();
168
+ }
169
+ return section;
170
+ }
171
+
172
+ function groupContaining(target: Node | null): IToastGroup | undefined {
173
+ return [...groups.values()].find((group) => group.ol.contains(target));
174
+ }
175
+
176
+ function pointerHit(event: PointerEvent): Node | null {
177
+ return typeof document.elementFromPoint === 'function'
178
+ ? document.elementFromPoint(event.clientX, event.clientY)
179
+ : (event.target as Node | null);
180
+ }
181
+
182
+ function ensureGroup(position: IOverlayToastPosition): IToastGroup {
183
+ let group = groups.get(position);
184
+ if (!group) {
185
+ const ol = document.createElement('ol');
186
+ ol.tabIndex = -1;
187
+ ol.setAttribute('data-onekey-toast-toaster', '');
188
+ const nextGroup: IToastGroup = {
189
+ position,
190
+ ol,
191
+ toasts: [],
192
+ heights: [],
193
+ };
194
+ const hover = (event: PointerEvent) => {
195
+ if (
196
+ event.pointerType !== 'touch' &&
197
+ !presses.has(event.pointerId) &&
198
+ hoveredGroups.get(event.pointerId) !== nextGroup
199
+ ) {
200
+ hoveredGroups.set(event.pointerId, nextGroup);
201
+ update();
202
+ }
203
+ };
204
+ ol.addEventListener('pointerenter', hover);
205
+ ol.addEventListener('pointermove', hover);
206
+ ol.addEventListener('pointerleave', (event) => {
207
+ if (
208
+ !presses.has(event.pointerId) &&
209
+ hoveredGroups.get(event.pointerId) === nextGroup
210
+ ) {
211
+ hoveredGroups.delete(event.pointerId);
212
+ update();
213
+ }
214
+ });
215
+ group = nextGroup;
216
+ groups.set(position, group);
217
+ }
218
+ if (group.ol.parentElement !== ensureSection()) {
219
+ ensureSection().append(group.ol);
220
+ }
221
+ return group;
222
+ }
223
+
224
+ function offsetOf(group: IToastGroup, node: IToastNode): number {
225
+ // The height index moves before the card list does, so the layout of the
226
+ // cards behind a leaving one starts closing at once.
227
+ const heightIndex = Math.max(
228
+ group.heights.findIndex((height) => height.id === node.id),
229
+ 0
230
+ );
231
+ const heightsBefore = group.heights
232
+ .slice(0, heightIndex)
233
+ .reduce((sum, height) => sum + height.height, 0);
234
+ return heightIndex * GAP + heightsBefore;
235
+ }
236
+
237
+ function measure(node: IToastNode) {
238
+ const group = groups.get(node.position);
239
+ if (!group || node.removed) {
240
+ return;
241
+ }
242
+ // The card's own height: a card further back in the stack is scaled
243
+ // and pinned to the front card's height, neither of which is its size.
244
+ const { style } = node.li;
245
+ const originalHeight = style.height;
246
+ const originalTransform = style.transform;
247
+ style.height = 'auto';
248
+ style.transform = 'none';
249
+ const { height } = node.li.getBoundingClientRect();
250
+ style.height = originalHeight;
251
+ style.transform = originalTransform;
252
+ node.initialHeight = height;
253
+ const existing = group.heights.find((entry) => entry.id === node.id);
254
+ if (existing) {
255
+ existing.height = height;
256
+ } else {
257
+ group.heights.unshift({ id: node.id, height });
258
+ }
259
+ }
260
+
261
+ function clearCloseTimer(node: IToastNode) {
262
+ if (node.closeTimer !== undefined) {
263
+ clearTimeout(node.closeTimer);
264
+ node.closeTimer = undefined;
265
+ }
266
+ }
267
+
268
+ function syncTimers() {
269
+ const paused = isExpanded() || hoveredGroups.size > 0 || presses.size > 0;
270
+ nodes.forEach((node) => {
271
+ if (node.removed || !Number.isFinite(node.spec.duration)) {
272
+ clearCloseTimer(node);
273
+ return;
274
+ }
275
+ if (paused) {
276
+ clearCloseTimer(node);
277
+ return;
278
+ }
279
+ if (node.closeTimer === undefined) {
280
+ // A resumed toast starts over with its whole lifetime, as before.
281
+ node.closeTimer = setTimeout(() => {
282
+ node.closeTimer = undefined;
283
+ deleteToast(node, 'timeout', true);
284
+ }, node.spec.duration);
285
+ }
286
+ });
287
+ }
288
+
289
+ function unmount(node: IToastNode, reason: IOverlayToastDismissReason) {
290
+ clearNodePresses(node);
291
+ if (node.unmountTimer !== undefined) {
292
+ clearTimeout(node.unmountTimer);
293
+ node.unmountTimer = undefined;
294
+ }
295
+ clearCloseTimer(node);
296
+ node.li.remove();
297
+ const group = groups.get(node.position);
298
+ if (group) {
299
+ group.toasts = group.toasts.filter((entry) => entry !== node);
300
+ group.heights = group.heights.filter((entry) => entry.id !== node.id);
301
+ }
302
+ if (nodes.get(node.id) === node) {
303
+ nodes.delete(node.id);
304
+ }
305
+ onEvent({
306
+ id: node.id,
307
+ generation: node.generation,
308
+ type: 'close',
309
+ reason,
310
+ });
311
+ }
312
+
313
+ function deleteToast(
314
+ node: IToastNode,
315
+ reason: IOverlayToastDismissReason,
316
+ notify: boolean
317
+ ) {
318
+ if (node.removed) {
319
+ return;
320
+ }
321
+ clearNodePresses(node);
322
+ const group = groups.get(node.position);
323
+ node.removed = true;
324
+ // Keep the offset the card had, for the exit transition.
325
+ node.offsetBeforeRemove = group ? offsetOf(group, node) : 0;
326
+ if (group) {
327
+ group.heights = group.heights.filter((entry) => entry.id !== node.id);
328
+ }
329
+ clearCloseTimer(node);
330
+ if (notify) {
331
+ onEvent({
332
+ id: node.id,
333
+ generation: node.generation,
334
+ type: 'dismiss',
335
+ reason,
336
+ });
337
+ }
338
+ node.unmountTimer = setTimeout(() => {
339
+ node.unmountTimer = undefined;
340
+ unmount(node, reason);
341
+ update();
342
+ }, TIME_BEFORE_UNMOUNT);
343
+ update();
344
+ }
345
+
346
+ function clearPress(pointerId: number, { node }: IToastPress) {
347
+ presses.delete(pointerId);
348
+ if (node.swipePointerId === pointerId) {
349
+ node.swipePointerId = undefined;
350
+ node.swiping = false;
351
+ node.li.setAttribute('data-swiping', 'false');
352
+ node.li.style.setProperty('--swipe-amount', '0px');
353
+ if (node.li.hasPointerCapture?.(pointerId)) {
354
+ node.li.releasePointerCapture(pointerId);
355
+ }
356
+ }
357
+ }
358
+
359
+ function clearNodePresses(node: IToastNode) {
360
+ presses.forEach((press, pointerId) => {
361
+ if (press.node === node) {
362
+ clearPress(pointerId, press);
363
+ hoveredGroups.delete(pointerId);
364
+ }
365
+ });
366
+ }
367
+
368
+ function swipeAmount(node: IToastNode, deltaY: number): number {
369
+ return node.position.startsWith('top')
370
+ ? Math.min(0, deltaY)
371
+ : Math.max(0, deltaY);
372
+ }
373
+
374
+ function onGlobalPointerMove(event: PointerEvent) {
375
+ const press = presses.get(event.pointerId);
376
+ if (!press) {
377
+ return;
378
+ }
379
+ const { node } = press;
380
+ const dx = Math.abs(event.clientX - press.x);
381
+ const dy = event.clientY - press.y;
382
+ const threshold =
383
+ event.pointerType === 'touch'
384
+ ? TOUCH_START_THRESHOLD
385
+ : POINTER_START_THRESHOLD;
386
+ press.moved ||= Math.max(dx, Math.abs(dy)) > threshold;
387
+ if (node.swipePointerId !== event.pointerId) {
388
+ return;
389
+ }
390
+ const amount = swipeAmount(node, dy);
391
+ if (!node.swiping) {
392
+ if (Math.abs(amount) <= threshold || Math.abs(amount) < dx) {
393
+ return;
394
+ }
395
+ // Preserve the descendant's native click until an actual swipe starts.
396
+ node.li.setPointerCapture?.(event.pointerId);
397
+ node.swiping = true;
398
+ node.li.setAttribute('data-swiping', 'true');
399
+ }
400
+ node.li.style.setProperty('--swipe-amount', `${amount}px`);
401
+ }
402
+
403
+ function onGlobalPointerEnd(event: PointerEvent) {
404
+ const { pointerId, pointerType } = event;
405
+ const press = presses.get(pointerId);
406
+ if (!press) {
407
+ return;
408
+ }
409
+ const { node } = press;
410
+ const released = event.type === 'pointerup';
411
+ const amount =
412
+ released && node.swipePointerId === pointerId && node.swiping
413
+ ? swipeAmount(node, event.clientY - press.y)
414
+ : 0;
415
+ const velocity =
416
+ Math.abs(amount) / Math.max(1, Date.now() - press.startedAt);
417
+ const dismissed =
418
+ Math.abs(amount) >= SWIPE_THRESHOLD || velocity > SWIPE_VELOCITY;
419
+ clearPress(pointerId, press);
420
+
421
+ // The swipe pseudo-element must be gone before checking where we landed.
422
+ const hit = released ? groupContaining(pointerHit(event)) : undefined;
423
+ if (pointerType === 'touch') {
424
+ if (
425
+ hit &&
426
+ nodes.size > 1 &&
427
+ hit === groups.get(node.position) &&
428
+ !press.moved &&
429
+ Math.max(
430
+ Math.abs(event.clientX - press.x),
431
+ Math.abs(event.clientY - press.y)
432
+ ) <= TOUCH_START_THRESHOLD
433
+ ) {
434
+ touchExpandedGroup = hit;
435
+ }
436
+ } else if (hit) {
437
+ hoveredGroups.set(pointerId, hit);
438
+ } else {
439
+ hoveredGroups.delete(pointerId);
440
+ }
441
+
442
+ if (dismissed) {
443
+ node.swipeOut = true;
444
+ node.li.style.setProperty('--swipe-amount', `${amount}px`);
445
+ deleteToast(node, 'swipe', true);
446
+ } else {
447
+ update();
448
+ }
449
+ }
450
+
451
+ function attachPointerHandlers(node: IToastNode) {
452
+ const { li } = node;
453
+ li.addEventListener('dragstart', (event) => {
454
+ event.preventDefault();
455
+ });
456
+ li.addEventListener('pointerdown', (event) => {
457
+ if (node.removed || event.button !== 0) {
458
+ return;
459
+ }
460
+ const target = event.target as HTMLElement | null;
461
+ if (
462
+ node.swipePointerId === undefined &&
463
+ !target?.closest?.('button, [data-okt-link]')
464
+ ) {
465
+ node.swipePointerId = event.pointerId;
466
+ }
467
+ presses.set(event.pointerId, {
468
+ node,
469
+ x: event.clientX,
470
+ y: event.clientY,
471
+ startedAt: Date.now(),
472
+ moved: false,
473
+ });
474
+ update();
475
+ });
476
+ li.addEventListener('lostpointercapture', (event) => {
477
+ // A touch's implicit capture may move from a descendant to the card.
478
+ if (
479
+ event.target === li &&
480
+ node.swipePointerId === event.pointerId &&
481
+ !li.hasPointerCapture?.(event.pointerId)
482
+ ) {
483
+ onGlobalPointerEnd(event);
484
+ }
485
+ });
486
+ }
487
+
488
+ function renderContent(node: IToastNode) {
489
+ const next = buildToastContent(node.spec, (event) => {
490
+ if (!node.removed) {
491
+ onEvent({
492
+ ...event,
493
+ id: node.id,
494
+ generation: node.generation,
495
+ } as IOverlayToastEvent);
496
+ }
497
+ });
498
+ if (node.content.parentElement === node.li) {
499
+ node.content.replaceWith(next);
500
+ } else {
501
+ node.li.append(next);
502
+ }
503
+ node.content = next;
504
+ if (node.spec.testID) {
505
+ node.li.setAttribute('data-testid', node.spec.testID);
506
+ } else {
507
+ node.li.removeAttribute('data-testid');
508
+ }
509
+ }
510
+
511
+ function createNode(item: IOverlayToastItem): IToastNode {
512
+ const li = document.createElement('li');
513
+ li.setAttribute('aria-live', 'polite');
514
+ li.setAttribute('aria-atomic', 'true');
515
+ li.setAttribute('role', 'status');
516
+ li.tabIndex = 0;
517
+ li.setAttribute('data-onekey-toast', '');
518
+ li.setAttribute('data-styled', 'true');
519
+ li.setAttribute('data-dismissible', 'true');
520
+ li.setAttribute('data-invert', 'false');
521
+ const closeButton = createCloseButton(
522
+ config.closeButtonLabel ?? 'Close toast'
523
+ );
524
+ li.append(closeButton);
525
+ const node: IToastNode = {
526
+ id: item.spec.id,
527
+ spec: item.spec,
528
+ revision: item.revision,
529
+ generation: item.generation,
530
+ position: positionOf(item.spec),
531
+ li,
532
+ content: document.createElement('div'),
533
+ mounted: false,
534
+ removed: false,
535
+ swiping: false,
536
+ swipeOut: false,
537
+ offsetBeforeRemove: 0,
538
+ initialHeight: 0,
539
+ };
540
+ closeButton.addEventListener('click', () =>
541
+ deleteToast(node, 'close', true)
542
+ );
543
+ li.addEventListener('keydown', (event) => {
544
+ if (
545
+ !node.removed &&
546
+ node.spec.layout === 'notification' &&
547
+ node.spec.pressable &&
548
+ event.target === li &&
549
+ (event.key === 'Enter' || event.key === ' ')
550
+ ) {
551
+ event.preventDefault();
552
+ onEvent({
553
+ id: node.id,
554
+ generation: node.generation,
555
+ type: 'press',
556
+ });
557
+ }
558
+ });
559
+ renderContent(node);
560
+ attachPointerHandlers(node);
561
+ return node;
562
+ }
563
+
564
+ function mountNode(node: IToastNode) {
565
+ const group = ensureGroup(node.position);
566
+ group.toasts.unshift(node);
567
+ group.ol.prepend(node.li);
568
+ nodes.set(node.id, node);
569
+ applyGroup(group);
570
+ // Measuring lays the card out in its resting-out state, so switching it
571
+ // to mounted right after starts the enter transition from there. No frame
572
+ // callback: those do not run while the page is hidden.
573
+ measure(node);
574
+ node.mounted = true;
575
+ update();
576
+ }
577
+
578
+ function obstructionTop(): number {
579
+ const bottom = config.topObstruction ?? 0;
580
+ if (bottom <= 0) {
581
+ return 0;
582
+ }
583
+ const gap = config.topObstructionGap ?? DEFAULT_OBSTRUCTION_GAP;
584
+ const room = config.topObstructionRoom ?? DEFAULT_OBSTRUCTION_ROOM;
585
+ return Math.max(0, Math.min(bottom + gap, globalThis.innerHeight - room));
586
+ }
587
+
588
+ function applyGroup(group: IToastGroup) {
589
+ const { ol } = group;
590
+ const [yPosition, xPosition] = group.position.split('-');
591
+ ol.dir = getDocumentDirection();
592
+ ol.setAttribute('data-theme', config.theme ?? 'light');
593
+ ol.setAttribute('data-y-position', yPosition ?? 'bottom');
594
+ ol.setAttribute('data-x-position', xPosition ?? 'right');
595
+ ol.style.setProperty(
596
+ '--front-toast-height',
597
+ `${group.heights[0]?.height ?? 0}px`
598
+ );
599
+ ol.style.setProperty('--offset', `${VIEWPORT_OFFSET}px`);
600
+ ol.style.setProperty('--width', `${TOAST_WIDTH}px`);
601
+ ol.style.setProperty('--gap', `${GAP}px`);
602
+ if (config.webContentMaxHeight !== undefined) {
603
+ ol.style.setProperty(
604
+ '--okt-max-height',
605
+ `${config.webContentMaxHeight}px`
606
+ );
607
+ } else {
608
+ ol.style.removeProperty('--okt-max-height');
609
+ }
610
+ // Top toasts rest under whatever hangs from the top of the window. An
611
+ // inline `top`: the narrow-window rule pins the toaster otherwise.
612
+ const top = yPosition === 'top' ? obstructionTop() : 0;
613
+ const reducedMotion =
614
+ config.respectReducedMotion !== false &&
615
+ globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
616
+ ol.style.transition = reducedMotion
617
+ ? ''
618
+ : `top ${OBSTRUCTION_SHIFT_MS}ms ease`;
619
+ ol.style.top = top > 0 ? `${top}px` : '';
620
+
621
+ group.toasts.forEach((node, index) => {
622
+ const { li } = node;
623
+ li.setAttribute('data-mounted', String(node.mounted));
624
+ li.setAttribute('data-removed', String(node.removed));
625
+ li.setAttribute('data-visible', String(index + 1 <= VISIBLE_TOASTS));
626
+ li.setAttribute('data-y-position', yPosition ?? 'bottom');
627
+ li.setAttribute('data-x-position', xPosition ?? 'right');
628
+ li.setAttribute('data-index', String(index));
629
+ li.setAttribute('data-front', String(index === 0));
630
+ li.setAttribute('data-swiping', String(node.swiping));
631
+ li.setAttribute('data-swipe-out', String(node.swipeOut));
632
+ li.setAttribute('data-expanded', String(isExpanded()));
633
+ li.style.setProperty('--index', String(index));
634
+ li.style.setProperty('--toasts-before', String(index));
635
+ li.style.setProperty('--z-index', String(group.toasts.length - index));
636
+ li.style.setProperty(
637
+ '--offset',
638
+ `${node.removed ? node.offsetBeforeRemove : offsetOf(group, node)}px`
639
+ );
640
+ li.style.setProperty('--initial-height', `${node.initialHeight}px`);
641
+ });
642
+ }
643
+
644
+ function update() {
645
+ if (destroyed) {
646
+ return;
647
+ }
648
+ groups.forEach((group, position) => {
649
+ if (group.toasts.length === 0) {
650
+ hoveredGroups.forEach((hoveredGroup, pointerId) => {
651
+ if (hoveredGroup === group) {
652
+ hoveredGroups.delete(pointerId);
653
+ }
654
+ });
655
+ if (touchExpandedGroup === group) {
656
+ touchExpandedGroup = undefined;
657
+ }
658
+ group.ol.remove();
659
+ groups.delete(position);
660
+ }
661
+ });
662
+ if (nodes.size <= 1) {
663
+ keyboardExpanded = false;
664
+ touchExpandedGroup = undefined;
665
+ }
666
+ groups.forEach((group) => {
667
+ applyGroup(group);
668
+ });
669
+ if (nodes.size === 0) {
670
+ section?.remove();
671
+ }
672
+ syncTimers();
673
+ }
674
+
675
+ function moveNode(
676
+ node: IToastNode,
677
+ position: IOverlayToastPosition
678
+ ): IToastGroup {
679
+ clearNodePresses(node);
680
+ const previous = groups.get(node.position);
681
+ if (previous) {
682
+ previous.toasts = previous.toasts.filter((entry) => entry !== node);
683
+ previous.heights = previous.heights.filter(
684
+ (entry) => entry.id !== node.id
685
+ );
686
+ }
687
+ node.position = position;
688
+ const group = ensureGroup(position);
689
+ group.toasts.push(node);
690
+ group.ol.append(node.li);
691
+ if (!node.removed) {
692
+ group.heights.push({ id: node.id, height: node.initialHeight });
693
+ }
694
+ return group;
695
+ }
696
+
697
+ function reconcileGroupOrder(
698
+ group: IToastGroup,
699
+ order: ReadonlyMap<string, number>
700
+ ) {
701
+ group.toasts.sort(
702
+ (a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)
703
+ );
704
+ group.toasts.forEach((node) => group.ol.append(node.li));
705
+ group.heights.sort(
706
+ (a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)
707
+ );
708
+ }
709
+
710
+ function onKeyDown(event: KeyboardEvent) {
711
+ if (nodes.size === 0 || section?.inert || section?.parentElement?.inert) {
712
+ return;
713
+ }
714
+ const lists = [...groups.values()].map((group) => group.ol);
715
+ if (event.altKey && event.code === 'KeyT') {
716
+ keyboardExpanded = true;
717
+ update();
718
+ lists[0]?.focus();
719
+ }
720
+ if (
721
+ event.code === 'Escape' &&
722
+ lists.some(
723
+ (list) =>
724
+ document.activeElement === list ||
725
+ list.contains(document.activeElement)
726
+ )
727
+ ) {
728
+ keyboardExpanded = false;
729
+ touchExpandedGroup = undefined;
730
+ update();
731
+ }
732
+ }
733
+
734
+ function onResize() {
735
+ if ((config.topObstruction ?? 0) > 0) {
736
+ update();
737
+ }
738
+ }
739
+
740
+ function onGlobalPointerDown(event: PointerEvent) {
741
+ if (
742
+ (touchExpandedGroup || keyboardExpanded) &&
743
+ !groupContaining(event.target as Node | null)
744
+ ) {
745
+ touchExpandedGroup = undefined;
746
+ keyboardExpanded = false;
747
+ update();
748
+ }
749
+ }
750
+
751
+ function onWindowBlur() {
752
+ presses.forEach((press, pointerId) => clearPress(pointerId, press));
753
+ hoveredGroups.clear();
754
+ keyboardExpanded = false;
755
+ touchExpandedGroup = undefined;
756
+ update();
757
+ }
758
+
759
+ document.addEventListener('keydown', onKeyDown);
760
+ document.addEventListener('pointerdown', onGlobalPointerDown, true);
761
+ document.addEventListener('pointermove', onGlobalPointerMove, true);
762
+ document.addEventListener('pointerup', onGlobalPointerEnd, true);
763
+ document.addEventListener('pointercancel', onGlobalPointerEnd, true);
764
+ globalThis.addEventListener('resize', onResize);
765
+ globalThis.addEventListener('blur', onWindowBlur);
766
+
767
+ return {
768
+ sync(items, nextConfig) {
769
+ if (destroyed) {
770
+ return;
771
+ }
772
+ syncing = true;
773
+ config = nextConfig;
774
+ const present = new Set(items.map((item) => item.spec.id));
775
+ // Cards the list no longer knows leave without ceremony.
776
+ [...nodes.values()].forEach((node) => {
777
+ if (!present.has(node.id)) {
778
+ unmount(node, 'programmatic');
779
+ }
780
+ });
781
+ const movedGroups = new Set<IToastGroup>();
782
+ // Oldest first, so each new card lands in front of the previous one.
783
+ [...items].reverse().forEach((item) => {
784
+ let node = nodes.get(item.spec.id);
785
+ if (node?.removed && item.visible) {
786
+ // Shown again while the previous card was leaving.
787
+ unmount(node, 'programmatic');
788
+ node = undefined;
789
+ }
790
+ if (!node) {
791
+ if (item.visible) {
792
+ mountNode(createNode(item));
793
+ } else {
794
+ onEvent({
795
+ id: item.spec.id,
796
+ generation: item.generation,
797
+ type: 'close',
798
+ reason: 'programmatic',
799
+ });
800
+ }
801
+ return;
802
+ }
803
+ if (node.revision !== item.revision) {
804
+ node.revision = item.revision;
805
+ node.spec = item.spec;
806
+ renderContent(node);
807
+ measure(node);
808
+ }
809
+ if (node.generation !== item.generation) {
810
+ // Shown again: the toast starts its lifetime over.
811
+ clearNodePresses(node);
812
+ node.generation = item.generation;
813
+ clearCloseTimer(node);
814
+ }
815
+ const position = positionOf(node.spec);
816
+ if (position !== node.position) {
817
+ movedGroups.add(moveNode(node, position));
818
+ }
819
+ if (!item.visible) {
820
+ deleteToast(node, 'programmatic', false);
821
+ }
822
+ });
823
+ if (movedGroups.size > 0) {
824
+ const order = new Map(
825
+ items.map((item, index) => [item.spec.id, index])
826
+ );
827
+ movedGroups.forEach((group) => reconcileGroupOrder(group, order));
828
+ }
829
+ update();
830
+ syncing = false;
831
+ pendingEvents.splice(0).forEach(report);
832
+ },
833
+ destroy() {
834
+ destroyed = true;
835
+ document.removeEventListener('keydown', onKeyDown);
836
+ document.removeEventListener('pointerdown', onGlobalPointerDown, true);
837
+ document.removeEventListener('pointermove', onGlobalPointerMove, true);
838
+ document.removeEventListener('pointerup', onGlobalPointerEnd, true);
839
+ document.removeEventListener('pointercancel', onGlobalPointerEnd, true);
840
+ globalThis.removeEventListener('resize', onResize);
841
+ globalThis.removeEventListener('blur', onWindowBlur);
842
+ presses.forEach((press, pointerId) => clearPress(pointerId, press));
843
+ hoveredGroups.clear();
844
+ nodes.forEach((node) => {
845
+ clearCloseTimer(node);
846
+ if (node.unmountTimer !== undefined) {
847
+ clearTimeout(node.unmountTimer);
848
+ }
849
+ });
850
+ nodes.clear();
851
+ groups.clear();
852
+ section?.remove();
853
+ section = null;
854
+ },
855
+ };
856
+ }