@hozo/primitives 0.1.0 → 0.2.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 (57) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +7 -2
  3. package/dist/flat-list.native.d.ts +8 -8
  4. package/dist/flat-list.native.d.ts.map +1 -1
  5. package/dist/flat-list.native.js +55 -25
  6. package/dist/flat-list.native.js.map +1 -1
  7. package/dist/foundation.native.d.ts +16 -2
  8. package/dist/foundation.native.d.ts.map +1 -1
  9. package/dist/foundation.native.js.map +1 -1
  10. package/dist/index.d.ts +6 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +7 -9
  13. package/dist/index.js.map +1 -1
  14. package/dist/index.native.d.ts +1 -0
  15. package/dist/index.native.d.ts.map +1 -1
  16. package/dist/index.native.js +1 -0
  17. package/dist/index.native.js.map +1 -1
  18. package/dist/presence-context.d.ts +15 -0
  19. package/dist/presence-context.d.ts.map +1 -0
  20. package/dist/presence-context.js +11 -0
  21. package/dist/presence-context.js.map +1 -0
  22. package/dist/presence.d.ts +12 -0
  23. package/dist/presence.d.ts.map +1 -0
  24. package/dist/presence.js +45 -0
  25. package/dist/presence.js.map +1 -0
  26. package/dist/presence.native.d.ts +8 -0
  27. package/dist/presence.native.d.ts.map +1 -0
  28. package/dist/presence.native.js +66 -0
  29. package/dist/presence.native.js.map +1 -0
  30. package/dist/pressable.d.ts +9 -2
  31. package/dist/pressable.d.ts.map +1 -1
  32. package/dist/pressable.js +3 -3
  33. package/dist/pressable.js.map +1 -1
  34. package/dist/runtime-transition.native.d.ts +16 -1
  35. package/dist/runtime-transition.native.d.ts.map +1 -1
  36. package/dist/runtime-transition.native.js +34 -7
  37. package/dist/runtime-transition.native.js.map +1 -1
  38. package/dist/text-input.d.ts +319 -3
  39. package/dist/text-input.d.ts.map +1 -1
  40. package/dist/text-input.js +4 -3
  41. package/dist/text-input.js.map +1 -1
  42. package/dist/view.d.ts +295 -2
  43. package/dist/view.d.ts.map +1 -1
  44. package/dist/view.js +3 -3
  45. package/dist/view.js.map +1 -1
  46. package/package.json +4 -3
  47. package/src/flat-list.native.tsx +69 -47
  48. package/src/foundation.native.tsx +16 -1
  49. package/src/index.native.ts +2 -0
  50. package/src/index.ts +209 -219
  51. package/src/presence-context.ts +27 -0
  52. package/src/presence.native.tsx +81 -0
  53. package/src/presence.tsx +55 -0
  54. package/src/pressable.ts +66 -63
  55. package/src/runtime-transition.native.tsx +68 -7
  56. package/src/text-input.ts +74 -72
  57. package/src/view.ts +42 -36
package/src/index.ts CHANGED
@@ -6,7 +6,6 @@ import {
6
6
  } from '@hozo/engine'
