@tamagui/toast 1.7.10 → 1.8.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 (131) hide show
  1. package/dist/cjs/Toast.js +95 -543
  2. package/dist/cjs/Toast.js.map +3 -3
  3. package/dist/cjs/ToastAnnounce.js +93 -0
  4. package/dist/cjs/ToastAnnounce.js.map +7 -0
  5. package/dist/cjs/ToastImpl.js +354 -0
  6. package/dist/cjs/ToastImpl.js.map +7 -0
  7. package/dist/cjs/ToastProvider.js +109 -0
  8. package/dist/cjs/ToastProvider.js.map +7 -0
  9. package/dist/cjs/ToastViewport.js +307 -0
  10. package/dist/cjs/ToastViewport.js.map +7 -0
  11. package/dist/cjs/constants.js +29 -0
  12. package/dist/cjs/constants.js.map +7 -0
  13. package/dist/cjs/createNativeToast.js +49 -0
  14. package/dist/cjs/createNativeToast.js.map +7 -0
  15. package/dist/cjs/createNativeToast.native.js +37 -0
  16. package/dist/cjs/createNativeToast.native.js.map +7 -0
  17. package/dist/cjs/createToast.js +88 -0
  18. package/dist/cjs/createToast.js.map +7 -0
  19. package/dist/cjs/types.js +17 -0
  20. package/dist/cjs/types.js.map +7 -0
  21. package/dist/esm/Toast.js +101 -531
  22. package/dist/esm/Toast.js.map +3 -3
  23. package/dist/esm/Toast.mjs +101 -531
  24. package/dist/esm/Toast.mjs.map +3 -3
  25. package/dist/esm/ToastAnnounce.js +64 -0
  26. package/dist/esm/ToastAnnounce.js.map +7 -0
  27. package/dist/esm/ToastAnnounce.mjs +64 -0
  28. package/dist/esm/ToastAnnounce.mjs.map +7 -0
  29. package/dist/esm/ToastImpl.js +330 -0
  30. package/dist/esm/ToastImpl.js.map +7 -0
  31. package/dist/esm/ToastImpl.mjs +330 -0
  32. package/dist/esm/ToastImpl.mjs.map +7 -0
  33. package/dist/esm/ToastProvider.js +70 -0
  34. package/dist/esm/ToastProvider.js.map +7 -0
  35. package/dist/esm/ToastProvider.mjs +70 -0
  36. package/dist/esm/ToastProvider.mjs.map +7 -0
  37. package/dist/esm/ToastViewport.js +274 -0
  38. package/dist/esm/ToastViewport.js.map +7 -0
  39. package/dist/esm/ToastViewport.mjs +274 -0
  40. package/dist/esm/ToastViewport.mjs.map +7 -0
  41. package/dist/esm/constants.js +5 -0
  42. package/dist/esm/constants.js.map +7 -0
  43. package/dist/esm/constants.mjs +5 -0
  44. package/dist/esm/constants.mjs.map +7 -0
  45. package/dist/esm/createNativeToast.js +25 -0
  46. package/dist/esm/createNativeToast.js.map +7 -0
  47. package/dist/esm/createNativeToast.mjs +25 -0
  48. package/dist/esm/createNativeToast.mjs.map +7 -0
  49. package/dist/esm/createNativeToast.native.js +13 -0
  50. package/dist/esm/createNativeToast.native.js.map +7 -0
  51. package/dist/esm/createNativeToast.native.mjs +13 -0
  52. package/dist/esm/createNativeToast.native.mjs.map +7 -0
  53. package/dist/esm/createToast.js +54 -0
  54. package/dist/esm/createToast.js.map +7 -0
  55. package/dist/esm/createToast.mjs +54 -0
  56. package/dist/esm/createToast.mjs.map +7 -0
  57. package/dist/esm/types.js +1 -0
  58. package/dist/esm/types.js.map +7 -0
  59. package/dist/esm/types.mjs +1 -0
  60. package/dist/esm/types.mjs.map +7 -0
  61. package/dist/jsx/Toast.js +97 -509
  62. package/dist/jsx/Toast.js.map +3 -3
  63. package/dist/jsx/Toast.mjs +97 -509
  64. package/dist/jsx/Toast.mjs.map +3 -3
  65. package/dist/jsx/ToastAnnounce.js +60 -0
  66. package/dist/jsx/ToastAnnounce.js.map +7 -0
  67. package/dist/jsx/ToastAnnounce.mjs +60 -0
  68. package/dist/jsx/ToastAnnounce.mjs.map +7 -0
  69. package/dist/jsx/ToastImpl.js +309 -0
  70. package/dist/jsx/ToastImpl.js.map +7 -0
  71. package/dist/jsx/ToastImpl.mjs +309 -0
  72. package/dist/jsx/ToastImpl.mjs.map +7 -0
  73. package/dist/jsx/ToastProvider.js +65 -0
  74. package/dist/jsx/ToastProvider.js.map +7 -0
  75. package/dist/jsx/ToastProvider.mjs +65 -0
  76. package/dist/jsx/ToastProvider.mjs.map +7 -0
  77. package/dist/jsx/ToastViewport.js +254 -0
  78. package/dist/jsx/ToastViewport.js.map +7 -0
  79. package/dist/jsx/ToastViewport.mjs +254 -0
  80. package/dist/jsx/ToastViewport.mjs.map +7 -0
  81. package/dist/jsx/constants.js +5 -0
  82. package/dist/jsx/constants.js.map +7 -0
  83. package/dist/jsx/constants.mjs +5 -0
  84. package/dist/jsx/constants.mjs.map +7 -0
  85. package/dist/jsx/createNativeToast.js +25 -0
  86. package/dist/jsx/createNativeToast.js.map +7 -0
  87. package/dist/jsx/createNativeToast.mjs +25 -0
  88. package/dist/jsx/createNativeToast.mjs.map +7 -0
  89. package/dist/jsx/createNativeToast.native.js +13 -0
  90. package/dist/jsx/createNativeToast.native.js.map +7 -0
  91. package/dist/jsx/createNativeToast.native.mjs +13 -0
  92. package/dist/jsx/createNativeToast.native.mjs.map +7 -0
  93. package/dist/jsx/createToast.js +49 -0
  94. package/dist/jsx/createToast.js.map +7 -0
  95. package/dist/jsx/createToast.mjs +49 -0
  96. package/dist/jsx/createToast.mjs.map +7 -0
  97. package/dist/jsx/types.js +1 -0
  98. package/dist/jsx/types.js.map +7 -0
  99. package/dist/jsx/types.mjs +1 -0
  100. package/dist/jsx/types.mjs.map +7 -0
  101. package/package.json +14 -13
  102. package/src/Toast.tsx +139 -908
  103. package/src/ToastAnnounce.tsx +97 -0
  104. package/src/ToastImpl.tsx +439 -0
  105. package/src/ToastProvider.tsx +134 -0
  106. package/src/ToastViewport.tsx +354 -0
  107. package/src/constants.ts +1 -0
  108. package/src/createNativeToast.native.tsx +16 -0
  109. package/src/createNativeToast.tsx +25 -0
  110. package/src/createToast.tsx +93 -0
  111. package/src/types.ts +21 -0
  112. package/types/Toast.d.ts +429 -106
  113. package/types/Toast.d.ts.map +1 -1
  114. package/types/ToastAnnounce.d.ts +35 -0
  115. package/types/ToastAnnounce.d.ts.map +1 -0
  116. package/types/ToastImpl.d.ts +267 -0
  117. package/types/ToastImpl.d.ts.map +1 -0
  118. package/types/ToastProvider.d.ts +80 -0
  119. package/types/ToastProvider.d.ts.map +1 -0
  120. package/types/ToastViewport.d.ts +115 -0
  121. package/types/ToastViewport.d.ts.map +1 -0
  122. package/types/constants.d.ts +2 -0
  123. package/types/constants.d.ts.map +1 -0
  124. package/types/createNativeToast.d.ts +3 -0
  125. package/types/createNativeToast.d.ts.map +1 -0
  126. package/types/createNativeToast.native.d.ts +3 -0
  127. package/types/createNativeToast.native.d.ts.map +1 -0
  128. package/types/createToast.d.ts +42 -0
  129. package/types/createToast.d.ts.map +1 -0
  130. package/types/types.d.ts +17 -0
  131. package/types/types.d.ts.map +1 -0
