@hozo/engine 0.3.0 → 0.4.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 (125) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +8 -4
  3. package/dist/authored-gap.d.ts +11 -0
  4. package/dist/authored-gap.d.ts.map +1 -0
  5. package/dist/authored-gap.js +45 -0
  6. package/dist/authored-gap.js.map +1 -0
  7. package/dist/class-resolver.d.ts +41 -3
  8. package/dist/class-resolver.d.ts.map +1 -1
  9. package/dist/class-resolver.js +160 -23
  10. package/dist/class-resolver.js.map +1 -1
  11. package/dist/class-transition.d.ts +32 -0
  12. package/dist/class-transition.d.ts.map +1 -0
  13. package/dist/class-transition.js +48 -0
  14. package/dist/class-transition.js.map +1 -0
  15. package/dist/color-transition.d.ts +2 -0
  16. package/dist/color-transition.d.ts.map +1 -1
  17. package/dist/color-transition.js +4 -0
  18. package/dist/color-transition.js.map +1 -1
  19. package/dist/cx.d.ts +4 -0
  20. package/dist/cx.d.ts.map +1 -0
  21. package/dist/cx.js +17 -0
  22. package/dist/cx.js.map +1 -0
  23. package/dist/dom-style.d.ts +1 -0
  24. package/dist/dom-style.d.ts.map +1 -1
  25. package/dist/dom-style.js +4 -0
  26. package/dist/dom-style.js.map +1 -1
  27. package/dist/gap-styles.d.ts +3 -0
  28. package/dist/gap-styles.d.ts.map +1 -0
  29. package/dist/gap-styles.js +7 -0
  30. package/dist/gap-styles.js.map +1 -0
  31. package/dist/generated/animated.d.ts +3 -0
  32. package/dist/generated/animated.d.ts.map +1 -0
  33. package/dist/generated/animated.js +7 -0
  34. package/dist/generated/animated.js.map +1 -0
  35. package/dist/generated/class-resolver.d.ts +1 -1
  36. package/dist/generated/class-resolver.d.ts.map +1 -1
  37. package/dist/generated/class-resolver.js +1 -1
  38. package/dist/generated/class-resolver.js.map +1 -1
  39. package/dist/generated/gap-styles.d.ts +3 -0
  40. package/dist/generated/gap-styles.d.ts.map +1 -0
  41. package/dist/generated/gap-styles.js +4 -0
  42. package/dist/generated/gap-styles.js.map +1 -0
  43. package/dist/generated/safe-area.d.ts +1 -1
  44. package/dist/generated/safe-area.d.ts.map +1 -1
  45. package/dist/generated/safe-area.js +1 -1
  46. package/dist/generated/safe-area.js.map +1 -1
  47. package/dist/generated/spread-styles.d.ts +2 -0
  48. package/dist/generated/spread-styles.d.ts.map +1 -0
  49. package/dist/generated/spread-styles.js +3 -0
  50. package/dist/generated/spread-styles.js.map +1 -0
  51. package/dist/generated/text-inheritance-protocol.d.ts +3 -0
  52. package/dist/generated/text-inheritance-protocol.d.ts.map +1 -0
  53. package/dist/generated/text-inheritance-protocol.js +3 -0
  54. package/dist/generated/text-inheritance-protocol.js.map +1 -0
  55. package/dist/generated/text-size-context.d.ts +2 -0
  56. package/dist/generated/text-size-context.d.ts.map +1 -0
  57. package/dist/generated/text-size-context.js +3 -0
  58. package/dist/generated/text-size-context.js.map +1 -0
  59. package/dist/hooks.native.js +1 -1
  60. package/dist/index.d.ts +6 -3
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +6 -3
  63. package/dist/index.js.map +1 -1
  64. package/dist/presence-context.d.ts +15 -0
  65. package/dist/presence-context.d.ts.map +1 -0
  66. package/dist/presence-context.js +11 -0
  67. package/dist/presence-context.js.map +1 -0
  68. package/dist/project.d.ts +8 -0
  69. package/dist/project.d.ts.map +1 -1
  70. package/dist/project.js +7 -0
  71. package/dist/project.js.map +1 -1
  72. package/dist/project.native.d.ts +1 -1
  73. package/dist/project.native.d.ts.map +1 -1
  74. package/dist/project.native.js +1 -1
  75. package/dist/project.native.js.map +1 -1
  76. package/dist/responder.d.ts +34 -0
  77. package/dist/responder.d.ts.map +1 -1
  78. package/dist/responder.js +52 -0
  79. package/dist/responder.js.map +1 -1
  80. package/dist/runtime-transition.native.d.ts +37 -0
  81. package/dist/runtime-transition.native.d.ts.map +1 -0
  82. package/dist/runtime-transition.native.js +252 -0
  83. package/dist/runtime-transition.native.js.map +1 -0
  84. package/dist/safe-area.native.d.ts +12 -0
  85. package/dist/safe-area.native.d.ts.map +1 -1
  86. package/dist/safe-area.native.js +44 -21
  87. package/dist/safe-area.native.js.map +1 -1
  88. package/dist/spread-styles.d.ts +14 -0
  89. package/dist/spread-styles.d.ts.map +1 -0
  90. package/dist/spread-styles.js +56 -0
  91. package/dist/spread-styles.js.map +1 -0
  92. package/dist/text-inheritance.d.ts +35 -0
  93. package/dist/text-inheritance.d.ts.map +1 -0
  94. package/dist/text-inheritance.js +48 -0
  95. package/dist/text-inheritance.js.map +1 -0
  96. package/dist/text-style.d.ts +8 -0
  97. package/dist/text-style.d.ts.map +1 -0
  98. package/dist/text-style.js +34 -0
  99. package/dist/text-style.js.map +1 -0
  100. package/package.json +22 -2
  101. package/src/authored-gap.ts +41 -0
  102. package/src/class-resolver.ts +213 -7
  103. package/src/class-transition.ts +71 -0
  104. package/src/color-transition.ts +5 -0
  105. package/src/cx.ts +18 -0
  106. package/src/dom-style.ts +3 -0
  107. package/src/gap-styles.ts +11 -0
  108. package/src/generated/animated.ts +15 -0
  109. package/src/generated/class-resolver.ts +7 -1
  110. package/src/generated/gap-styles.ts +3 -0
  111. package/src/generated/safe-area.ts +5 -1
  112. package/src/generated/spread-styles.ts +2 -0
  113. package/src/generated/text-inheritance-protocol.ts +9 -0
  114. package/src/generated/text-size-context.ts +2 -0
  115. package/src/hooks.native.ts +1 -1
  116. package/src/index.ts +17 -2
  117. package/src/presence-context.ts +27 -0
  118. package/src/project.native.ts +1 -1
  119. package/src/project.ts +9 -0
  120. package/src/responder.ts +52 -0
  121. package/src/runtime-transition.native.tsx +324 -0
  122. package/src/safe-area.native.ts +59 -24
  123. package/src/spread-styles.ts +74 -0
  124. package/src/text-inheritance.ts +75 -0
  125. package/src/text-style.ts +35 -0