7
7
  import {
8
8
  createElement,
9
- forwardRef,
10
9
  type HTMLAttributes,
11
10
  isValidElement,
12
11
  type ReactElement,
@@ -31,6 +30,7 @@ import {
31
30
  } from './windowing.ts'
32
31
 
33
32
  export * from './foundation.tsx'
33
+ export { Presence, type PresenceProps } from './presence.tsx'
34
34
 
35
35
  export interface HozoScrollEvent {
36
36
  nativeEvent: {
@@ -183,223 +183,216 @@ function useMeasurements(
183
183
  }, [rootRef, contentRef])
184
184
  }
185
185
 
186
- export interface HozoScrollViewProps extends SharedScrollableProps {}
186
+ export interface HozoScrollViewProps extends SharedScrollableProps {
187
+ /** Declared here, because React 19 takes `ref` as an ordinary prop. */
188
+ ref?: Ref<HTMLDivElement>
189
+ }
187
190
 
188
- export const HozoScrollView = forwardRef<HTMLDivElement, HozoScrollViewProps>(
189
- function HozoScrollView(
190
- {
191
- children,
192
- className,
193
- style,
194
- contentContainerStyle,
195
- horizontal,
196
- refreshing,
197
- onRefresh,
198
- refreshControl,
199
- showsVerticalScrollIndicator = true,
200
- showsHorizontalScrollIndicator = true,
201
- onScroll,
202
- scrollEventThrottle = 0,
203
- onScrollBeginDrag,
204
- onScrollEndDrag,
205
- onMomentumScrollEnd,
206
- onContentSizeChange,
207
- onLayout,
208
- testID,
209
- nativeID,
210
- pointerEvents,
211
- accessibilityLabel,
212
- accessibilityHint,
213
- accessibilityRole,
214
- accessibilityState,
215
- accessibilityValue,
216
- accessibilityLiveRegion,
217
- keyboardShouldPersistTaps: _keyboardShouldPersistTaps,
218
- stickyHeaderIndices: _stickyHeaderIndices,
219
- contentInsetAdjustmentBehavior: _contentInsetAdjustmentBehavior,
220
- automaticallyAdjustKeyboardInsets: _automaticallyAdjustKeyboardInsets,
221
- bounces: _bounces,
222
- pagingEnabled: _pagingEnabled,
223
- directionalLockEnabled: _directionalLockEnabled,
224
- nestedScrollEnabled: _nestedScrollEnabled,
225
- alwaysBounceVertical: _alwaysBounceVertical,
226
- overScrollMode: _overScrollMode,
227
- snapToOffsets: _snapToOffsets,
228
- snapToEnd: _snapToEnd,
229
- onPointerDown,
230
- onPointerDownCapture,
231
- onPointerMove,
232
- onPointerMoveCapture,
233
- onPointerUp,
234
- onPointerCancel,
235
- onLostPointerCapture,
236
- onStartShouldSetResponder,
237
- onStartShouldSetResponderCapture,
238
- onMoveShouldSetResponder,
239
- onMoveShouldSetResponderCapture,
240
- onResponderGrant,
241
- onResponderStart,
242
- onResponderMove,
243
- onResponderEnd,
244
- onResponderRelease,
245
- onResponderReject,
246
- onResponderTerminate,
247
- onResponderTerminationRequest,
248
- ...domProps
191
+ export function HozoScrollView({
192
+ ref: forwardedRef,
193
+ children,
194
+ className,
195
+ style,
196
+ contentContainerStyle,
197
+ horizontal,
198
+ refreshing,
199
+ onRefresh,
200
+ refreshControl,
201
+ showsVerticalScrollIndicator = true,
202
+ showsHorizontalScrollIndicator = true,
203
+ onScroll,
204
+ scrollEventThrottle = 0,
205
+ onScrollBeginDrag,
206
+ onScrollEndDrag,
207
+ onMomentumScrollEnd,
208
+ onContentSizeChange,
209
+ onLayout,
210
+ testID,
211
+ nativeID,
212
+ pointerEvents,
213
+ accessibilityLabel,
214
+ accessibilityHint,
215
+ accessibilityRole,
216
+ accessibilityState,
217
+ accessibilityValue,
218
+ accessibilityLiveRegion,
219
+ keyboardShouldPersistTaps: _keyboardShouldPersistTaps,
220
+ stickyHeaderIndices: _stickyHeaderIndices,
221
+ contentInsetAdjustmentBehavior: _contentInsetAdjustmentBehavior,
222
+ automaticallyAdjustKeyboardInsets: _automaticallyAdjustKeyboardInsets,
223
+ bounces: _bounces,
224
+ pagingEnabled: _pagingEnabled,
225
+ directionalLockEnabled: _directionalLockEnabled,
226
+ nestedScrollEnabled: _nestedScrollEnabled,
227
+ alwaysBounceVertical: _alwaysBounceVertical,
228
+ overScrollMode: _overScrollMode,
229
+ snapToOffsets: _snapToOffsets,
230
+ snapToEnd: _snapToEnd,
231
+ onPointerDown,
232
+ onPointerDownCapture,
233
+ onPointerMove,
234
+ onPointerMoveCapture,
235
+ onPointerUp,
236
+ onPointerCancel,
237
+ onLostPointerCapture,
238
+ onStartShouldSetResponder,
239
+ onStartShouldSetResponderCapture,
240
+ onMoveShouldSetResponder,
241
+ onMoveShouldSetResponderCapture,
242
+ onResponderGrant,
243
+ onResponderStart,
244
+ onResponderMove,
245
+ onResponderEnd,
246
+ onResponderRelease,
247
+ onResponderReject,
248
+ onResponderTerminate,
249
+ onResponderTerminationRequest,
250
+ ...domProps
251
+ }: HozoScrollViewProps): ReactElement {
252
+ const rootRef = useRef<HTMLDivElement>(null)
253
+ const contentRef = useRef<HTMLDivElement>(null)
254
+ const lastScroll = useRef(0)
255
+ const setRoot = useCallback(
256
+ (element: HTMLDivElement | null) => {
257
+ rootRef.current = element
258
+ assignRef(forwardedRef, element)
249
259
  },
250
- forwardedRef,
251
- ) {
252
- const rootRef = useRef<HTMLDivElement>(null)
253
- const contentRef = useRef<HTMLDivElement>(null)
254
- const lastScroll = useRef(0)
255
- const setRoot = useCallback(
256
- (element: HTMLDivElement | null) => {
257
- rootRef.current = element
258
- assignRef(forwardedRef, element)
259
- },
260
- [forwardedRef],
261
- )
262
- useMeasurements(rootRef, contentRef, onLayout, onContentSizeChange)
263
- const responderProps = {
264
- onStartShouldSetResponder,
265
- onStartShouldSetResponderCapture,
266
- onMoveShouldSetResponder,
267
- onMoveShouldSetResponderCapture,
268
- onResponderGrant,
269
- onResponderStart,
270
- onResponderMove,
271
- onResponderEnd,
272
- onResponderRelease,
273
- onResponderReject,
274
- onResponderTerminate,
275
- onResponderTerminationRequest,
276
- }
277
- const hasResponderContract = Object.values(responderProps).some(Boolean)
278
- const responder = useResponderDomProps(
279
- rootRef,
280
- responderProps,
281
- hasResponderContract && accessibilityState?.disabled !== true,
282
- )
283
- const nestedRefresh = refreshProps(refreshControl)
284
- const activeRefreshing = refreshing ?? nestedRefresh?.refreshing ?? false
285
- const activeRefresh = onRefresh ?? nestedRefresh?.onRefresh
286
- const hideScrollbar = horizontal
287
- ? !showsHorizontalScrollIndicator
288
- : !showsVerticalScrollIndicator
289
- const viewport = horizontal
290
- ? { overflowX: 'auto' as const, overflowY: 'hidden' as const }
291
- : { overflowX: 'hidden' as const, overflowY: 'auto' as const }
292
- const emitScroll = () => (rootRef.current ? nativeScrollEvent(rootRef.current) : undefined)
293
- const emitTo = (callback: ((event: HozoScrollEvent) => void) | undefined) => {
294
- const event = emitScroll()
295
- if (event) callback?.(event)
296
- }
260
+ [forwardedRef],
261
+ )
262
+ useMeasurements(rootRef, contentRef, onLayout, onContentSizeChange)
263
+ const responderProps = {
264
+ onStartShouldSetResponder,
265
+ onStartShouldSetResponderCapture,
266
+ onMoveShouldSetResponder,
267
+ onMoveShouldSetResponderCapture,
268
+ onResponderGrant,
269
+ onResponderStart,
270
+ onResponderMove,
271
+ onResponderEnd,
272
+ onResponderRelease,
273
+ onResponderReject,
274
+ onResponderTerminate,
275
+ onResponderTerminationRequest,
276
+ }
277
+ const hasResponderContract = Object.values(responderProps).some(Boolean)
278
+ const responder = useResponderDomProps(
279
+ rootRef,
280
+ responderProps,
281
+ hasResponderContract && accessibilityState?.disabled !== true,
282
+ )
283
+ const nestedRefresh = refreshProps(refreshControl)
284
+ const activeRefreshing = refreshing ?? nestedRefresh?.refreshing ?? false
285
+ const activeRefresh = onRefresh ?? nestedRefresh?.onRefresh
286
+ const hideScrollbar = horizontal ? !showsHorizontalScrollIndicator : !showsVerticalScrollIndicator
287
+ const viewport = horizontal
288
+ ? { overflowX: 'auto' as const, overflowY: 'hidden' as const }
289
+ : { overflowX: 'hidden' as const, overflowY: 'auto' as const }
290
+ const emitScroll = () => (rootRef.current ? nativeScrollEvent(rootRef.current) : undefined)
291
+ const emitTo = (callback: ((event: HozoScrollEvent) => void) | undefined) => {
292
+ const event = emitScroll()
293
+ if (event) callback?.(event)
294
+ }
297
295
 
298
- return createElement(
299
- 'div',
300
- {
301
- ...domProps,
302
- ref: setRoot,
303
- className,
304
- id: nativeID,
305
- 'data-testid': testID,
306
- role: accessibilityRole ?? domProps.role,
307
- 'data-hozo-pointer-events': pointerEvents,
308
- 'data-hozo-disabled': accessibilityState?.disabled ? '' : undefined,
309
- 'data-hozo-horizontal': horizontal ? '' : undefined,
310
- 'data-hozo-hide-scrollbar': hideScrollbar ? '' : undefined,
311
- 'aria-label': accessibilityLabel,
312
- 'aria-description': accessibilityHint,
313
- 'aria-disabled': accessibilityState?.disabled,
314
- 'aria-selected': accessibilityState?.selected,
315
- 'aria-checked': accessibilityState?.checked,
316
- 'aria-busy': accessibilityState?.busy || activeRefreshing || undefined,
317
- 'aria-expanded': accessibilityState?.expanded,
318
- 'aria-valuemin': accessibilityValue?.min,
319
- 'aria-valuemax': accessibilityValue?.max,
320
- 'aria-valuenow': accessibilityValue?.now,
321
- 'aria-valuetext': accessibilityValue?.text,
322
- 'aria-live': accessibilityLiveRegion === 'none' ? undefined : accessibilityLiveRegion,
323
- style: { ...viewport, ...hozoDomStyle(style) },
324
- onPointerDown:
325
- onScrollBeginDrag || responder.onPointerDown || onPointerDown
326
- ? (event) => {
327
- emitTo(onScrollBeginDrag)
328
- responder.onPointerDown?.(event)
329
- onPointerDown?.(event)
330
- }
331
- : undefined,
332
- onPointerDownCapture:
333
- responder.onPointerDownCapture || onPointerDownCapture
334
- ? (event) => {
335
- responder.onPointerDownCapture?.(event)
336
- onPointerDownCapture?.(event)
337
- }
338
- : undefined,
339
- onPointerMove:
340
- responder.onPointerMove || onPointerMove
341
- ? (event) => {
342
- responder.onPointerMove?.(event)
343
- onPointerMove?.(event)
344
- }
345
- : undefined,
346
- onPointerMoveCapture:
347
- responder.onPointerMoveCapture || onPointerMoveCapture
348
- ? (event) => {
349
- responder.onPointerMoveCapture?.(event)
350
- onPointerMoveCapture?.(event)
351
- }
352
- : undefined,
353
- onPointerUp:
354
- onScrollEndDrag || responder.onPointerUp || onPointerUp
355
- ? (event) => {
356
- emitTo(onScrollEndDrag)
357
- responder.onPointerUp?.(event)
358
- onPointerUp?.(event)
359
- }
360
- : undefined,
361
- onPointerCancel:
362
- responder.onPointerCancel || onPointerCancel
363
- ? (event) => {
364
- responder.onPointerCancel?.(event)
365
- onPointerCancel?.(event)
366
- }
367
- : undefined,
368
- onLostPointerCapture:
369
- responder.onLostPointerCapture || onLostPointerCapture
370
- ? (event) => {
371
- responder.onLostPointerCapture?.(event)
372
- onLostPointerCapture?.(event)
373
- }
374
- : undefined,
375
- onScroll: () => {
376
- const now = Date.now()
377
- const event = emitScroll()
378
- if (!event) return
379
- if (
380
- onScroll &&
381
- (scrollEventThrottle <= 0 || now - lastScroll.current >= scrollEventThrottle)
382
- ) {
383
- lastScroll.current = now
384
- onScroll(event)
385
- }
386
- },
387
- onScrollEnd: onMomentumScrollEnd ? () => emitTo(onMomentumScrollEnd) : undefined,
296
+ return createElement(
297
+ 'div',
298
+ {
299
+ ...domProps,
300
+ ref: setRoot,
301
+ className,
302
+ id: nativeID,
303
+ 'data-testid': testID,
304
+ role: accessibilityRole ?? domProps.role,
305
+ 'data-hozo-pointer-events': pointerEvents,
306
+ 'data-hozo-disabled': accessibilityState?.disabled ? '' : undefined,
307
+ 'data-hozo-horizontal': horizontal ? '' : undefined,
308
+ 'data-hozo-hide-scrollbar': hideScrollbar ? '' : undefined,
309
+ 'aria-label': accessibilityLabel,
310
+ 'aria-description': accessibilityHint,
311
+ 'aria-disabled': accessibilityState?.disabled,
312
+ 'aria-selected': accessibilityState?.selected,
313
+ 'aria-checked': accessibilityState?.checked,
314
+ 'aria-busy': accessibilityState?.busy || activeRefreshing || undefined,
315
+ 'aria-expanded': accessibilityState?.expanded,
316
+ 'aria-valuemin': accessibilityValue?.min,
317
+ 'aria-valuemax': accessibilityValue?.max,
318
+ 'aria-valuenow': accessibilityValue?.now,
319
+ 'aria-valuetext': accessibilityValue?.text,
320
+ 'aria-live': accessibilityLiveRegion === 'none' ? undefined : accessibilityLiveRegion,
321
+ style: { ...viewport, ...hozoDomStyle(style) },
322
+ onPointerDown:
323
+ onScrollBeginDrag || responder.onPointerDown || onPointerDown
324
+ ? (event) => {
325
+ emitTo(onScrollBeginDrag)
326
+ responder.onPointerDown?.(event)
327
+ onPointerDown?.(event)
328
+ }
329
+ : undefined,
330
+ onPointerDownCapture:
331
+ responder.onPointerDownCapture || onPointerDownCapture
332
+ ? (event) => {
333
+ responder.onPointerDownCapture?.(event)
334
+ onPointerDownCapture?.(event)
335
+ }
336
+ : undefined,
337
+ onPointerMove:
338
+ responder.onPointerMove || onPointerMove
339
+ ? (event) => {
340
+ responder.onPointerMove?.(event)
341
+ onPointerMove?.(event)
342
+ }
343
+ : undefined,
344
+ onPointerMoveCapture:
345
+ responder.onPointerMoveCapture || onPointerMoveCapture
346
+ ? (event) => {
347
+ responder.onPointerMoveCapture?.(event)
348
+ onPointerMoveCapture?.(event)
349
+ }
350
+ : undefined,
351
+ onPointerUp:
352
+ onScrollEndDrag || responder.onPointerUp || onPointerUp
353
+ ? (event) => {
354
+ emitTo(onScrollEndDrag)
355
+ responder.onPointerUp?.(event)
356
+ onPointerUp?.(event)
357
+ }
358
+ : undefined,
359
+ onPointerCancel:
360
+ responder.onPointerCancel || onPointerCancel
361
+ ? (event) => {
362
+ responder.onPointerCancel?.(event)
363
+ onPointerCancel?.(event)
364
+ }
365
+ : undefined,
366
+ onLostPointerCapture:
367
+ responder.onLostPointerCapture || onLostPointerCapture
368
+ ? (event) => {
369
+ responder.onLostPointerCapture?.(event)
370
+ onLostPointerCapture?.(event)
371
+ }
372
+ : undefined,
373
+ onScroll: () => {
374
+ const now = Date.now()
375
+ const event = emitScroll()
376
+ if (!event) return
377
+ if (
378
+ onScroll &&
379
+ (scrollEventThrottle <= 0 || now - lastScroll.current >= scrollEventThrottle)
380
+ ) {
381
+ lastScroll.current = now
382
+ onScroll(event)
383
+ }
388
384
  },
389
- activeRefresh
390
- ? createElement(HozoRefreshControl, {
391
- refreshing: activeRefreshing,
392
- onRefresh: activeRefresh,
393
- })
394
- : null,
395
- createElement(
396
- 'div',
397
- { ref: contentRef, style: hozoDomStyle(contentContainerStyle) },
398
- children,
399
- ),
400
- )
401
- },
402
- )
385
+ onScrollEnd: onMomentumScrollEnd ? () => emitTo(onMomentumScrollEnd) : undefined,
386
+ },
387
+ activeRefresh
388
+ ? createElement(HozoRefreshControl, {
389
+ refreshing: activeRefreshing,
390
+ onRefresh: activeRefresh,
391
+ })
392
+ : null,
393
+ createElement('div', { ref: contentRef, style: hozoDomStyle(contentContainerStyle) }, children),
394
+ )
395
+ }
403
396
 
404
397
  export interface HozoFlatListRenderInfo<T> {
405
398
  item: T
@@ -489,8 +482,9 @@ function invertedTransform(horizontal: boolean | undefined) {
489
482
  return horizontal ? [{ scaleX: -1 }] : [{ scaleY: -1 }]
490
483
  }
491
484
 
492
- function HozoFlatListInner<T>(props: HozoFlatListProps<T>, forwardedRef: Ref<HozoFlatListHandle>) {
485
+ export function HozoFlatList<T>(props: HozoFlatListProps<T> & { ref?: Ref<HozoFlatListHandle> }) {
493
486
  const {
487
+ ref: forwardedRef,
494
488
  data = [],
495
489
  renderItem,
496
490
  keyExtractor,
@@ -1101,10 +1095,6 @@ function HozoFlatListInner<T>(props: HozoFlatListProps<T>, forwardedRef: Ref<Hoz
1101
1095
  )
1102
1096
  }
1103
1097
 
1104
- export const HozoFlatList = forwardRef(HozoFlatListInner) as <T>(
1105
- props: HozoFlatListProps<T> & { ref?: Ref<HozoFlatListHandle> },
1106
- ) => ReactElement
1107
-
1108
1098
  export { HozoFlatList as FlatList, HozoScrollView as ScrollView }
1109
1099
  export type FlatListRenderInfo<T> = HozoFlatListRenderInfo<T>
1110
1100
  export type FlatListProps<T> = HozoFlatListProps<T>
@@ -0,0 +1,27 @@
1
+ // What `Presence` tells the elements that animate out inside it, on
2
+ // Native (decision 007, amendment 1).
3
+ //
4
+ // On Web the same thing travels as an attribute, `data-state`, and CSS
5
+ // does the rest. React Native has no attributes to select on, so the
6
+ // state is a context instead, and `HozoAnimated` -- the component the
7
+ // compiler puts in place of an element with a `data-[state=closed]:`
8
+ // class -- reads it.
9
+
10
+ import { createContext } from 'react'
11
+
12
+ export type PresenceState = 'open' | 'closed'
13
+
14
+ export interface PresenceContextValue {
15
+ state: PresenceState
16
+ /**
17
+ * Called by an element that will animate out, once, on mount. `Presence`
18
+ * waits for every registered element before it removes its child, and
19
+ * removes it at once when none registered. The returned function
20
+ * unregisters.
21
+ */
22
+ register(id: symbol, durationMs: number): () => void
23
+ /** Called by a registered element when its exit animation has ended. */
24
+ done(id: symbol): void
25
+ }
26
+
27
+ export const PresenceContext = createContext<PresenceContextValue | null>(null)
@@ -0,0 +1,81 @@
1
+ // Keeps a child mounted while it animates out (decision 007, slice 2).
2
+ //
3
+ // React removes an element the moment it stops being rendered, so nothing
4
+ // can animate after that. `Presence` holds on to its child after `show`
5
+ // turns false, tells it it is leaving, and lets it go when every element
6
+ // inside that animates out has finished.
7
+ //
8
+ // The Web half is `./presence.tsx`. Both are written against the same
9
+ // class: `data-[state=closed]:`.
10
+
11
+ import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
12
+ import { PresenceContext, type PresenceContextValue } from './presence-context.ts'
13
+
14
+ export interface PresenceProps {
15
+ /** Whether the child is shown. Turning it false starts the exit. */
16
+ show: boolean
17
+ children?: ReactNode
18
+ }
19
+
20
+ /**
21
+ * How long past the longest registered transition to wait for one that
22
+ * never reports. An animation interrupted by an unmount above, or one the
23
+ * runtime dropped, would otherwise keep the child on screen for good.
24
+ */
25
+ const GRACE_MS = 100
26
+
27
+ export function Presence({ show, children }: PresenceProps) {
28
+ const [mounted, setMounted] = useState(show)
29
+ // Set during render rather than in an effect, so a child that is shown
30
+ // again appears in the same commit instead of one frame late.
31
+ if (show && !mounted) setMounted(true)
32
+
33
+ const exiting = useRef(new Map<symbol, number>())
34
+ const waiting = useRef(new Set<symbol>())
35
+
36
+ const finish = useCallback(() => {
37
+ waiting.current.clear()
38
+ setMounted(false)
39
+ }, [])
40
+
41
+ useEffect(() => {
42
+ // Shown again before the exit ended: whatever was leaving is staying.
43
+ if (show) {
44
+ waiting.current.clear()
45
+ return
46
+ }
47
+ if (!mounted) return
48
+ if (exiting.current.size === 0) {
49
+ finish()
50
+ return
51
+ }
52
+ waiting.current = new Set(exiting.current.keys())
53
+ const longest = Math.max(...exiting.current.values())
54
+ const timer = setTimeout(finish, longest + GRACE_MS)
55
+ return () => clearTimeout(timer)
56
+ }, [show, mounted, finish])
57
+
58
+ const register = useCallback((id: symbol, durationMs: number) => {
59
+ exiting.current.set(id, durationMs)
60
+ return () => {
61
+ exiting.current.delete(id)
62
+ waiting.current.delete(id)
63
+ }
64
+ }, [])
65
+
66
+ const done = useCallback(
67
+ (id: symbol) => {
68
+ if (!waiting.current.delete(id)) return
69
+ if (waiting.current.size === 0) finish()
70
+ },
71
+ [finish],
72
+ )
73
+
74
+ const value = useMemo<PresenceContextValue>(
75
+ () => ({ state: show ? 'open' : 'closed', register, done }),
76
+ [show, register, done],
77
+ )
78
+
79
+ if (!mounted) return null
80
+ return <PresenceContext.Provider value={value}>{children}</PresenceContext.Provider>
81
+ }
@@ -0,0 +1,55 @@
1
+ // Keeps a child mounted while it animates out (decision 007, slice 2).
2
+ //
3
+ // React removes an element the moment it stops being rendered, so nothing
4
+ // can animate after that. `Presence` holds on to its child after `show`
5
+ // turns false, sets `data-state="closed"` on it, and removes it when its
6
+ // transition or animation ends. The exit itself is CSS: a
7
+ // `data-[state=closed]:` class and a `transition-*` one, so it costs no
8
+ // script beyond this. The timing lives in `usePresence`
9
+ // (`@hozo/behaviors`), which Hozo's overlays use for their panels.
10
+ //
11
+ // The Native half is `./presence.native.tsx`, written against the same
12
+ // class.
13
+
14
+ import { usePresence } from '@hozo/behaviors'
15
+ import { cloneElement, isValidElement, type ReactElement, type ReactNode, type Ref } from 'react'
16
+
17
+ export interface PresenceProps {
18
+ /** Whether the child is shown. Turning it false starts the exit. */
19
+ show: boolean
20
+ /**
21
+ * One element, which receives `data-state`. A Hozo primitive passes it
22
+ * to the DOM; a component of your own has to forward it.
23
+ */
24
+ children?: ReactNode
25
+ }
26
+
27
+ function setRef<T>(ref: Ref<T> | undefined, value: T | null) {
28
+ if (typeof ref === 'function') ref(value)
29
+ else if (ref) (ref as { current: T | null }).current = value
30
+ }
31
+
32
+ export function Presence({ show, children }: PresenceProps) {
33
+ const presence = usePresence(show)
34
+
35
+ if (!presence.mounted) return null
36
+ if (!isValidElement(children)) return children ?? null
37
+ const child = children as ReactElement<Record<string, unknown>>
38
+ const childRef = child.props.ref as Ref<Element> | undefined
39
+ const chain =
40
+ (name: 'onTransitionEnd' | 'onAnimationEnd') =>
41
+ (event: { target: EventTarget; currentTarget: EventTarget }) => {
42
+ const own = child.props[name]
43
+ if (typeof own === 'function') own(event)
44
+ presence[name](event)
45
+ }
46
+ return cloneElement(child, {
47
+ 'data-state': presence.state,
48
+ ref: (node: Element | null) => {
49
+ presence.ref(node)
50
+ setRef(childRef, node)
51
+ },
52
+ onTransitionEnd: chain('onTransitionEnd'),
53
+ onAnimationEnd: chain('onAnimationEnd'),
54
+ })
55
+ }