@oxyhq/bloom 0.54.1 → 0.55.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 (56) hide show
  1. package/lib/commonjs/toast/ToastRow.js +35 -10
  2. package/lib/commonjs/toast/ToastRow.js.map +1 -1
  3. package/lib/commonjs/toast/ToastSwipeHandler.js +15 -5
  4. package/lib/commonjs/toast/ToastSwipeHandler.js.map +1 -1
  5. package/lib/commonjs/toast/constants.js +18 -1
  6. package/lib/commonjs/toast/constants.js.map +1 -1
  7. package/lib/commonjs/toast/toast-store.js +39 -1
  8. package/lib/commonjs/toast/toast-store.js.map +1 -1
  9. package/lib/commonjs/toast/use-stack-hover.js +175 -0
  10. package/lib/commonjs/toast/use-stack-hover.js.map +1 -0
  11. package/lib/commonjs/toast/use-stack-hover.native.js +42 -0
  12. package/lib/commonjs/toast/use-stack-hover.native.js.map +1 -0
  13. package/lib/module/toast/ToastRow.js +35 -10
  14. package/lib/module/toast/ToastRow.js.map +1 -1
  15. package/lib/module/toast/ToastSwipeHandler.js +16 -4
  16. package/lib/module/toast/ToastSwipeHandler.js.map +1 -1
  17. package/lib/module/toast/constants.js +18 -1
  18. package/lib/module/toast/constants.js.map +1 -1
  19. package/lib/module/toast/toast-store.js +39 -1
  20. package/lib/module/toast/toast-store.js.map +1 -1
  21. package/lib/module/toast/use-stack-hover.js +168 -0
  22. package/lib/module/toast/use-stack-hover.js.map +1 -0
  23. package/lib/module/toast/use-stack-hover.native.js +35 -0
  24. package/lib/module/toast/use-stack-hover.native.js.map +1 -0
  25. package/lib/typescript/commonjs/toast/ToastRow.d.ts.map +1 -1
  26. package/lib/typescript/commonjs/toast/ToastSwipeHandler.d.ts +4 -0
  27. package/lib/typescript/commonjs/toast/ToastSwipeHandler.d.ts.map +1 -1
  28. package/lib/typescript/commonjs/toast/constants.d.ts.map +1 -1
  29. package/lib/typescript/commonjs/toast/toast-store.d.ts +15 -0
  30. package/lib/typescript/commonjs/toast/toast-store.d.ts.map +1 -1
  31. package/lib/typescript/commonjs/toast/use-stack-hover.d.ts +55 -0
  32. package/lib/typescript/commonjs/toast/use-stack-hover.d.ts.map +1 -0
  33. package/lib/typescript/commonjs/toast/use-stack-hover.native.d.ts +26 -0
  34. package/lib/typescript/commonjs/toast/use-stack-hover.native.d.ts.map +1 -0
  35. package/lib/typescript/module/toast/ToastRow.d.ts.map +1 -1
  36. package/lib/typescript/module/toast/ToastSwipeHandler.d.ts +4 -0
  37. package/lib/typescript/module/toast/ToastSwipeHandler.d.ts.map +1 -1
  38. package/lib/typescript/module/toast/constants.d.ts.map +1 -1
  39. package/lib/typescript/module/toast/toast-store.d.ts +15 -0
  40. package/lib/typescript/module/toast/toast-store.d.ts.map +1 -1
  41. package/lib/typescript/module/toast/use-stack-hover.d.ts +55 -0
  42. package/lib/typescript/module/toast/use-stack-hover.d.ts.map +1 -0
  43. package/lib/typescript/module/toast/use-stack-hover.native.d.ts +26 -0
  44. package/lib/typescript/module/toast/use-stack-hover.native.d.ts.map +1 -0
  45. package/package.json +1 -1
  46. package/src/__tests__/Toaster.test.tsx +554 -0
  47. package/src/__tests__/toast-position-utils.test.ts +28 -0
  48. package/src/__tests__/toast-stack-hover.test.ts +92 -0
  49. package/src/__tests__/toast-store.test.ts +72 -0
  50. package/src/toast/Toast.stories.tsx +10 -0
  51. package/src/toast/ToastRow.tsx +33 -10
  52. package/src/toast/ToastSwipeHandler.tsx +14 -2
  53. package/src/toast/constants.ts +18 -1
  54. package/src/toast/toast-store.ts +39 -1
  55. package/src/toast/use-stack-hover.native.ts +34 -0
  56. package/src/toast/use-stack-hover.ts +182 -0