package/src/index.ts CHANGED
@@ -28,16 +28,30 @@ export {
28
28
  hozoBackdropFilterAdapter,
29
29
  } from './backdrop.ts'
30
30
 
31
- export { type ClassResolver, createClassResolver, type StyleObject } from './class-resolver.ts'
32
- export { blendColor } from './color-transition.ts'
31
+ export {
32
+ type ClassResolver,
33
+ type ClassResolverPlan,
34
+ createClassResolver,
35
+ type StyleObject,
36
+ } from './class-resolver.ts'
37
+ export {
38
+ type ClassTransition,
39
+ type ClassTransitionSpec,
40
+ type ClassTransitionTable,
41
+ createClassTransitions,
42
+ } from './class-transition.ts'
43
+ export { blendColor, canBlendColor } from './color-transition.ts'
44
+ export { type CxValue, cx } from './cx.ts'
33
45
  export { type HozoDomStyle, hozoDomProps, hozoDomStyle } from './dom-style.ts'
34
46
  export { externalLinkAttributes } from './external-link.ts'
35
47
  export { hozoInteractive } from './interactive.ts'
36
48
  export {
49
+ createSpreadResponder,
37
50
  type HozoResponderEvent,
38
51
  type HozoResponderTouch,
39
52
  type HozoTouchHistory,
40
53
  type HozoTouchTrack,
54
+ RESPONDER_PROPS,
41
55
  type ResponderProps,
42
56
  useResponderDomProps,
43
57
  } from './responder.ts'
@@ -47,4 +61,5 @@ export {
47
61
  HozoTextSizeContext,
48
62
  useHozoTextSize,
49
63
  } from './text-size.ts'
64
+ export { hozoSplitTextStyle } from './text-style.ts'
50
65
  export { hozoViewBase, hozoViewClassName } from './view-base.ts'
@@ -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)
@@ -1 +1 @@
1
- export { hozoClasses, hozoPreflight } from './project.ts'
1
+ export { hozoClasses, hozoClassTransitions, hozoPreflight } from './project.ts'
package/src/project.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createClassResolver } from './class-resolver.ts'
2
+ import type { ClassTransitionTable } from './class-transition.ts'
2
3
 