@@ -0,0 +1,97 @@
1
+ import {
2
+ GetProps,
3
+ Stack,
4
+ TamaguiElement,
5
+ Text,
6
+ styled,
7
+ useEvent,
8
+ useIsomorphicLayoutEffect,
9
+ } from '@tamagui/core'
10
+ import { Portal } from '@tamagui/portal'
11
+ import { VisuallyHidden } from '@tamagui/visually-hidden'
12
+ import * as React from 'react'
13
+
14
+ import { ScopedProps, useToastProviderContext } from './ToastProvider'
15
+ import { TOAST_NAME } from './constants'
16
+
17
+ const ToastAnnounceExcludeFrame = styled(Stack, {
18
+ name: 'ToastAnnounceExclude',
19
+ })
20
+ type ToastAnnounceExcludeFrameProps = GetProps<typeof ToastAnnounceExcludeFrame>
21
+ type ToastAnnounceExcludeProps = ToastAnnounceExcludeFrameProps & {
22
+ altText?: string
23
+ }
24
+
25
+ const ToastAnnounceExclude = React.forwardRef<TamaguiElement, ToastAnnounceExcludeProps>(
26
+ (props: ScopedProps<ToastAnnounceExcludeProps>, forwardedRef) => {
27
+ const { __scopeToast, altText, ...announceExcludeProps } = props
28
+
29
+ return (
30
+ <ToastAnnounceExcludeFrame
31
+ data-toast-announce-exclude=""
32
+ data-toast-announce-alt={altText || undefined}
33
+ {...announceExcludeProps}
34
+ ref={forwardedRef}
35
+ />
36
+ )
37
+ }
38
+ )
39
+
40
+ /* -----------------------------------------------------------------------------------------------*/
41
+
42
+ interface ToastAnnounceProps
43
+ extends Omit<GetProps<typeof VisuallyHidden>, 'children'>,
44
+ ScopedProps<{ children: string[] }> {}
45
+
46
+ const ToastAnnounce: React.FC<ToastAnnounceProps> = (
47
+ props: ScopedProps<ToastAnnounceProps>
48
+ ) => {
49
+ const { __scopeToast, children, ...announceProps } = props
50
+ const context = useToastProviderContext(TOAST_NAME, __scopeToast)
51
+ const [renderAnnounceText, setRenderAnnounceText] = React.useState(false)
52
+ const [isAnnounced, setIsAnnounced] = React.useState(false)
53
+
54
+ // render text content in the next frame to ensure toast is announced in NVDA
55
+ useNextFrame(() => setRenderAnnounceText(true))
56
+
57
+ // cleanup after announcing
58
+ React.useEffect(() => {
59
+ const timer = setTimeout(() => setIsAnnounced(true), 1000)
60
+ return () => clearTimeout(timer)
61
+ }, [])
62
+
63
+ return isAnnounced ? null : (
64
+ <Portal asChild>
65
+ <VisuallyHidden {...announceProps}>
66
+ {renderAnnounceText && (
67
+ <Text>
68
+ {context.label} {children}
69
+ </Text>
70
+ )}
71
+ </VisuallyHidden>
72
+ </Portal>
73
+ )
74
+ }
75
+
76
+ /* -----------------------------------------------------------------------------------------------*/
77
+
78
+ function useNextFrame(callback = () => {}) {
79
+ const fn = useEvent(callback)
80
+ useIsomorphicLayoutEffect(() => {
81
+ let raf1 = 0
82
+ let raf2 = 0
83
+ raf1 = requestAnimationFrame(() => (raf2 = requestAnimationFrame(fn)))
84
+ return () => {
85
+ cancelAnimationFrame(raf1)
86
+ cancelAnimationFrame(raf2)
87
+ }
88
+ }, [fn])
89
+ }
90
+
91
+
92
+ export {
93
+ ToastAnnounce,
94
+ ToastAnnounceProps,
95
+ ToastAnnounceExclude,
96
+ ToastAnnounceExcludeProps,
97
+ }
@@ -0,0 +1,439 @@
1
+ import { useIsPresent } from '@tamagui/animate-presence'
2
+ import { useComposedRefs } from '@tamagui/compose-refs'
3
+ import {
4
+ GetProps,
5
+ TamaguiElement,
6
+ Theme,
7
+ composeEventHandlers,
8
+ getAnimationDriver,
9
+ isWeb,
10
+ styled,
11
+ useEvent,
12
+ useThemeName,
13
+ } from '@tamagui/core'
14
+ import { Dismissable, DismissableProps } from '@tamagui/dismissable'
15
+ import { PortalItem } from '@tamagui/portal'
16
+ import { ThemeableStack } from '@tamagui/stacks'
17
+ import * as React from 'react'
18
+ import { Animated, GestureResponderEvent, PanResponder } from 'react-native'
19
+
20
+ import { TOAST_NAME } from './constants'
21
+ import { ToastAnnounce } from './ToastAnnounce'
22
+ import {
23
+ Collection,
24
+ ScopedProps,
25
+ SwipeDirection,
26
+ createToastContext,
27
+ useToastProviderContext,
28
+ } from './ToastProvider'
29
+ import { VIEWPORT_PAUSE, VIEWPORT_RESUME } from './ToastViewport'
30
+
31
+ const ToastImplFrame = styled(ThemeableStack, {
32
+ name: 'ToastImpl',
33
+ variants: {
34
+ backgrounded: {
35
+ true: {
36
+ backgroundColor: '$color6',
37
+ },
38
+ },
39
+ unstyled: {
40
+ false: {
41
+ borderRadius: '$10',
42
+ paddingHorizontal: '$5',
43
+ paddingVertical: '$2',
44
+ marginHorizontal: 'auto',
45
+ marginVertical: '$1',
46
+ },
47
+ },
48
+ },
49
+ defaultVariants: {
50
+ backgrounded: true,
51
+ unstyled: false,
52
+ },
53
+ })
54
+ interface ToastProps extends Omit<ToastImplProps, keyof ToastImplPrivateProps> {
55
+ /**
56
+ * The controlled open state of the dialog. Must be used in conjunction with `onOpenChange`.
57
+ */
58
+ open?: boolean
59
+ /**
60
+ * The open state of the dialog when it is initially rendered. Use when you do not need to control its open state.
61
+ */
62
+ defaultOpen?: boolean
63
+ /**
64
+ * Event handler called when the open state of the dialog changes.
65
+ */
66
+ onOpenChange?(open: boolean): void
67
+ /**
68
+ * Used to force mounting when more control is needed. Useful when
69
+ * controlling animation with React animation libraries.
70
+ */
71
+ forceMount?: true
72
+ }
73
+
74
+ type SwipeEvent = GestureResponderEvent
75
+
76
+ const [ToastInteractiveProvider, useToastInteractiveContext] = createToastContext(
77
+ TOAST_NAME,
78
+ {
79
+ onClose() {},
80
+ }
81
+ )
82
+
83
+ type ToastImplPrivateProps = { open: boolean; onClose(): void }
84
+ type ToastImplFrameProps = GetProps<typeof ToastImplFrame>
85
+ type ToastImplProps = ToastImplPrivateProps &
86
+ ToastImplFrameProps & {
87
+ /**
88
+ * Control the sensitivity of the toast for accessibility purposes.
89
+ * For toasts that are the result of a user action, choose foreground. Toasts generated from background tasks should use background.
90
+ */
91
+ type?: 'foreground' | 'background'
92
+ /**
93
+ * Time in milliseconds that toast should remain visible for. Overrides value given to `ToastProvider`.
94
+ */
95
+ duration?: number
96
+ /**
97
+ * Event handler called when the escape key is down. It can be prevented by calling `event.preventDefault`.
98
+ */
99
+ onEscapeKeyDown?: DismissableProps['onEscapeKeyDown']
100
+ /**
101
+ * Event handler called when the dismiss timer is paused.
102
+ * On web, this occurs when the pointer is moved over the viewport, the viewport is focused or when the window is blurred.
103
+ * On mobile, this occurs when the toast is touched.
104
+ */
105
+ onPause?(): void
106
+ /**
107
+ * Event handler called when the dismiss timer is resumed.
108
+ * On web, this occurs when the pointer is moved away from the viewport, the viewport is blurred or when the window is focused.
109
+ * On mobile, this occurs when the toast is released.
110
+ */
111
+ onResume?(): void
112
+ /**
113
+ * Event handler called when starting a swipe interaction. It can be prevented by calling `event.preventDefault`.
114
+ */
115
+ onSwipeStart?(event: SwipeEvent): void
116
+ /**
117
+ * Event handler called during a swipe interaction. It can be prevented by calling `event.preventDefault`.
118
+ */
119
+ onSwipeMove?(event: SwipeEvent): void
120
+ /**
121
+ * Event handler called at the cancellation of a swipe interaction. It can be prevented by calling `event.preventDefault`.
122
+ */
123
+ onSwipeCancel?(event: SwipeEvent): void
124
+ /**
125
+ * Event handler called at the end of a swipe interaction. It can be prevented by calling `event.preventDefault`.
126
+ */
127
+ onSwipeEnd?(event: SwipeEvent): void
128
+ /**
129
+ * The viewport's name to send the toast to. Used when using multiple viewports and want to forward toasts to different ones.
130
+ *
131
+ * @default "default"
132
+ */
133
+ viewportName?: string
134
+ }
135
+
136
+ const ToastImpl = React.forwardRef<TamaguiElement, ToastImplProps>(
137
+ (props: ScopedProps<ToastImplProps>, forwardedRef) => {
138
+ const {
139
+ __scopeToast,
140
+ type = 'foreground',
141
+ duration: durationProp,
142
+ open,
143
+ onClose,
144
+ onEscapeKeyDown,
145
+ onPause,
146
+ onResume,
147
+ onSwipeStart,
148
+ onSwipeMove,
149
+ onSwipeCancel,
150
+ onSwipeEnd,
151
+ viewportName,
152
+ ...toastProps
153
+ } = props
154
+ const isPresent = useIsPresent()
155
+ const context = useToastProviderContext(TOAST_NAME, __scopeToast)
156
+ const [node, setNode] = React.useState<TamaguiElement | null>(null)
157
+ const composedRefs = useComposedRefs(forwardedRef, (node) => setNode(node))
158
+ const duration = durationProp || context.duration
159
+ const closeTimerStartTimeRef = React.useRef(0)
160
+ const closeTimerRemainingTimeRef = React.useRef(duration)
161
+ const closeTimerRef = React.useRef(0)
162
+ const { onToastAdd, onToastRemove } = context
163
+ const handleClose = useEvent(() => {
164
+ if (!isPresent) {
165
+ // already removed from the react tree
166
+ return
167
+ }
168
+ // focus viewport if focus is within toast to read the remaining toast
169
+ // count to SR users and ensure focus isn't lost
170
+ if (isWeb) {
171
+ const isFocusInToast = (node as HTMLDivElement)?.contains(document.activeElement)
172
+ if (isFocusInToast) context.viewport?.focus()
173
+ }
174
+ onClose()
175
+ })
176
+
177
+ const startTimer = React.useCallback(
178
+ (duration: number) => {
179
+ if (!duration || duration === Infinity) return
180
+ clearTimeout(closeTimerRef.current)
181
+ closeTimerStartTimeRef.current = new Date().getTime()
182
+ closeTimerRef.current = setTimeout(handleClose, duration) as unknown as number
183
+ },
184
+ [handleClose]
185
+ )
186
+ const handleResume = React.useCallback(() => {
187
+ startTimer(closeTimerRemainingTimeRef.current)
188
+ onResume?.()
189
+ }, [onResume, startTimer])
190
+ const handlePause = React.useCallback(() => {
191
+ const elapsedTime = new Date().getTime() - closeTimerStartTimeRef.current
192
+ closeTimerRemainingTimeRef.current =
193
+ closeTimerRemainingTimeRef.current - elapsedTime
194
+ window.clearTimeout(closeTimerRef.current)
195
+ onPause?.()
196
+ }, [onPause])
197
+
198
+ React.useEffect(() => {
199
+ if (!isWeb) return
200
+ const viewport = context.viewport as HTMLElement
201
+ if (viewport) {
202
+ viewport.addEventListener(VIEWPORT_PAUSE, handlePause)
203
+ viewport.addEventListener(VIEWPORT_RESUME, handleResume)
204
+ return () => {
205
+ viewport.removeEventListener(VIEWPORT_PAUSE, handlePause)
206
+ viewport.removeEventListener(VIEWPORT_RESUME, handleResume)
207
+ }
208
+ }
209
+ }, [context.viewport, duration, onPause, onResume, startTimer])
210
+
211
+ // start timer when toast opens or duration changes.
212
+ // we include `open` in deps because closed !== unmounted when animating
213
+ // so it could reopen before being completely unmounted
214
+ React.useEffect(() => {
215
+ if (open && !context.isClosePausedRef.current) {
216
+ startTimer(duration)
217
+ }
218
+ }, [open, duration, context.isClosePausedRef, startTimer])
219
+
220
+ React.useEffect(() => {
221
+ onToastAdd()
222
+ return () => onToastRemove()
223
+ }, [onToastAdd, onToastRemove])
224
+
225
+ const announceTextContent = React.useMemo(() => {
226
+ if (!isWeb) return null
227
+ return node ? getAnnounceTextContent(node as HTMLDivElement) : null
228
+ }, [node])
229
+
230
+ const isHorizontalSwipe = ['left', 'right', 'horizontal'].includes(
231
+ context.swipeDirection
232
+ )
233
+
234
+ const driver = getAnimationDriver()
235
+ if (!driver) {
236
+ throw new Error('Must set animations in tamagui.config.ts')
237
+ }
238
+
239
+ const { useAnimatedNumber, useAnimatedNumberStyle } = driver
240
+
241
+ const animatedNumber = useAnimatedNumber(0)
242
+
243
+ // temp until reanimated useAnimatedNumber fix
244
+ const AnimatedView = (driver['NumberView'] ?? driver.View) as typeof Animated.View
245
+
246
+ const animatedStyles = useAnimatedNumberStyle(animatedNumber, (val) => {
247
+ return {
248
+ transform: [isHorizontalSwipe ? { translateX: val } : { translateY: val }],
249
+ }
250
+ })
251
+
252
+ const panResponder = React.useMemo(() => {
253
+ return PanResponder.create({
254
+ onMoveShouldSetPanResponder: (e) => {
255
+ onSwipeStart?.(e)
256
+ return true
257
+ },
258
+ onPanResponderGrant: (e) => {
259
+ if (!isWeb) {
260
+ handlePause?.()
261
+ }
262
+ },
263
+ onPanResponderMove: (e, { dy, dx }) => {
264
+ let y = 0
265
+ let x = 0
266
+ if (context.swipeDirection === 'horizontal') x = dx
267
+ else if (context.swipeDirection === 'left') x = Math.min(0, dx)
268
+ else if (context.swipeDirection === 'right') x = Math.max(0, dx)
269
+ else if (context.swipeDirection === 'vertical') y = dy
270
+ else if (context.swipeDirection === 'up') y = Math.min(0, dy)
271
+ else if (context.swipeDirection === 'down') y = Math.max(0, dy)
272
+
273
+ onSwipeMove?.(e)
274
+
275
+ const delta = { x, y }
276
+ animatedNumber.setValue(isHorizontalSwipe ? x : y, { type: 'direct' })
277
+ if (isDeltaInDirection(delta, context.swipeDirection, context.swipeThreshold)) {
278
+ onSwipeEnd?.(e)
279
+ }
280
+ },
281
+ onPanResponderEnd: (e, { dx, dy }) => {
282
+ if (
283
+ !isDeltaInDirection(
284
+ { x: dx, y: dy },
285
+ context.swipeDirection,
286
+ context.swipeThreshold
287
+ )
288
+ ) {
289
+ if (!isWeb) {
290
+ handleResume?.()
291
+ }
292
+ onSwipeCancel?.(e)
293
+ animatedNumber.setValue(0, { type: 'spring' })
294
+ }
295
+ },
296
+ })
297
+ }, [handlePause, handleResume])
298
+
299
+ // need to get the theme name from context and apply it again since portals don't retain the theme
300
+ const themeName = useThemeName()
301
+
302
+ return (
303
+ <>
304
+ {announceTextContent && (
305
+ <ToastAnnounce
306
+ __scopeToast={__scopeToast}
307
+ // Toasts are always role=status to avoid stuttering issues with role=alert in SRs.
308
+ role="status"
309
+ aria-live={type === 'foreground' ? 'assertive' : 'polite'}
310
+ aria-atomic
311
+ >
312
+ {announceTextContent}
313
+ </ToastAnnounce>
314
+ )}
315
+
316
+ <PortalItem hostName={viewportName ?? 'default'}>
317
+ <ToastInteractiveProvider
318
+ key={props.id}
319
+ scope={__scopeToast}
320
+ onClose={() => {
321
+ console.log('hellooow')
322
+ handleClose()
323
+ }}
324
+ >
325
+ <Dismissable
326
+ // asChild
327
+ onEscapeKeyDown={composeEventHandlers(onEscapeKeyDown, () => {
328
+ if (!context.isFocusedToastEscapeKeyDownRef.current) {
329
+ handleClose()
330
+ }
331
+ context.isFocusedToastEscapeKeyDownRef.current = false
332
+ })}
333
+ >
334
+ <Theme forceClassName name={themeName}>
335
+ <AnimatedView
336
+ {...panResponder?.panHandlers}
337
+ style={[{ margin: 'auto' }, animatedStyles]}
338
+ >
339
+ <Collection.ItemSlot scope={__scopeToast}>
340
+ <ToastImplFrame
341
+ // Ensure toasts are announced as status list or status when focused
342
+ role="status"
343
+ aria-live="off"
344
+ aria-atomic
345
+ tabIndex={0}
346
+ data-state={open ? 'open' : 'closed'}
347
+ data-swipe-direction={context.swipeDirection}
348
+ pointerEvents="auto"
349
+ // touchAction="none"
350
+ userSelect="none"
351
+ {...toastProps}
352
+ ref={composedRefs}
353
+ {...(isWeb && {
354
+ onKeyDown: composeEventHandlers(
355
+ (props as any).onKeyDown,
356
+ (event: KeyboardEvent) => {
357
+ if (event.key !== 'Escape') return
358
+ onEscapeKeyDown?.(event)
359
+ onEscapeKeyDown?.(event)
360
+ if (!event.defaultPrevented) {
361
+ context.isFocusedToastEscapeKeyDownRef.current = true
362
+ handleClose()
363
+ }
364
+ }
365
+ ),
366
+ })}
367
+ />
368
+ </Collection.ItemSlot>
369
+ </AnimatedView>
370
+ </Theme>
371
+ </Dismissable>
372
+ </ToastInteractiveProvider>
373
+ </PortalItem>
374
+ </>
375
+ )
376
+ }
377
+ )
378
+
379
+ ToastImpl.propTypes = {
380
+ type(props) {
381
+ if (props.type && !['foreground', 'background'].includes(props.type)) {
382
+ const error = `Invalid prop \`type\` supplied to \`${TOAST_NAME}\`. Expected \`foreground | background\`.`
383
+ return new Error(error)
384
+ }
385
+ return null
386
+ },
387
+ }
388
+
389
+ /* ---------------------------------------------------------------------------------------------- */
390
+
391
+ const isDeltaInDirection = (
392
+ delta: { x: number; y: number },
393
+ direction: SwipeDirection,
394
+ threshold = 0
395
+ ) => {
396
+ const deltaX = Math.abs(delta.x)
397
+ const deltaY = Math.abs(delta.y)
398
+ const isDeltaX = deltaX > deltaY
399
+ if (direction === 'left' || direction === 'right' || direction === 'horizontal') {
400
+ return isDeltaX && deltaX > threshold
401
+ } else {
402
+ return !isDeltaX && deltaY > threshold
403
+ }
404
+ }
405
+
406
+ function getAnnounceTextContent(container: HTMLElement) {
407
+ if (!isWeb) return ''
408
+ const textContent: string[] = []
409
+ const childNodes = Array.from(container.childNodes)
410
+
411
+ childNodes.forEach((node) => {
412
+ if (node.nodeType === node.TEXT_NODE && node.textContent)
413
+ textContent.push(node.textContent)
414
+ if (isHTMLElement(node)) {
415
+ const isHidden = node.ariaHidden || node.hidden || node.style.display === 'none'
416
+ const isExcluded = node.dataset.toastAnnounceExclude === ''
417
+
418
+ if (!isHidden) {
419
+ if (isExcluded) {
420
+ const altText = node.dataset.toastAnnounceAlt
421
+ if (altText) textContent.push(altText)
422
+ } else {
423
+ textContent.push(...getAnnounceTextContent(node))
424
+ }
425
+ }
426
+ }
427
+ })
428
+
429
+ // We return a collection of text rather than a single concatenated string.
430
+ // This allows SR VO to naturally pause break between nodes while announcing.
431
+ return textContent
432
+ }
433
+
434
+ function isHTMLElement(node: any): node is HTMLElement {
435
+ return node.nodeType === node.ELEMENT_NODE
436
+ }
437
+
438
+ export { ToastImpl, ToastImplFrame, ToastImplProps, useToastInteractiveContext }
439
+ export type { ToastProps }
@@ -0,0 +1,134 @@
1
+
2
+ import { createCollection } from '@tamagui/collection'
3
+ import { TamaguiElement, useId } from '@tamagui/core'
4
+ import type { Scope } from '@tamagui/create-context'
5
+ import { createContextScope } from '@tamagui/create-context'
6
+ import { PortalProvider } from '@tamagui/portal'
7
+ import * as React from 'react'
8
+
9
+
10
+ /* -------------------------------------------------------------------------------------------------
11
+ * ToastProvider
12
+ * -----------------------------------------------------------------------------------------------*/
13
+
14
+ const PROVIDER_NAME = 'ToastProvider'
15
+
16
+ const [Collection, useCollection, createCollectionScope] =
17
+ createCollection<TamaguiElement>('Toast')
18
+
19
+ type SwipeDirection = 'vertical' | 'up' | 'down' | 'horizontal' | 'left' | 'right'
20
+ type ToastProviderContextValue = {
21
+ id: string
22
+ label: string
23
+ duration: number
24
+ swipeDirection: SwipeDirection
25
+ swipeThreshold: number
26
+ toastCount: number
27
+ viewport: TamaguiElement | null
28
+ onViewportChange(viewport: TamaguiElement): void
29
+ onToastAdd(): void
30
+ onToastRemove(): void
31
+ isFocusedToastEscapeKeyDownRef: React.MutableRefObject<boolean>
32
+ isClosePausedRef: React.MutableRefObject<boolean>
33
+ }
34
+
35
+ type ScopedProps<P> = P & { __scopeToast?: Scope }
36
+ const [createToastContext, createToastScope] = createContextScope('Toast', [
37
+ createCollectionScope,
38
+ ])
39
+ const [ToastProviderProvider, useToastProviderContext] =
40
+ createToastContext<ToastProviderContextValue>(PROVIDER_NAME)
41
+
42
+ interface ToastProviderProps {
43
+ children?: React.ReactNode
44
+ /**
45
+ * An author-localized label for each toast. Used to help screen reader users
46
+ * associate the interruption with a toast.
47
+ * @defaultValue 'Notification'
48
+ */
49
+ label?: string
50
+ /**
51
+ * Time in milliseconds that each toast should remain visible for.
52
+ * @defaultValue 5000
53
+ */
54
+ duration?: number
55
+ /**
56
+ * Direction of pointer swipe that should close the toast.
57
+ * @defaultValue 'right'
58
+ */
59
+ swipeDirection?: SwipeDirection
60
+ /**
61
+ * Distance in pixels that the swipe must pass before a close is triggered.
62
+ * @defaultValue 50
63
+ */
64
+ swipeThreshold?: number
65
+ /**
66
+ * @defaultValue unique generated identifier
67
+ */
68
+ id?: string
69
+ }
70
+
71
+ const ToastProvider: React.FC<ToastProviderProps> = (
72
+ props: ScopedProps<ToastProviderProps>
73
+ ) => {
74
+ const {
75
+ __scopeToast,
76
+ id: providedId,
77
+ label = 'Notification',
78
+ duration = 5000,
79
+ swipeDirection = 'right',
80
+ swipeThreshold = 50,
81
+ children,
82
+ } = props
83
+ const id = providedId ?? useId()
84
+ const [viewport, setViewport] = React.useState<TamaguiElement | null>(null)
85
+ const [toastCount, setToastCount] = React.useState(0)
86
+ const isFocusedToastEscapeKeyDownRef = React.useRef(false)
87
+ const isClosePausedRef = React.useRef(false)
88
+
89
+ return (
90
+ <PortalProvider shouldAddRootHost={false} rootHostName="default">
91
+ <Collection.Provider scope={__scopeToast}>
92
+ <ToastProviderProvider
93
+ scope={__scopeToast}
94
+ id={id}
95
+ label={label}
96
+ duration={duration}
97
+ swipeDirection={swipeDirection}
98
+ swipeThreshold={swipeThreshold}
99
+ toastCount={toastCount}
100
+ viewport={viewport}
101
+ onViewportChange={setViewport}
102
+ onToastAdd={React.useCallback(() => {
103
+ setToastCount((prevCount) => prevCount + 1)
104
+ }, [])}
105
+ onToastRemove={React.useCallback(() => {
106
+ setToastCount((prevCount) => prevCount - 1)
107
+ }, [])}
108
+ isFocusedToastEscapeKeyDownRef={isFocusedToastEscapeKeyDownRef}
109
+ isClosePausedRef={isClosePausedRef}
110
+ >
111
+ {children}
112
+ </ToastProviderProvider>
113
+ </Collection.Provider>
114
+ </PortalProvider>
115
+ )
116
+ }
117
+
118
+ ToastProvider.propTypes = {
119
+ label(props) {
120
+ if (props.label && typeof props.label === 'string' && !props.label.trim()) {
121
+ const error = `Invalid prop \`label\` supplied to \`${PROVIDER_NAME}\`. Expected non-empty \`string\`.`
122
+ return new Error(error)
123
+ }
124
+ return null
125
+ },
126
+ }
127
+
128
+ ToastProvider.displayName = PROVIDER_NAME
129
+
130
+ export {
131
+ Collection, ToastProvider, createToastContext, createToastScope, useCollection, useToastProviderContext
132
+ }
133
+ export type { ScopedProps, SwipeDirection, ToastProviderProps }
134
+