@@ -0,0 +1,92 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { renderHook } from '@testing-library/react-native';
4
+
5
+ import {
6
+ isStackHovered as isStackHoveredNative,
7
+ useStackHover as useStackHoverNative,
8
+ } from '../toast/use-stack-hover.native';
9
+ import { isStackHovered, useStackHover } from '../toast/use-stack-hover';
10
+
11
+ /**
12
+ * The hover trigger's platform split. jest resolves the WEB file by default (as
13
+ * every non-Metro bundler and a consumer's `tsc` do), so `Toaster.test.tsx` covers
14
+ * the web behaviour through real rows; this file covers the NATIVE fork, which has
15
+ * no behaviour to exercise, plus the source properties that keep the split honest.
16
+ */
17
+ const SRC = join(__dirname, '..');
18
+ const read = (rel: string) => readFileSync(join(SRC, rel), 'utf8');
19
+ const code = (rel: string) =>
20
+ read(rel)
21
+ .replace(/\/\*[\s\S]*?\*\//g, '')
22
+ .replace(/^\s*\/\/.*$/gm, '');
23
+
24
+ describe('stack hover platform split', () => {
25
+ it('native hands back no handlers at all, for either stacking value', () => {
26
+ const stacked = renderHook(() => useStackHoverNative({ enableStacking: true }));
27
+ const flat = renderHook(() => useStackHoverNative({ enableStacking: false }));
28
+
29
+ expect(Object.keys(stacked.result.current)).toEqual([]);
30
+ expect(Object.keys(flat.result.current)).toEqual([]);
31
+ });
32
+
33
+ it('native returns ONE object identity, so the row box props never churn', () => {
34
+ const { result, rerender } = renderHook(() =>
35
+ useStackHoverNative({ enableStacking: true }),
36
+ );
37
+ const first = result.current;
38
+ rerender(undefined);
39
+
40
+ expect(result.current).toBe(first);
41
+ });
42
+
43
+ it('nothing ever hovers on native', () => {
44
+ expect(isStackHoveredNative()).toBe(false);
45
+ });
46
+
47
+ it('web hands back both pointer handlers', () => {
48
+ const { result } = renderHook(() => useStackHover({ enableStacking: true }));
49
+
50
+ expect(typeof result.current.onPointerEnter).toBe('function');
51
+ expect(typeof result.current.onPointerLeave).toBe('function');
52
+ });
53
+
54
+ it('web is not hovered until a pointer says so', () => {
55
+ expect(isStackHovered()).toBe(false);
56
+ });
57
+
58
+ it('the native fork carries no hover state, no timer and no store import', () => {
59
+ const native = code('toast/use-stack-hover.native.ts');
60
+ // A native bundle must not ship the web file's module-level latch or its
61
+ // pending-leave timeout, which is the whole reason this is a file split rather
62
+ // than a `Platform.OS` branch.
63
+ expect(native).not.toMatch(/setTimeout/);
64
+ expect(native).not.toMatch(/from '\.\/toast-store'/);
65
+ expect(native).not.toMatch(/pointerType/);
66
+ });
67
+
68
+ it('the web fork gates on a mouse pointer', () => {
69
+ const web = code('toast/use-stack-hover.ts');
70
+ // Touch fires enter before pointerdown and leave after pointerup, so without
71
+ // this every tap on a touch-capable web device would expand then collapse.
72
+ expect(web).toMatch(/pointerType === 'mouse'/);
73
+ });
74
+
75
+ it('the web fork drives the store rather than a second expansion mechanism', () => {
76
+ const web = code('toast/use-stack-hover.ts');
77
+ expect(web).toMatch(/toastStore\.expand\(\)/);
78
+ expect(web).toMatch(/toastStore\.collapse\(\)/);
79
+ // With stacking off there is nothing to expand, so the pointer pauses directly.
80
+ expect(web).toMatch(/toastStore\.pauseAllTimers\(\)/);
81
+ expect(web).toMatch(/toastStore\.resumeAllTimers\(\)/);
82
+ // No parallel state: expansion lives in the store and nowhere else.
83
+ expect(web).not.toMatch(/useState/);
84
+ expect(web).not.toMatch(/isExpanded\s*=/);
85
+ });
86
+
87
+ it('the row box is the hover target and the press toggle stands down for it', () => {
88
+ expect(code('toast/ToastSwipeHandler.tsx')).toMatch(/\{\.\.\.hoverProps\}/);
89
+ // Hover owns expansion on web; a click must not toggle it shut again.
90
+ expect(code('toast/ToastRow.tsx')).toMatch(/else if \(!isStackHovered\(\)\)/);
91
+ });
92
+ });
@@ -17,6 +17,9 @@ describe('toastStore', () => {
17
17
  });
18
18
 
19
19
  afterEach(() => {
20
+ // The expansion hold is registered by whoever owns hovering, so a test that
21
+ // installs one must not leak it into the next.
22
+ toastStore.setExpansionHold(null);
20
23
  toastStore.dismissToast(undefined);
21
24
  // Drains the hide-overlay timeout so the next test starts from a clean state.
22
25
  jest.runOnlyPendingTimers();
@@ -573,6 +576,14 @@ describe('toastStore', () => {
573
576
  expect(toastStore.getSnapshot().isExpanded).toBe(true);
574
577
  });
575
578
 
579
+ /**
580
+ * The auto-collapse rule. A lone row renders identically expanded or collapsed
581
+ * (`toast-position-utils.test.ts`: "a single row is unmoved by expansion"), while
582
+ * `isExpanded` keeps every timer paused — so collapsing at one row is invisible
583
+ * and is the only thing that stops that last toast hanging on screen forever.
584
+ * The exception is a stack something is HOLDING open, which on web is a pointer
585
+ * resting on it.
586
+ */
576
587
  it('auto-collapses once only one toast is left', () => {
577
588
  const first = toastStore.addToast({ title: 'a' });
578
589
  toastStore.addToast({ title: 'b' });
@@ -581,6 +592,67 @@ describe('toastStore', () => {
581
592
  toastStore.dismissToast(first, 'onDismiss');
582
593
  expect(toastStore.getSnapshot().isExpanded).toBe(false);
583
594
  });
595
+
596
+ it('resumes the surviving toast on that auto-collapse, so it cannot hang', () => {
597
+ const first = toastStore.addToast({ title: 'a', duration: 1000 });
598
+ toastStore.addToast({ title: 'b', duration: 1000 });
599
+ toastStore.expand();
600
+
601
+ toastStore.dismissToast(first, 'onDismiss');
602
+ jest.advanceTimersByTime(ENTERING_ANIMATION_DURATION + 1000);
603
+
604
+ expect(toastStore.getSnapshot().toasts).toHaveLength(0);
605
+ });
606
+
607
+ it('stays expanded while more than one toast is left', () => {
608
+ const first = toastStore.addToast({ title: 'a' });
609
+ toastStore.addToast({ title: 'b' });
610
+ toastStore.addToast({ title: 'c' });
611
+ toastStore.expand();
612
+
613
+ toastStore.dismissToast(first, 'onDismiss');
614
+ expect(toastStore.getSnapshot().isExpanded).toBe(true);
615
+ });
616
+
617
+ it('does not auto-collapse a stack something is holding open', () => {
618
+ toastStore.setExpansionHold(() => true);
619
+ const first = toastStore.addToast({ title: 'a', duration: 1000 });
620
+ toastStore.addToast({ title: 'b', duration: 1000 });
621
+ toastStore.expand();
622
+
623
+ toastStore.dismissToast(first, 'onDismiss');
624
+
625
+ expect(toastStore.getSnapshot().isExpanded).toBe(true);
626
+ // Still paused: resuming here is what would let a hovered toast expire under
627
+ // the cursor.
628
+ jest.advanceTimersByTime(1_000_000);
629
+ expect(toastStore.getSnapshot().toasts).toHaveLength(1);
630
+ });
631
+
632
+ it('resets an EMPTY stack even while held', () => {
633
+ // Nothing can hold open a stack that no longer exists, and once the rows
634
+ // unmount no `pointerleave` ever arrives to release the hold — so this must
635
+ // not depend on it.
636
+ toastStore.setExpansionHold(() => true);
637
+ const only = toastStore.addToast({ title: 'a' });
638
+ toastStore.expand();
639
+
640
+ toastStore.dismissToast(only, 'onDismiss');
641
+
642
+ expect(toastStore.getSnapshot().toasts).toHaveLength(0);
643
+ expect(toastStore.getSnapshot().isExpanded).toBe(false);
644
+ });
645
+
646
+ it('stops consulting a hold once it is cleared', () => {
647
+ toastStore.setExpansionHold(() => true);
648
+ toastStore.setExpansionHold(null);
649
+ const first = toastStore.addToast({ title: 'a' });
650
+ toastStore.addToast({ title: 'b' });
651
+ toastStore.expand();
652
+
653
+ toastStore.dismissToast(first, 'onDismiss');
654
+ expect(toastStore.getSnapshot().isExpanded).toBe(false);
655
+ });
584
656
  });
585
657
 
586
658
  describe('subscription', () => {
@@ -26,6 +26,14 @@ import type { ToasterProps } from './types';
26
26
  * unstacked they must be ~54px apart (46px measured row + 8px gap), collapsed-
27
27
  * stack ~8px apart. Equal `y` values mean the rows are drawn on top of each
28
28
  * other — the failure this shape exists to catch.
29
+ *
30
+ * `Sequential*` gives you BOTH durations for a reason. The `One`/`Two` buttons use
31
+ * `duration: Infinity` so a row stays put while you inspect it — but that starts no
32
+ * auto-close timer at all, so nothing driven from those buttons can see the timer
33
+ * path. `One 3s`/`Two 3s` fire at the outlet's real duration; drive those when the
34
+ * question is a row's LIFETIME rather than its position. (`Toaster.test.tsx`'s
35
+ * "sequential toasts at the default duration" block covers the render set there;
36
+ * only a browser can judge the geometry.)
29
37
  */
30
38
  const meta: Meta = {
31
39
  title: 'Components/Toast',
@@ -249,6 +257,8 @@ function SequentialDemo({ outlet }: { outlet?: ToasterProps }) {
249
257
  <Demo outlet={outlet}>
250
258
  <Button onPress={() => toast('Row one', { duration: Infinity })}>One</Button>
251
259
  <Button onPress={() => toast('Row two', { duration: Infinity })}>Two</Button>
260
+ <Button onPress={() => toast('Row one')}>One 3s</Button>
261
+ <Button onPress={() => toast('Row two')}>Two 3s</Button>
252
262
  </Demo>
253
263
  );
254
264
  }
@@ -60,6 +60,7 @@ import {
60
60
  } from './constants';
61
61
  import { useDynamicToastContext, useToastContext } from './context';
62
62
  import { calculateStackScaleX } from './position-utils';
63
+ import { isStackHovered } from './use-stack-hover';
63
64
  import { useAnimatedTarget } from './use-animated-target';
64
65
  import { ToastContent } from './ToastContent';
65
66
  import { ToastSwipeHandler } from './ToastSwipeHandler';
@@ -354,18 +355,41 @@ export const ToastRow = React.forwardRef<ToastRef, ToastRowProps>(
354
355
  }
355
356
  }, [id, isExpanded]);
356
357
 
358
+ /**
359
+ * INVARIANT: NO TAP ON A STACKED ROW IS INERT. Every one of them dismisses,
360
+ * expands or collapses.
361
+ *
362
+ * The close-button strip dismisses only when a ✕ is actually THERE to aim at,
363
+ * which is exactly `closeButton && dismissible` — the same condition
364
+ * `ToastContent` renders it under, and nothing to do with expansion. Anything
365
+ * else in the strip falls through to the row's own behaviour rather than being
366
+ * swallowed: on a collapsed stack it expands, on an expanded one it collapses.
367
+ *
368
+ * Guarding the strip on `isExpanded` (as this did until now) made two taps do
369
+ * nothing at all — the whole strip at default config, where `closeButton` is
370
+ * `false` so the dismiss branch is unreachable, and the VISIBLE ✕ on a
371
+ * collapsed stack's front row. On Android that second one has no fallback:
372
+ * the RNGH tap wins the race against `ToastContent`'s nested close Pressable,
373
+ * so the ✕ never got its own press either.
374
+ *
375
+ * `x` is relative to the row, which is CAPPED at `TOAST_MAX_ROW_WIDTH`.
376
+ * Measuring the strip from the window edge would put it outside the row
377
+ * entirely on a wide viewport — do not "simplify" this back to `screenWidth`.
378
+ *
379
+ * W13 — the expansion TOGGLE stands down while a mouse is hovering the stack,
380
+ * because hover already owns expansion there (`use-stack-hover`). Without this
381
+ * a desktop click would collapse the stack under the cursor and resume the
382
+ * timers hover had just paused. Dismissing is unaffected, `onPress` always
383
+ * runs, and `isStackHovered()` is always false on native and on any touch web
384
+ * device — so press remains the only trigger wherever there is no pointer.
385
+ */
357
386
  const onSwipePress = React.useCallback(
358
387
  ({ x }: { x: number; y: number }) => {
359
388
  if (enableStacking && numberOfToasts > 1 && position !== 'center') {
360
- // On Android the RNGH tap wins the race against the nested Pressable,
361
- // so a press in the close-button strip has to dismiss explicitly.
362
- // `x` is relative to the row, which is capped — measuring the strip
363
- // from the window edge would put it outside the row on a wide viewport.
364
- if (x > rowWidth - CLOSE_BUTTON_HIT_AREA) {
365
- if (isExpanded && closeButton && dismissible) {
366
- onDismiss(id);
367
- }
368
- } else {
389
+ const inCloseStrip = x > rowWidth - CLOSE_BUTTON_HIT_AREA;
390
+ if (inCloseStrip && closeButton && dismissible) {
391
+ onDismiss(id);
392
+ } else if (!isStackHovered()) {
369
393
  toggleExpand();
370
394
  }
371
395
  }
@@ -376,7 +400,6 @@ export const ToastRow = React.forwardRef<ToastRef, ToastRowProps>(
376
400
  numberOfToasts,
377
401
  position,
378
402
  rowWidth,
379
- isExpanded,
380
403
  closeButton,
381
404
  dismissible,
382
405
  onDismiss,
@@ -14,6 +14,10 @@
14
14
  * covers `toast.custom` JSX and `unstyled` rows too, which never reach that
15
15
  * card. Every distance the gesture measures is a fraction of the capped
16
16
  * `rowWidth`, not of the window — see the constant.
17
+ *
18
+ * W13 — being THE row box also makes it the hover target: `useStackHover`'s
19
+ * handlers go here so a pointer over ANY row counts as a pointer over the stack.
20
+ * The handlers are empty on native.
17
21
  */
18
22
  import * as React from 'react';
19
23
  import {
@@ -37,6 +41,7 @@ import { easeInOutCircFn } from './animations';
37
41
  import { TOAST_MAX_ROW_WIDTH } from './constants';
38
42
  import { useToastContext } from './context';
39
43
  import type { ToastPosition, ToastProps } from './types';
44
+ import { useStackHover } from './use-stack-hover';
40
45
 
41
46
  /** Fraction of the row a horizontal swipe must cross to dismiss. */
42
47
  const HORIZONTAL_DISMISS_FRACTION = 0.25;
@@ -76,10 +81,16 @@ export const ToastSwipeHandler: React.FC<
76
81
  // The row is `width: '100%'` up to the cap, so this is its real width.
77
82
  const rowWidth = Math.min(windowWidth, TOAST_MAX_ROW_WIDTH);
78
83
  const translate = useSharedValue(0);
79
- const { swipeToDismissDirection: direction, position: positionCtx } =
80
- useToastContext();
84
+ const {
85
+ swipeToDismissDirection: direction,
86
+ position: positionCtx,
87
+ enableStacking,
88
+ } = useToastContext();
81
89
  const position = positionProps ?? positionCtx;
82
90
  const isAndroid = Platform.OS === 'android';
91
+ // W13 — hover lives on THE ROW BOX, so hovering any row counts as hovering the
92
+ // stack. Empty on native; see `use-stack-hover.native.ts`.
93
+ const hoverProps = useStackHover({ enableStacking });
83
94
 
84
95
  const pan = Gesture.Pan()
85
96
  .onBegin(() => {
@@ -199,6 +210,7 @@ export const ToastSwipeHandler: React.FC<
199
210
  styles.rowBox,
200
211
  style,
201
212
  ]}
213
+ {...hoverProps}
202
214
  // W9 — on web `LinearTransition`'s easing degrades to CSS `ease` because
203
215
  // a `bezierFn` result carries no easing-name symbol for the CSS mapper.
204
216
  // Accepted: the transition still runs, only its curve differs.
@@ -98,7 +98,24 @@ export const toastDefaults: {
98
98
  theme: 'system',
99
99
  autoWiggleOnUpdate: 'never',
100
100
  richColors: false,
101
- enableStacking: false,
101
+ /**
102
+ * ON, unlike upstream — the same class of correction as `TOAST_MAX_ROW_WIDTH`.
103
+ *
104
+ * sonner-NATIVE defaults this off; sonner (web) has no switch at all, because a
105
+ * collapsed stack — front row full size, the ones behind scaled and offset,
106
+ * expanding on interaction — IS its default presentation. The port inherited the
107
+ * mobile default onto every desktop consumer, where an unstacked run of toasts
108
+ * is a column of full cards rather than a stack.
109
+ *
110
+ * Bloom already deviates deliberately elsewhere (`position: 'bottom-center'` vs
111
+ * upstream's `top-center`, `duration: 3000` vs 4000, `gap: 8` vs 14), so this is
112
+ * in keeping rather than a break with the port.
113
+ *
114
+ * Turning it OFF (`<ToastOutlet enableStacking={false} />`) restores the flat
115
+ * column, which is still the right choice for a surface that must show several
116
+ * toasts at once without an interaction.
117
+ */
118
+ enableStacking: true,
102
119
  stackGap: 8,
103
120
  allowFontScaling: true,
104
121
  };
@@ -42,6 +42,7 @@ class ToastStore {
42
42
  private pendingPromises = new Set<string | number>();
43
43
  private collapseCooldown = false;
44
44
  private collapseCooldownTimeout: ReturnType<typeof setTimeout> | null = null;
45
+ private expansionHold: (() => boolean) | null = null;
45
46
 
46
47
  subscribe = (callback: Subscriber) => {
47
48
  this.subscribers.add(callback);
@@ -59,6 +60,24 @@ class ToastStore {
59
60
  this.config = config;
60
61
  };
61
62
 
63
+ /**
64
+ * Something outside the store can HOLD an expanded stack open — on web, a pointer
65
+ * resting on it. Registered by the platform trigger (`use-stack-hover`) so this
66
+ * module stays pure JS with no DOM and no platform branch; native registers
67
+ * nothing and the predicate stays `null`.
68
+ *
69
+ * It is asked at DECISION time rather than tracked as state on purpose: a row can
70
+ * stop being under the pointer with no event at all — rows unmount under the
71
+ * cursor and move under a stationary one, and neither fires `pointerleave` —
72
+ * so any cached boolean goes stale. Nothing renders from this, so it is
73
+ * deliberately not part of the snapshot.
74
+ */
75
+ setExpansionHold = (hold: (() => boolean) | null) => {
76
+ this.expansionHold = hold;
77
+ };
78
+
79
+ private isHeldOpen = (): boolean => this.expansionHold?.() === true;
80
+
62
81
  private notify = () => {
63
82
  this.subscribers.forEach((callback) => callback());
64
83
  };
@@ -305,8 +324,27 @@ class ToastStore {
305
324
  const updatedRefs = { ...this.state.toastRefs };
306
325
  delete updatedRefs[id];
307
326
 
327
+ /**
328
+ * An expanded stack collapses itself once a single row is left, because
329
+ * "expanded" then means nothing visually — a lone row resolves to the SAME
330
+ * offset and scale either way (`toast-position-utils.test.ts` pins that) — while
331
+ * `isExpanded` keeps every timer paused, so staying expanded would leave that
332
+ * last toast on screen forever with no visible reason. Inherited from
333
+ * sonner-native and kept deliberately: on native it is invisible and it is the
334
+ * only thing that stops the last row hanging.
335
+ *
336
+ * UNLESS something is holding the stack open. On web that is a pointer resting
337
+ * on it, and collapsing under the cursor would resume the timers hover had just
338
+ * paused — the toast would then expire while the user is reading it, which is
339
+ * exactly what hover exists to prevent.
340
+ *
341
+ * An EMPTY stack always resets, hold or no hold: it no longer exists to be held,
342
+ * and once the rows unmount no `pointerleave` will ever arrive to release it.
343
+ */
344
+ const isEmpty = filteredToasts.length === 0;
345
+ const heldOpen = !isEmpty && this.isHeldOpen();
308
346
  const shouldAutoCollapse =
309
- filteredToasts.length <= 1 && this.state.isExpanded;
347
+ filteredToasts.length <= 1 && this.state.isExpanded && !heldOpen;
310
348
 
311
349
  const updatedIndex = this.cloneIndex();
312
350
  updatedIndex.delete(id);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Bloom-original — NATIVE. Metro resolves this over `use-stack-hover.ts` on iOS and
3
+ * Android, the same filename split `ToastHost.native.tsx` uses.
4
+ *
5
+ * Native keeps PRESS as the only way to expand a stack, so this hands back no
6
+ * handlers at all. Two reasons it is a fork rather than a runtime `Platform` check:
7
+ * the web file's module-level hover state and its `setTimeout` have no business
8
+ * existing in a native bundle, and `onPointerEnter`/`onPointerLeave` DO fire on
9
+ * native for touch (RN's pointer events unify touch and mouse), which would make
10
+ * every tap expand-then-collapse while the press toggle fired as well.
11
+ *
12
+ * Keep the shape identical to the web file — `ToastSwipeHandler` spreads whatever
13
+ * this returns onto the row box, and `ToastRow` calls `isStackHovered()`
14
+ * unconditionally.
15
+ */
16
+ export type StackHoverProps = Record<string, never>;
17
+
18
+ /** Parity with the web file's export; nothing here waits for anything. */
19
+ export const HOVER_LEAVE_GRACE = 0;
20
+
21
+ /** Nothing hovers on a touch screen. */
22
+ export function isStackHovered(): boolean {
23
+ return false;
24
+ }
25
+
26
+ /** One frozen object, so spreading it never changes the row box's props. */
27
+ const NO_HOVER_PROPS: StackHoverProps = Object.freeze({});
28
+
29
+ export function useStackHover(_options: { enableStacking: boolean }): StackHoverProps {
30
+ return NO_HOVER_PROPS;
31
+ }
32
+
33
+ /** Parity with the web file so the shared suite can call it on either platform. */
34
+ export function resetStackHoverForTests(): void {}
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Bloom-original — WEB/default. `use-stack-hover.native.ts` is the native no-op,
3
+ * filename-resolved by Metro exactly as `ToastHost.native.tsx` is, so `toast/`
4
+ * stays one universal engine with no `index.web` fork.
5
+ *
6
+ * sonner expands its stack on HOVER; sonner-native only has press, because a phone
7
+ * has no pointer. Bloom needs both: press is the touch and native affordance, hover
8
+ * is what a desktop user expects, and a touch-capable web device must not get a
9
+ * phantom hover from its own taps.
10
+ *
11
+ * THIS IS A TRIGGER, NOT A SECOND MECHANISM. It drives the store's existing
12
+ * `expand`/`collapse`, which already pause and resume the auto-close timers
13
+ * (`ToastStore.expand` calls `timers.pauseAll()`, `collapse` calls `resumeAll()`),
14
+ * so hovering to read a toast cannot let it expire under the cursor — no new
15
+ * pausing path, no new store state. With stacking OFF there is nothing to expand,
16
+ * so the pointer pauses the timers directly instead: the reason sonner pauses is
17
+ * that the pointer is over the toast, which has nothing to do with stacking.
18
+ *
19
+ * TWO THINGS ARE LOAD-BEARING:
20
+ *
21
+ * - `pointerType === 'mouse'`. Touch fires `pointerenter` before `pointerdown`
22
+ * and `pointerleave` after `pointerup` (the pointer ceases to exist), so
23
+ * without this guard every TAP on a touch-capable web device would expand then
24
+ * collapse the stack while the press toggle fired too — three handlers fighting
25
+ * over one tap. Hover is additive: pens and touch fall through to press.
26
+ * - THE LEAVE IS DEFERRED BY A FRAME-ISH GRACE PERIOD, and any enter cancels it.
27
+ * Rows are separate absolutely-positioned boxes with `gap` between them once
28
+ * expanded, so moving the pointer from one row to the next leaves the first
29
+ * before entering the second. Collapsing on that would snap the stack shut and
30
+ * reopen it on whatever row ends up under the pointer — a jitter loop, plus a
31
+ * resume/pause pair per crossing that re-banks each timer's remaining time.
32
+ *
33
+ * The state is module-level on purpose: there is ONE stack per document, the same
34
+ * reason `toastStore` is a module singleton. It is written and read only inside
35
+ * event handlers — never in render — so the React Compiler has nothing to freeze.
36
+ */
37
+ import { useMemo } from 'react';
38
+
39
+ import { toastStore } from './toast-store';
40
+
41
+ /**
42
+ * How long a leave waits for a neighbouring row to claim the pointer. One frame is
43
+ * enough for the same-tick leave/enter pair a row crossing produces; this is a
44
+ * little more so a slow frame cannot flash the stack shut. Exported so the suite
45
+ * asserts against the real value rather than a copy of it.
46
+ */
47
+ export const HOVER_LEAVE_GRACE = 80;
48
+
49
+ /** The portal root every toast row lives under — see `portal/index.web.tsx`. */
50
+ const PORTAL_ROOT_ID = 'bloom-portal-root';
51
+
52
+ type HoverEvent = { nativeEvent: { pointerType?: string } };
53
+
54
+ let hovered = false;
55
+ let leaveTimeout: ReturnType<typeof setTimeout> | null = null;
56
+
57
+ const isMouse = (event: HoverEvent) => event.nativeEvent.pointerType === 'mouse';
58
+
59
+ const cancelPendingLeave = () => {
60
+ if (leaveTimeout !== null) {
61
+ clearTimeout(leaveTimeout);
62
+ leaveTimeout = null;
63
+ }
64
+ };
65
+
66
+ /**
67
+ * Whether the pointer is over the stack RIGHT NOW.
68
+ *
69
+ * Two sources, and both are load-bearing:
70
+ *
71
+ * - the `hovered` latch answers "a mouse entered and has not left", which is the
72
+ * only thing available where there is no DOM (jest runs on `testEnvironment:
73
+ * 'node'`), and is a cheap early-out.
74
+ * - the live `:hover` query answers "a row is under the pointer", which the latch
75
+ * CANNOT: a row can stop being hovered with no event whatsoever. Measured — a row
76
+ * culled by `visibleToasts` under a stationary cursor fires no `pointerleave`,
77
+ * `pointerout` or `mouseleave` at all, and the restack then slides the remaining
78
+ * rows out from under the pointer. A latch alone therefore sticks TRUE, which
79
+ * would disable the press toggle for the rest of the session and suppress every
80
+ * later auto-collapse.
81
+ *
82
+ * Requiring both means a stale latch is corrected by the DOM and a stray DOM match
83
+ * (a pen, a touch) is rejected by the latch.
84
+ *
85
+ * COVERAGE, stated plainly: jest cannot see the DOM half at all
86
+ * (`testEnvironment: 'node'`), and a browser cannot isolate it either — its two
87
+ * consequences are a press toggle standing down (unreachable with a mouse, which
88
+ * always hovers what it presses) and a suppressed auto-collapse (which the deferred
89
+ * leave below independently corrects the moment any boundary event fires). Both
90
+ * halves are kept because each is measurably more accurate than the other alone, not
91
+ * because a test proves the composite.
92
+ *
93
+ * `ToastRow` asks so a press does not TOGGLE what hover already opened, and
94
+ * `toastStore` asks before auto-collapsing a stack down to its last row. The press
95
+ * still runs the toast's own `onPress`; only the expansion toggle steps aside.
96
+ */
97
+ export function isStackHovered(): boolean {
98
+ return hovered && rowUnderPointer() !== false;
99
+ }
100
+
101
+ /**
102
+ * The live DOM answer, or `undefined` where there is no DOM to ask (jest runs on
103
+ * `testEnvironment: 'node'`). Deliberately tri-state: "unknowable" and "no" must not
104
+ * collapse into the same value, because the two callers want opposite defaults —
105
+ * `isStackHovered` trusts the latch when it cannot check, while the deferred leave
106
+ * only stands down on a positive "yes, still hovered".
107
+ */
108
+ function rowUnderPointer(): boolean | undefined {
109
+ if (typeof document === 'undefined') {
110
+ return undefined;
111
+ }
112
+ return document.querySelector(`#${PORTAL_ROOT_ID} [aria-live]:hover`) !== null;
113
+ }
114
+
115
+ /**
116
+ * A pointer resting on the stack HOLDS it open, so the store must not auto-collapse
117
+ * it out from under the cursor. Registered here rather than passed in because this
118
+ * file is the one that knows what hovering means; the store only knows that
119
+ * something says "not yet". Native's fork registers nothing.
120
+ */
121
+ toastStore.setExpansionHold(isStackHovered);
122
+
123
+ export type StackHoverProps = {
124
+ onPointerEnter: (event: HoverEvent) => void;
125
+ onPointerLeave: (event: HoverEvent) => void;
126
+ };
127
+
128
+ export function useStackHover({
129
+ enableStacking,
130
+ }: {
131
+ enableStacking: boolean;
132
+ }): StackHoverProps {
133
+ // Stable per outlet configuration: these land on the row box as props, and every
134
+ // row re-renders on each stack change.
135
+ return useMemo(
136
+ () => ({
137
+ onPointerEnter: (event: HoverEvent) => {
138
+ if (!isMouse(event)) {
139
+ return;
140
+ }
141
+ cancelPendingLeave();
142
+ hovered = true;
143
+ if (enableStacking) {
144
+ // Pauses the timers as part of expanding.
145
+ toastStore.expand();
146
+ } else {
147
+ toastStore.pauseAllTimers();
148
+ }
149
+ },
150
+ onPointerLeave: (event: HoverEvent) => {
151
+ if (!isMouse(event) || !hovered) {
152
+ return;
153
+ }
154
+ cancelPendingLeave();
155
+ leaveTimeout = setTimeout(() => {
156
+ leaveTimeout = null;
157
+ // The rows may have moved rather than the pointer: an expand, a collapse
158
+ // or a restack slides them under a stationary cursor without firing a
159
+ // single pointer event, so re-ask the DOM before acting on a leave that
160
+ // fired 80ms ago. Only a positive "still hovered" stands the collapse down.
161
+ if (rowUnderPointer() === true) {
162
+ return;
163
+ }
164
+ hovered = false;
165
+ if (enableStacking) {
166
+ // Resumes the timers as part of collapsing.
167
+ toastStore.collapse();
168
+ } else {
169
+ toastStore.resumeAllTimers();
170
+ }
171
+ }, HOVER_LEAVE_GRACE);
172
+ },
173
+ }),
174
+ [enableStacking],
175
+ );
176
+ }
177
+
178
+ /** Test-only reset: the module state outlives a render tree, so a suite must clear it. */
179
+ export function resetStackHoverForTests(): void {
180
+ cancelPendingLeave();
181
+ hovered = false;
182
+ }