3
4
  /**
4
5
  * Project-wide Native defaults when no bundler integration supplies them.
@@ -18,3 +19,11 @@ export const hozoPreflight = true
18
19
  * what those props did before.
19
20
  */
20
21
  export const hozoClasses = createClassResolver({})
22
+
23
+ /**
24
+ * What the project's runtime-resolved classes say about transitions (#1450),
25
+ * for the same components, read through `createClassTransitions`.
26
+ * Redirected like `hozoClasses`; unconfigured, it is empty, so those
27
+ * components keep switching at once.
28
+ */
29
+ export const hozoClassTransitions: ClassTransitionTable = {}
package/src/responder.ts CHANGED
@@ -370,3 +370,55 @@ export function createResponderDomProps<T extends HTMLElement>(
370
370
  onLostPointerCapture,
371
371
  }
372
372
  }
373
+
374
+ /** The responder props by name, for a caller that has them in an untyped bag. */
375
+ export const RESPONDER_PROPS = [
376
+ 'onStartShouldSetResponder',
377
+ 'onStartShouldSetResponderCapture',
378
+ 'onMoveShouldSetResponder',
379
+ 'onMoveShouldSetResponderCapture',
380
+ 'onResponderGrant',
381
+ 'onResponderStart',
382
+ 'onResponderMove',
383
+ 'onResponderEnd',
384
+ 'onResponderRelease',
385
+ 'onResponderReject',
386
+ 'onResponderTerminate',
387
+ 'onResponderTerminationRequest',
388
+ ] as const satisfies readonly (keyof ResponderProps)[]
389
+
390
+ const latestResponderProps = new WeakMap<HTMLElement, { current: ResponderProps }>()
391
+
392
+ /**
393
+ * The responder without a hook, for a spread translated during render (#1126).
394
+ *
395
+ * `useResponderDomProps` keeps the latest props in a ref and releases the
396
+ * pointer in an effect. A compiled element's spread has neither, so the
397
+ * element it lands on holds the latest props instead: `attach` (from a
398
+ * callback ref) records them against the element, and the handlers read
399
+ * them from there, so a re-render during a gesture does not leave the
400
+ * registration with the props of the render that began it. `release`, when
401
+ * the element goes, is the hook's effect cleanup.
402
+ */
403
+ export function createSpreadResponder(props: ResponderProps) {
404
+ const elementRef: { current: HTMLElement | null } = { current: null }
405
+ const propsRef = {
406
+ get current(): ResponderProps {
407
+ const element = elementRef.current
408
+ return (element && latestResponderProps.get(element)?.current) || props
409
+ },
410
+ }
411
+ return {
412
+ handlers: createResponderDomProps(elementRef, propsRef),
413
+ attach(element: HTMLElement) {
414
+ elementRef.current = element
415
+ const box = latestResponderProps.get(element)
416
+ if (box) box.current = props
417
+ else latestResponderProps.set(element, { current: props })
418
+ },
419
+ release(element: HTMLElement) {
420
+ latestResponderProps.delete(element)
421
+ if (activeResponder?.element === element) releaseRegistration(activeResponder.props)
422
+ },
423
+ }
424
+ }
@@ -0,0 +1,324 @@
1
+ // A transition driven by the style changing, rather than by an
2
+ // interaction.
3
+ //
4
+ // `./pressable.native.tsx` already animates, and it is built the other way
5
+ // round: it knows the four interaction booleans, calls the author's `style`
6
+ // function for each combination, and animates between the results. That
7
+ // shape is right there and wrong here, because the conditions this has to
8
+ // serve are ambient -- `dark:`, `md:`, `motion-reduce:` -- and the
9
+ // compiler expresses those as a guarded array, `[base, __hozoDark &&
10
+ // dark]`, which is already resolved by the time it arrives.
11
+ //
12
+ // So this one asks a simpler question: what did the style just become, and
13
+ // what was it before? Everything that differs and can be interpolated is
14
+ // animated to its new value; everything else is passed straight through.
15
+ // That covers the interaction case too, in principle, which is why this is
16
+ // not named after the conditions that prompted it.
17
+ //
18
+ // Colours run on the JavaScript driver and opacity and transforms do not.
19
+ // React Native cannot interpolate a colour natively, so mixing the two in
20
+ // one `Animated.timing` would drag the fast ones onto the slow driver.
21
+ // They are separate animations for that reason and not for tidiness.
22
+
23
+ import { type ReactNode, useContext, useEffect, useMemo, useRef, useState } from 'react'
24
+ import { Animated, Easing, type StyleProp, StyleSheet, type ViewStyle } from 'react-native'
25
+ import { PresenceContext } from './presence-context.ts'
26
+
27
+ export interface HozoTransitionSpec {
28
+ duration: number
29
+ delay?: number
30
+ easing: 'linear' | 'ease-in' | 'ease-out' | 'ease-in-out'
31
+ /**
32
+ * The CSS `transition-property` list, as `transition-[left,width]` or
33
+ * `transition-all` writes it. Only the position and size keys read it:
34
+ * opacity, colours and transforms animate whenever they change, as they
35
+ * always have, and a spec without it animates no position or size.
36
+ */
37
+ properties?: readonly string[]
38
+ }
39
+
40
+ /** The colour properties worth animating, in the order they are read. */
41
+ const COLOR_KEYS = ['backgroundColor', 'borderColor', 'color'] as const
42
+
43
+ // Position and size, which React Native lays out with every frame of the
44
+ // animation: they run on the JavaScript driver with the colours, and only
45
+ // when the spec names them. A `transition-colors` beside an `md:w-80` has
46
+ // never moved the width, and a resize that started animating because this
47
+ // learned to would be a change nobody asked for.
48
+ //
49
+ // Each CSS name maps to the React Native keys it covers. `start` and `end`
50
+ // stay logical, so a thumb that moves by its inline-start inset slides the
51
+ // right way in a right-to-left layout with nothing mirrored here: Yoga
52
+ // resolves the side.
53
+ const LAYOUT_PROPERTIES: Record<string, readonly string[]> = {
54
+ inset: ['top', 'right', 'bottom', 'left', 'start', 'end'],
55
+ 'inset-inline': ['start', 'end', 'left', 'right'],
56
+ 'inset-block': ['top', 'bottom'],
57
+ 'inset-inline-start': ['start'],
58
+ 'inset-inline-end': ['end'],
59
+ top: ['top'],
60
+ right: ['right'],
61
+ bottom: ['bottom'],
62
+ left: ['left'],
63
+ width: ['width'],
64
+ height: ['height'],
65
+ }
66
+
67
+ function layoutKeys(properties: readonly string[] | undefined): readonly string[] {
68
+ if (!properties) return []
69
+ if (properties.includes('all')) return [...new Set(Object.values(LAYOUT_PROPERTIES).flat())]
70
+ return [...new Set(properties.flatMap((property) => LAYOUT_PROPERTIES[property] ?? []))]
71
+ }
72
+
73
+ /**
74
+ * The transform entries, flattened to `{ key: value }`.
75
+ *
76
+ * React Native's `transform` is an array of one-key objects, which is a
77
+ * shape nothing can be diffed against directly -- two arrays with the same
78
+ * entries in a different order are the same transform and not equal.
79
+ */
80
+ function transformMap(style: ViewStyle | undefined): Map<string, number> {
81
+ const out = new Map<string, number>()
82
+ const transform = style?.transform
83
+ if (!Array.isArray(transform)) return out
84
+ for (const entry of transform) {
85
+ for (const [key, value] of Object.entries(entry as Record<string, unknown>)) {
86
+ if (typeof value === 'number') out.set(key, value)
87
+ }
88
+ }
89
+ return out
90
+ }
91
+
92
+ /**
93
+ * The style an interrupted animation is showing: `to`, with each number it
94
+ * animates (opacity, and the position and size keys the spec names) put
95
+ * `at` of the way from `from`. `at` is the eased progress, so this is the
96
+ * value on screen and not a point on a straight line.
97
+ */
98
+ function midway(
99
+ from: ViewStyle,
100
+ to: ViewStyle,
101
+ at: number,
102
+ properties: readonly string[] | undefined,
103
+ ): ViewStyle {
104
+ if (at >= 1) return to
105
+ const out: Record<string, unknown> = { ...to }
106
+ for (const key of ['opacity', ...layoutKeys(properties)]) {
107
+ const start = (from as Record<string, unknown>)[key]
108
+ const end = (to as Record<string, unknown>)[key]
109
+ if (typeof start === 'number' && typeof end === 'number') out[key] = start + (end - start) * at
110
+ }
111
+ return out as ViewStyle
112
+ }
113
+
114
+ /** What a transform key means when nothing sets it. */
115
+ function identity(key: string): number {
116
+ return key.startsWith('scale') ? 1 : 0
117
+ }
118
+
119
+ export interface HozoAnimatedProps {
120
+ style?: StyleProp<ViewStyle>
121
+ hozoTransition?: HozoTransitionSpec
122
+ /**
123
+ * The first frame of an enter animation, from a `starting:` class
124
+ * (decision 007). The element mounts at these values and transitions to
125
+ * `style`, which is what `@starting-style` does on Web. Read once, on
126
+ * mount: it is where the element enters from, not a style it keeps.
127
+ */
128
+ hozoStarting?: StyleProp<ViewStyle>
129
+ /**
130
+ * The last frame of an exit animation, from a `data-[state=closed]:`
131
+ * class (decision 007, amendment 1). Laid over `style` while the
132
+ * enclosing `Presence` is closing, which is what the attribute selector
133
+ * does on Web; `Presence` removes the element when the transition to it
134
+ * ends.
135
+ */
136
+ hozoExit?: StyleProp<ViewStyle>
137
+ children?: ReactNode
138
+ [key: string]: unknown
139
+ }
140
+
141
+ export function HozoAnimated({
142
+ style,
143
+ hozoTransition,
144
+ hozoStarting,
145
+ hozoExit,
146
+ children,
147
+ ...props
148
+ }: HozoAnimatedProps) {
149
+ const presence = useContext(PresenceContext)
150
+ // Only an element that has somewhere to leave to takes part. One without
151
+ // `hozoExit` neither waits for `Presence` nor makes it wait.
152
+ const exits = presence !== null && hozoExit != null
153
+ const leaving = exits && presence.state === 'closed'
154
+ const flat = useMemo(
155
+ () => StyleSheet.flatten(leaving ? [style, hozoExit] : style) ?? {},
156
+ [style, hozoExit, leaving],
157
+ )
158
+
159
+ // One progress value per animation rather than one per property. The
160
+ // properties change together -- they are the same rule flipping -- so
161
+ // animating a single 0 → 1 and interpolating each property from its old
162
+ // value to its new one is both cheaper and impossible to get out of
163
+ // step with itself.
164
+ const progress = useRef(new Animated.Value(1)).current
165
+ // Without `hozoStarting` the first render has nothing to animate from --
166
+ // `from` and `to` are the same style, and the mount effect below runs an
167
+ // animation that moves nothing. With it, `from` is the starting frame
168
+ // laid over the style, so that same mount effect is the enter animation.
169
+ const [entersFrom] = useState<ViewStyle>(() =>
170
+ hozoStarting ? { ...flat, ...(StyleSheet.flatten(hozoStarting) ?? {}) } : flat,
171
+ )
172
+ const from = useRef<ViewStyle>(entersFrom)
173
+ const to = useRef<ViewStyle>(flat)
174
+
175
+ // What changed, computed during render so the effect below has nothing
176
+ // to work out. `JSON.stringify` on the two style objects is enough: they
177
+ // are flat, their values are primitives, and the compiler emits the keys
178
+ // in a stable order.
179
+ const signature = JSON.stringify(flat)
180
+ const previous = useRef(signature)
181
+ // How far the running animation has got, which is 1 once it has ended.
182
+ const reached = useRef(1)
183
+ if (previous.current !== signature) {
184
+ // The *visible* style becomes the new starting point, not the
185
+ // previous target. Interrupting a half-finished fade and restarting
186
+ // from where it was going would make it jump to the end first. For a
187
+ // number that is the point between the two the animation had reached;
188
+ // a colour or a transform still starts from the previous target.
189
+ from.current = midway(from.current, to.current, reached.current, hozoTransition?.properties)
190
+ to.current = flat
191
+ previous.current = signature
192
+ }
193
+
194
+ useEffect(() => {
195
+ if (!hozoTransition) return
196
+ const listener = progress.addListener(({ value }) => {
197
+ reached.current = value
198
+ })
199
+ return () => progress.removeListener(listener)
200
+ }, [progress, hozoTransition])
201
+
202
+ // Registered for as long as it can exit, so `Presence` knows to wait for
203
+ // it and how long to wait before giving up.
204
+ const [id] = useState(() => Symbol('HozoAnimated'))
205
+ const register = exits ? presence.register : undefined
206
+ const exitMs = hozoTransition ? hozoTransition.duration + (hozoTransition.delay ?? 0) : 0
207
+ useEffect(() => register?.(id, exitMs), [register, id, exitMs])
208
+ // Read when the animation ends, which is after this render's values may
209
+ // have changed.
210
+ const leavingNow = useRef(leaving)
211
+ leavingNow.current = leaving
212
+ const done = presence?.done
213
+ const doneNow = useRef(done)
214
+ doneNow.current = done
215
+
216
+ // `signature` is read above rather than inside, and it is what says the
217
+ // style moved -- `hozoTransition` does not change when only the values
218
+ // do. Without it a style change starts no transition at all, which is
219
+ // the whole feature. `biome check --unsafe` offers to remove it.
220
+ // biome-ignore lint/correctness/useExhaustiveDependencies: it is what says the style changed
221
+ useEffect(() => {
222
+ if (!hozoTransition) return
223
+ progress.setValue(0)
224
+ const animation = Animated.timing(progress, {
225
+ toValue: 1,
226
+ duration: hozoTransition.duration,
227
+ delay: hozoTransition.delay ?? 0,
228
+ easing: easingFor(hozoTransition.easing),
229
+ // Colours are in here too, and React Native cannot interpolate one
230
+ // on the native driver. One animation on the JavaScript driver is
231
+ // the honest choice: two drivers running the same rule would drift
232
+ // against each other on a busy frame, and a background that arrives
233
+ // before the text that sits on it is worse than both arriving late.
234
+ useNativeDriver: false,
235
+ })
236
+ animation.start(({ finished }) => {
237
+ if (finished && leavingNow.current) doneNow.current?.(id)
238
+ })
239
+ return () => animation.stop()
240
+ }, [progress, signature, hozoTransition, id])
241
+
242
+ // biome-ignore lint/correctness/useExhaustiveDependencies: as above -- `signature` is what changed
243
+ const animated = useMemo(() => {
244
+ if (!hozoTransition) return flat
245
+ const overrides: Record<string, unknown> = {}
246
+
247
+ if (typeof from.current.opacity === 'number' || typeof flat.opacity === 'number') {
248
+ const start = typeof from.current.opacity === 'number' ? from.current.opacity : 1
249
+ const end = typeof flat.opacity === 'number' ? flat.opacity : 1
250
+ if (start !== end) {
251
+ overrides.opacity = progress.interpolate({ inputRange: [0, 1], outputRange: [start, end] })
252
+ }
253
+ }
254
+
255
+ for (const key of COLOR_KEYS) {
256
+ // Read through a record: `color` lives on `TextStyle` and the rest
257
+ // on `ViewStyle`, and a component that may be either has to look at
258
+ // both. The runtime check below is what makes it safe.
259
+ const start = (from.current as Record<string, unknown>)[key]
260
+ const end = (flat as Record<string, unknown>)[key]
261
+ if (typeof start !== 'string' || typeof end !== 'string' || start === end) continue
262
+ overrides[key] = progress.interpolate({ inputRange: [0, 1], outputRange: [start, end] })
263
+ }
264
+
265
+ // Numbers only: a percentage or `auto` has nothing to interpolate
266
+ // between until it is laid out, so it changes at once, as before.
267
+ for (const key of layoutKeys(hozoTransition.properties)) {
268
+ const start = (from.current as Record<string, unknown>)[key]
269
+ const end = (flat as Record<string, unknown>)[key]
270
+ if (typeof start !== 'number' || typeof end !== 'number' || start === end) continue
271
+ overrides[key] = progress.interpolate({ inputRange: [0, 1], outputRange: [start, end] })
272
+ }
273
+
274
+ const before = transformMap(from.current)
275
+ const after = transformMap(flat)
276
+ const keys = [...new Set([...before.keys(), ...after.keys()])]
277
+ const moved = keys.filter(
278
+ (key) => (before.get(key) ?? identity(key)) !== (after.get(key) ?? identity(key)),
279
+ )
280
+ if (moved.length > 0) {
281
+ // Every key, not only the moved ones: `transform` is replaced
282
+ // wholesale, so leaving one out would reset it to identity halfway
283
+ // through the animation of its neighbour.
284
+ overrides.transform = keys.map((key) => ({
285
+ [key]: progress.interpolate({
286
+ inputRange: [0, 1],
287
+ outputRange: [before.get(key) ?? identity(key), after.get(key) ?? identity(key)],
288
+ }),
289
+ }))
290
+ }
291
+
292
+ return [flat, overrides]
293
+ }, [flat, hozoTransition, progress, signature])
294
+
295
+ return (
296
+ <Animated.View style={animated as StyleProp<ViewStyle>} {...props}>
297
+ {exits ? (
298
+ // The state is this element's, as `data-state` on Web belongs to
299
+ // the one element `Presence` puts it on. Something nested further
300
+ // in does not leave with it.
301
+ <PresenceContext.Provider value={null}>{children}</PresenceContext.Provider>
302
+ ) : (
303
+ children
304
+ )}
305
+ </Animated.View>
306
+ )
307
+ }
308
+
309
+ function easingFor(name: HozoTransitionSpec['easing']) {
310
+ // Built here rather than in a module-level table, for the reason
311
+ // `hooks.native.ts` does the same: a table calls `Easing.bezier` on
312
+ // import, for every project that loads the package and never
313
+ // transitions. The import itself is free; the call is not.
314
+ switch (name) {
315
+ case 'linear':
316
+ return Easing.linear
317
+ case 'ease-in':
318
+ return Easing.bezier(0.4, 0, 1, 1)
319
+ case 'ease-out':
320
+ return Easing.bezier(0, 0, 0.2, 1)
321
+ default:
322
+ return Easing.bezier(0.4, 0, 0.2, 1)
323
+ }
324
+ }
@@ -21,6 +21,8 @@
21
21
  // obscure one: `@react-navigation` pulls it in, so most applications with
22
22
  // more than one screen already have it.
23
23
 
24
+ import { type Context, createContext, useContext } from 'react'
25
+
24
26
  /** The four insets, in the shape the compiled style reads them. */
25
27
  export interface HozoSafeAreaInsets {
26
28
  top: number
@@ -31,47 +33,62 @@ export interface HozoSafeAreaInsets {
31
33
 
32
34
  type InsetsHook = () => HozoSafeAreaInsets
33
35
 
36
+ interface SafeAreaPackage {
37
+ useSafeAreaInsets?: InsetsHook
38
+ SafeAreaInsetsContext?: Context<HozoSafeAreaInsets | null>
39
+ }
40
+
34
41
  const NONE: HozoSafeAreaInsets = { top: 0, right: 0, bottom: 0, left: 0 }
35
42
 
36
43
  /**
37
- * The package's hook, or a hook-shaped constant when it is not installed.
44
+ * The package, or `null` when it is not installed.
38
45
  *
39
46
  * Resolved at module load, which is both the simple answer and the correct
40
- * one. Simple, because a hook chosen once is a hook called unconditionally
41
- * afterwards -- selecting per render would be calling a hook inside a
42
- * branch, which is the rule React does not bend even when the branch is
43
- * decided by the bundle and never changes.
47
+ * one: a hook chosen once is a hook called unconditionally afterwards --
48
+ * selecting per render would be calling a hook inside a branch, which is the
49
+ * rule React does not bend even when the branch is decided by the bundle and
50
+ * never changes.
44
51
  *
45
- * Correct, because this module is only loaded when the compiler emitted a
46
- * safe-area class. A project that writes none never imports it, never
47
- * resolves anything, and never sees the warning; a project that writes one
48
- * sees it exactly once, at startup, when there is still time to act.
52
+ * Silent here, because loading this module says nothing about whether an
53
+ * app asked for an inset: `@hozo/engine`'s Native entry re-exports it, so
54
+ * anything that imports the entry loads it. The warning waits for a
55
+ * safe-area class to render.
49
56
  */
50
- function resolveInsetsHook(): InsetsHook {
57
+ function resolvePackage(): SafeAreaPackage | null {
51
58
  try {
52
59
  // eslint-disable-next-line @typescript-eslint/no-require-imports
53
- const module = require('react-native-safe-area-context') as {
54
- useSafeAreaInsets?: InsetsHook
55
- }
56
- if (typeof module.useSafeAreaInsets === 'function') return module.useSafeAreaInsets
60
+ return require('react-native-safe-area-context') as SafeAreaPackage
57
61
  } catch {
58
- // Not installed. Fall through to the warning: an optional dependency
59
- // that throws on absence is not optional.
62
+ return null
63
+ }
64
+ }
65
+
66
+ const safeAreaPackage = resolvePackage()
67
+
68
+ let warned = false
69
+
70
+ /** Zeros, after saying once why, for a safe-area class with no package. */
71
+ function useMissingInsets(): HozoSafeAreaInsets {
72
+ if (!warned) {
73
+ warned = true
74
+ console.warn(
75
+ '[hozo] a safe-area class needs `react-native-safe-area-context`, which is not installed. ' +
76
+ 'Insets are zero until it is: add it, then wrap the app in its `<SafeAreaProvider>`. ' +
77
+ 'Hozo ships no native code of its own, and the real inset is `UIView.safeAreaInsets` on ' +
78
+ 'iOS and `WindowInsets` on Android -- neither of which React Native exposes to JavaScript.',
79
+ )
60
80
  }
61
- console.warn(
62
- '[hozo] a safe-area class needs `react-native-safe-area-context`, which is not installed. ' +
63
- 'Insets are zero until it is: add it, then wrap the app in its `<SafeAreaProvider>`. ' +
64
- 'Hozo ships no native code of its own, and the real inset is `UIView.safeAreaInsets` on ' +
65
- 'iOS and `WindowInsets` on Android -- neither of which React Native exposes to JavaScript.',
66
- )
67
81
  // Zeros rather than a throw, because of what each costs: a missing inset
68
82
  // draws content under a notch, which is ugly and recoverable, and a
69
83
  // thrown error is a blank app. The warning is what makes the ugly one
70
84
  // findable.
71
- return () => NONE
85
+ return NONE
72
86
  }
73
87
 
74
- const useInsets = resolveInsetsHook()
88
+ const useInsets: InsetsHook =
89
+ typeof safeAreaPackage?.useSafeAreaInsets === 'function'
90
+ ? safeAreaPackage.useSafeAreaInsets
91
+ : useMissingInsets
75
92
 
76
93
  /**
77
94
  * The current safe-area insets. Drives `pt-[env(safe-area-inset-top)]` and
@@ -85,3 +102,21 @@ const useInsets = resolveInsetsHook()
85
102
  export function useHozoSafeArea(): HozoSafeAreaInsets {
86
103
  return useInsets()
87
104
  }
105
+
106
+ const providedInsets: Context<HozoSafeAreaInsets | null> =
107
+ safeAreaPackage?.SafeAreaInsetsContext ?? createContext<HozoSafeAreaInsets | null>(null)
108
+
109
+ /**
110
+ * The insets an app's `<SafeAreaProvider>` reports, or zeros when there is
111
+ * none, without a warning.
112
+ *
113
+ * For a component that insets itself rather than a class an app wrote: a
114
+ * Native `Menu` pinned to the bottom edge has to clear the home indicator in
115
+ * every app that renders it, and must not take the app down in one that never
116
+ * installed the package or never mounted its provider. The package's own hook
117
+ * throws without the provider, so this reads its context instead, where a
118
+ * missing provider is `null`.
119
+ */
120
+ export function useHozoProvidedSafeArea(): HozoSafeAreaInsets {
121
+ return useContext(providedInsets) ?? NONE
122
+ }
@@ -0,0 +1,74 @@
1
+ // A caller's spread composed after the styles compiled from a class, rather
2
+ // than replacing them (#1054).
3
+ //
4
+ // Compiled output calls this only for an element that has both a style
5
+ // compiled from its classes and a spread that might carry the same prop:
6
+ //
7
+ // <Listbox {...hozoSpreadStyles({ style: hozoStyles.hozo0 }, [], rest)} />
8
+ //
9
+ // Every owner Hozo ships composes class styles first and the caller's style
10
+ // after; a spread re-emitted after the compiled attribute used to throw the
11
+ // compiled one away instead. Sources are copied in order, each once, the way
12
+ // JSX spreads them, so a getter on `rest` runs once and `rest.style` is never
13
+ // read a second time.
14
+
15
+ type StyleValue = unknown
16
+ type StyleFunction = (state: unknown) => StyleValue
17
+
18
+ function resolve(value: StyleValue, state: unknown): StyleValue {
19
+ return typeof value === 'function' ? (value as StyleFunction)(state) : value
20
+ }
21
+
22
+ /** Class styles first, the caller's after; a pressable's style function stays one. */
23
+ function compose(
24
+ compiled: StyleValue,
25
+ own: StyleValue,
26
+ normalize?: (value: StyleValue) => StyleValue,
27
+ ): StyleValue {
28
+ if (typeof compiled === 'function' || typeof own === 'function') {
29
+ return (state: unknown) => {
30
+ const generated = resolve(compiled, state)
31
+ const author = resolve(own, state)
32
+ return [generated, normalize ? normalize(author) : author]
33
+ }
34
+ }
35
+ return [compiled, normalize ? normalize(own) : own]
36
+ }
37
+
38
+ /**
39
+ * @param styles What was compiled for each style prop.
40
+ * @param writtenLast Props whose compiled value already ends with a style the
41
+ * author wrote after every spread. In source that style replaced whatever a
42
+ * spread carried, so a spread's copy is dropped rather than composed.
43
+ * @param sources The spreads, and any props written between them as
44
+ * one-entry objects, in source order.
45
+ */
46
+ export function hozoSpreadStyles(
47
+ styles: Readonly<Record<string, StyleValue>>,
48
+ writtenLast: readonly string[],
49
+ ...sources: readonly unknown[]
50
+ ): Record<string, unknown> {
51
+ return composeSpreadStyles(styles, writtenLast, sources)
52
+ }
53
+
54
+ /** Internal core shared by the ordinary and gap-aware generated boundaries. */
55
+ export function composeSpreadStyles(
56
+ styles: Readonly<Record<string, StyleValue>>,
57
+ writtenLast: readonly string[],
58
+ sources: readonly unknown[],
59
+ normalize?: (value: StyleValue) => StyleValue,
60
+ ): Record<string, unknown> {
61
+ let props: Record<string, unknown> = {}
62
+ for (const source of sources) {
63
+ // Object spread, not `Object.assign`: it defines rather than sets, so an
64
+ // own `__proto__` key stays a key, exactly as `{...source}` in JSX.
65
+ if (source != null) props = { ...props, ...(source as object) }
66
+ }
67
+ for (const [name, compiled] of Object.entries(styles)) {
68
+ props[name] =
69
+ !writtenLast.includes(name) && Object.hasOwn(props, name)
70
+ ? compose(compiled, props[name], normalize)
71
+ : compiled
72
+ }
73
+ return props
74
+ }