@hozo/primitives 0.2.0 → 0.3.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.
@@ -1,3 +1,4 @@
1
+ import { usePressableInteraction } from '@hozo/behaviors/pressable-interaction'
1
2
  import { blendColor } from '@hozo/engine'
2
3
  import {
3
4
  createContext,
@@ -9,7 +10,6 @@ import {
9
10
  useLayoutEffect,
10
11
  useMemo,
11
12
  useRef,
12
- useState,
13
13
  } from 'react'
14
14
  import {
15
15
  Animated,
@@ -51,10 +51,6 @@ export interface HozoPressableProps extends Omit<PressableProps, 'style'> {
51
51
  hozoFocusVisible?: boolean
52
52
  }
53
53
 
54
- const HOVERED = 1
55
- const FOCUSED = 2
56
- const PRESSED = 4
57
- const FOCUS_VISIBLE = 8
58
54
  const AnimatedPressable = Animated.createAnimatedComponent(Pressable)
59
55
 
60
56
  /**
@@ -92,6 +88,8 @@ export function pressableFor(transition: HozoTransition | undefined): ElementTyp
92
88
  const AnimatedText = Animated.createAnimatedComponent(Text)
93
89
  type InteractionContextValue = HozoPressableState & { transition?: HozoTransition }
94
90
  const InteractionContext = createContext<InteractionContextValue | null>(null)
91
+ type AnimationDriver = { current: ((state: HozoPressableState) => void) | null }
92
+ const AnimationDriverContext = createContext<AnimationDriver | null>(null)
95
93
 
96
94
  function easingFor(name: HozoTransition['easing']) {
97
95
  switch (name) {
@@ -106,10 +104,36 @@ function easingFor(name: HozoTransition['easing']) {
106
104
  }
107
105
  }
108
106
 
107
+ function transitionTiming(
108
+ value: Animated.Value,
109
+ toValue: number,
110
+ transition: HozoTransition,
111
+ useNativeDriver: boolean,
112
+ ) {
113
+ return Animated.timing(value, {
114
+ toValue,
115
+ duration: transition.duration,
116
+ delay: transition.delay ?? 0,
117
+ easing: easingFor(transition.easing),
118
+ useNativeDriver,
119
+ })
120
+ }
121
+
109
122
  type TransformTarget = { key: string; value: number; degrees: boolean }
110
123
  const transformRank = (key: string) =>
111
124
  key.startsWith('translate') ? 0 : key.startsWith('rotate') ? 1 : 2
112
125
 
126
+ // Both motion probes need the full Cartesian product, in the same order.
127
+ // Called only by the transition child, never by a plain Pressable.
128
+ function interactionStates(): HozoPressableState[] {
129
+ return Array.from({ length: 16 }, (_, bits) => ({
130
+ pressed: !!(bits & 8),
131
+ hovered: !!(bits & 4),
132
+ focused: !!(bits & 2),
133
+ focusVisible: !!(bits & 1),
134
+ }))
135
+ }
136
+
113
137
  function transformTargets(style: StyleProp<ViewStyle>): TransformTarget[] {
114
138
  const merged = new Map<string, TransformTarget>()
115
139
  const visit = (part: StyleProp<ViewStyle>) => {
@@ -171,33 +195,122 @@ export function HozoPressable({
171
195
  hozoFocusVisible = false,
172
196
  ...props
173
197
  }: HozoPressableProps) {
174
- const [interaction, setInteraction] = useState(0)
175
- const interactionRef = useRef(0)
176
- const initialStyle =
177
- typeof style === 'function'
178
- ? style({ pressed: false, hovered: false, focused: false, focusVisible: false })
179
- : style
198
+ // Keep the event/context owner mounted when motion is added or removed.
199
+ // Only the optional animation child owns nodes and progress listeners.
200
+ const driver = useRef<((state: HozoPressableState) => void) | null>(null)
201
+ const animate = useCallback((state: HozoPressableState) => driver.current?.(state), [])
202
+ const { state: interaction, handlers } = usePressableInteraction({
203
+ focusVisible: hozoFocusVisible,
204
+ onChange: hozoTransition ? animate : undefined,
205
+ })
206
+ const context = useMemo(
207
+ () => ({ ...interaction, transition: hozoTransition }),
208
+ [hozoTransition, interaction],
209
+ )
210
+ // Resolve the owner's snapshot once, not once again inside RN's host.
211
+ // RN's pressed flag can disagree with the owner snapshot. Active wins,
212
+ // as before; only that case needs a separate style evaluation.
213
+ const restingLook = useMemo(
214
+ () =>
215
+ hozoTransition ? undefined : typeof style === 'function' ? style({ ...interaction }) : style,
216
+ [hozoTransition, interaction, style],
217
+ )
218
+ // Assemble native props once, with no trailing conditional spread on the
219
+ // hot no-motion path. Private animation data never goes through RN props.
220
+ const Component: ElementType = hozoTransition ? TransitionPressable : Pressable
221
+ const host = (
222
+ <Component
223
+ {...props}
224
+ onHoverIn={(event: MouseEvent) => {
225
+ handlers.hoverIn()
226
+ onHoverIn?.(event)
227
+ }}
228
+ onHoverOut={(event: MouseEvent) => {
229
+ handlers.hoverOut()
230
+ onHoverOut?.(event)
231
+ }}
232
+ onFocus={(event: NativeSyntheticEvent<TargetedEvent>) => {
233
+ handlers.focus()
234
+ onFocus?.(event)
235
+ }}
236
+ onBlur={(event: NativeSyntheticEvent<TargetedEvent>) => {
237
+ handlers.blur()
238
+ onBlur?.(event)
239
+ }}
240
+ onPointerDown={
241
+ hozoFocusVisible
242
+ ? (event: Parameters<NonNullable<PressableProps['onPointerDown']>>[0]) => {
243
+ handlers.pointerDown()
244
+ onPointerDown?.(event)
245
+ }
246
+ : onPointerDown
247
+ }
248
+ onKeyDown={
249
+ hozoFocusVisible
250
+ ? (event: Parameters<NonNullable<PressableProps['onKeyDown']>>[0]) => {
251
+ handlers.keyDown()
252
+ onKeyDown?.(event)
253
+ }
254
+ : onKeyDown
255
+ }
256
+ onPressIn={(event: GestureResponderEvent) => {
257
+ handlers.pressIn()
258
+ onPressIn?.(event)
259
+ }}
260
+ onPressOut={(event: GestureResponderEvent) => {
261
+ handlers.pressOut()
262
+ onPressOut?.(event)
263
+ }}
264
+ style={
265
+ hozoTransition
266
+ ? style
267
+ : ({ pressed }: PressableStateCallbackType) =>
268
+ pressed && !interaction.pressed && typeof style === 'function'
269
+ ? style({ ...interaction, pressed: pressed || interaction.pressed })
270
+ : restingLook
271
+ }
272
+ />
273
+ )
274
+ return (
275
+ <InteractionContext.Provider value={context}>
276
+ {hozoTransition ? (
277
+ <AnimationDriverContext.Provider value={driver}>{host}</AnimationDriverContext.Provider>
278
+ ) : (
279
+ host
280
+ )}
281
+ </InteractionContext.Provider>
282
+ )
283
+ }
284
+
285
+ function TransitionPressable({
286
+ style,
287
+ ...props
288
+ }: Omit<HozoPressableProps, 'hozoFocusVisible' | 'hozoTransition'>) {
289
+ // This private owner is mounted only inside both providers, for motion.
290
+ const context = useContext(InteractionContext)!
291
+ const hozoTransition = context.transition!
292
+ const interaction = useMemo(
293
+ () => ({
294
+ pressed: context.pressed,
295
+ hovered: context.hovered,
296
+ focused: context.focused,
297
+ focusVisible: context.focusVisible,
298
+ }),
299
+ [context.pressed, context.hovered, context.focused, context.focusVisible],
300
+ )
301
+ const driver = useContext(AnimationDriverContext)!
302
+ const initialStyle = typeof style === 'function' ? style({ ...interaction }) : style
180
303
  const initialOpacity = StyleSheet.flatten(initialStyle)?.opacity
181
304
  const opacity = useRef(
182
305
  new Animated.Value(typeof initialOpacity === 'number' ? initialOpacity : 1),
183
306
  ).current
184
307
  const colorSpecs = useMemo(() => {
185
- if (!hozoTransition?.colors || typeof style !== 'function') return [] as ColorKey[]
308
+ if (!hozoTransition.colors || typeof style !== 'function') return [] as ColorKey[]
186
309
  const found = new Set<ColorKey>()
187
- for (const pressed of [false, true]) {
188
- for (const hovered of [false, true]) {
189
- for (const focused of [false, true]) {
190
- for (const focusVisible of [false, true]) {
191
- for (const key of colorTargets(
192
- style({ pressed, hovered, focused, focusVisible }),
193
- ).keys())
194
- found.add(key)
195
- }
196
- }
197
- }
198
- }
310
+ for (const state of interactionStates())
311
+ for (const key of colorTargets(style(state)).keys()) found.add(key)
199
312
  return [...found]
200
- }, [hozoTransition?.colors, style])
313
+ }, [hozoTransition.colors, style])
201
314
  const initialColors = colorTargets(initialStyle)
202
315
  const colorRanges = useRef(new Map<ColorKey, ColorRange>()).current
203
316
  for (const key of colorSpecs) {
@@ -208,11 +321,15 @@ export function HozoPressable({
208
321
  }
209
322
  const colorProgress = useRef(new Animated.Value(0)).current
210
323
  const colorFraction = useRef(0)
324
+ const animation = useRef<Animated.CompositeAnimation | null>(null)
211
325
  useEffect(() => {
212
326
  const listener = colorProgress.addListener(({ value }) => {
213
327
  colorFraction.current = value
214
328
  })
215
- return () => colorProgress.removeListener(listener)
329
+ return () => {
330
+ colorProgress.removeListener(listener)
331
+ animation.current?.stop()
332
+ }
216
333
  }, [colorProgress])
217
334
  const animatedColors = Object.fromEntries(
218
335
  [...colorRanges].map(([key, range]) => [
@@ -224,20 +341,13 @@ export function HozoPressable({
224
341
  ]),
225
342
  )
226
343
  const transformSpecs = useMemo(() => {
227
- if (!hozoTransition?.transform || typeof style !== 'function') return []
228
- const states = [false, true].flatMap((pressed) =>
229
- [false, true].flatMap((hovered) =>
230
- [false, true].flatMap((focused) =>
231
- [false, true].map((focusVisible) => ({ pressed, hovered, focused, focusVisible })),
232
- ),
233
- ),
234
- )
344
+ if (!hozoTransition.transform || typeof style !== 'function') return []
235
345
  const merged = new Map<string, TransformTarget>()
236
- for (const state of states) {
346
+ for (const state of interactionStates()) {
237
347
  for (const target of transformTargets(style(state))) merged.set(target.key, target)
238
348
  }
239
349
  return [...merged.values()].sort((a, b) => transformRank(a.key) - transformRank(b.key))
240
- }, [hozoTransition?.transform, style])
350
+ }, [hozoTransition.transform, style])
241
351
  const transformValues = useRef(new Map<string, Animated.Value>()).current
242
352
  const initialTargets = new Map(
243
353
  transformTargets(initialStyle).map((target) => [target.key, target]),
@@ -259,61 +369,31 @@ export function HozoPressable({
259
369
  : transformValues.get(spec.key)!,
260
370
  }))
261
371
  const animateInteraction = useCallback(
262
- (next: number) => {
263
- if (!hozoTransition || typeof style !== 'function') return
264
- const flattened = StyleSheet.flatten(
265
- style({
266
- pressed: (next & PRESSED) !== 0,
267
- hovered: (next & HOVERED) !== 0,
268
- focused: (next & FOCUSED) !== 0,
269
- focusVisible: (next & FOCUS_VISIBLE) !== 0,
270
- }),
271
- )
372
+ (next: HozoPressableState) => {
373
+ if (typeof style !== 'function') return
374
+ const flattened = StyleSheet.flatten(style({ ...next }))
272
375
  const animations: Animated.CompositeAnimation[] = []
273
376
  if (hozoTransition.opacity) {
274
377
  const targetOpacity = typeof flattened?.opacity === 'number' ? flattened.opacity : 1
275
- animations.push(
276
- Animated.timing(opacity, {
277
- toValue: targetOpacity,
278
- duration: hozoTransition.duration,
279
- delay: hozoTransition.delay ?? 0,
280
- easing: easingFor(hozoTransition.easing),
281
- useNativeDriver: true,
282
- }),
283
- )
378
+ animations.push(transitionTiming(opacity, targetOpacity, hozoTransition, true))
284
379
  }
285
380
  if (hozoTransition.transform) {
286
381
  const targets = new Map(
287
- transformTargets(
288
- style({
289
- pressed: (next & PRESSED) !== 0,
290
- hovered: (next & HOVERED) !== 0,
291
- focused: (next & FOCUSED) !== 0,
292
- focusVisible: (next & FOCUS_VISIBLE) !== 0,
293
- }),
294
- ).map((target) => [target.key, target.value]),
382
+ transformTargets(style({ ...next })).map((target) => [target.key, target.value]),
295
383
  )
296
384
  for (const spec of transformSpecs) {
297
385
  animations.push(
298
- Animated.timing(transformValues.get(spec.key)!, {
299
- toValue: targets.get(spec.key) ?? identityFor(spec),
300
- duration: hozoTransition.duration,
301
- delay: hozoTransition.delay ?? 0,
302
- easing: easingFor(hozoTransition.easing),
303
- useNativeDriver: true,
304
- }),
386
+ transitionTiming(
387
+ transformValues.get(spec.key)!,
388
+ targets.get(spec.key) ?? identityFor(spec),
389
+ hozoTransition,
390
+ true,
391
+ ),
305
392
  )
306
393
  }
307
394
  }
308
395
  if (hozoTransition.colors) {
309
- const targets = colorTargets(
310
- style({
311
- pressed: (next & PRESSED) !== 0,
312
- hovered: (next & HOVERED) !== 0,
313
- focused: (next & FOCUSED) !== 0,
314
- focusVisible: (next & FOCUS_VISIBLE) !== 0,
315
- }),
316
- )
396
+ const targets = colorTargets(style({ ...next }))
317
397
  for (const [key, range] of colorRanges) {
318
398
  const current = blendColor(range.from, range.to, colorFraction.current)
319
399
  const target = targets.get(key) ?? (key === 'backgroundColor' ? 'transparent' : current)
@@ -321,157 +401,70 @@ export function HozoPressable({
321
401
  }
322
402
  colorProgress.setValue(0)
323
403
  colorFraction.current = 0
324
- animations.push(
325
- Animated.timing(colorProgress, {
326
- toValue: 1,
327
- duration: hozoTransition.duration,
328
- delay: hozoTransition.delay ?? 0,
329
- easing: easingFor(hozoTransition.easing),
330
- useNativeDriver: false,
331
- }),
332
- )
404
+ animations.push(transitionTiming(colorProgress, 1, hozoTransition, false))
333
405
  }
334
- Animated.parallel(animations).start()
406
+ animation.current = Animated.parallel(animations)
407
+ animation.current.start()
335
408
  },
336
409
  [colorProgress, colorRanges, hozoTransition, opacity, style, transformSpecs, transformValues],
337
410
  )
338
- const setFlag = useCallback(
339
- (flag: number, active: boolean) => {
340
- const current = interactionRef.current
341
- const next = active ? current | flag : current & ~flag
342
- interactionRef.current = next
343
- animateInteraction(next)
344
- setInteraction(next)
345
- },
346
- [animateInteraction],
347
- )
411
+ // Install only the committed driver. A speculative render must not replace
412
+ // the callback used synchronously by the parent's event machine.
413
+ useLayoutEffect(() => {
414
+ driver.current = animateInteraction
415
+ return () => {
416
+ if (driver.current === animateInteraction) driver.current = null
417
+ }
418
+ }, [animateInteraction, driver])
348
419
  const PressableComponent = pressableFor(hozoTransition)
349
- const modality = useRef<'keyboard' | 'pointer'>('keyboard')
350
420
 
351
421
  // The style for the state this component is in, resolved here because
352
422
  // the animated path cannot hand React Native a callback -- see the
353
423
  // `style` prop below.
354
424
  const resolvedStyle = useMemo(
355
- () =>
356
- typeof style === 'function'
357
- ? style({
358
- pressed: (interaction & PRESSED) !== 0,
359
- hovered: (interaction & HOVERED) !== 0,
360
- focused: (interaction & FOCUSED) !== 0,
361
- focusVisible: (interaction & FOCUS_VISIBLE) !== 0,
362
- })
363
- : style,
425
+ () => (typeof style === 'function' ? style({ ...interaction }) : style),
364
426
  [interaction, style],
365
427
  )
366
428
 
367
- const context = useMemo(
368
- () => ({
369
- pressed: (interaction & PRESSED) !== 0,
370
- hovered: (interaction & HOVERED) !== 0,
371
- focused: (interaction & FOCUSED) !== 0,
372
- focusVisible: (interaction & FOCUS_VISIBLE) !== 0,
373
- transition: hozoTransition,
374
- }),
375
- [hozoTransition, interaction],
376
- )
377
-
378
429
  return (
379
- <InteractionContext.Provider value={context}>
380
- <PressableComponent
381
- {...props}
382
- onHoverIn={(event: MouseEvent) => {
383
- setFlag(HOVERED, true)
384
- onHoverIn?.(event)
385
- }}
386
- onHoverOut={(event: MouseEvent) => {
387
- setFlag(HOVERED, false)
388
- onHoverOut?.(event)
389
- }}
390
- onFocus={(event: NativeSyntheticEvent<TargetedEvent>) => {
391
- setFlag(FOCUSED, true)
392
- if (hozoFocusVisible) setFlag(FOCUS_VISIBLE, modality.current === 'keyboard')
393
- onFocus?.(event)
394
- }}
395
- onBlur={(event: NativeSyntheticEvent<TargetedEvent>) => {
396
- setFlag(FOCUSED, false)
397
- if (hozoFocusVisible) setFlag(FOCUS_VISIBLE, false)
398
- onBlur?.(event)
399
- }}
400
- onPointerDown={
401
- hozoFocusVisible
402
- ? (event: Parameters<NonNullable<PressableProps['onPointerDown']>>[0]) => {
403
- modality.current = 'pointer'
404
- setFlag(FOCUS_VISIBLE, false)
405
- onPointerDown?.(event)
406
- }
407
- : onPointerDown
408
- }
409
- onKeyDown={
410
- hozoFocusVisible
411
- ? (event: Parameters<NonNullable<PressableProps['onKeyDown']>>[0]) => {
412
- modality.current = 'keyboard'
413
- if ((interactionRef.current & FOCUSED) !== 0) setFlag(FOCUS_VISIBLE, true)
414
- onKeyDown?.(event)
415
- }
416
- : onKeyDown
417
- }
418
- onPressIn={(event: GestureResponderEvent) => {
419
- modality.current = 'pointer'
420
- if (hozoFocusVisible) setFlag(FOCUS_VISIBLE, false)
421
- setFlag(PRESSED, true)
422
- onPressIn?.(event)
423
- }}
424
- onPressOut={(event: GestureResponderEvent) => {
425
- setFlag(PRESSED, false)
426
- onPressOut?.(event)
427
- }}
428
- // An array when there is a transition, a callback when there is
429
- // not, and the difference is not a preference.
430
- //
431
- // `AnimatedProps` builds the animated node from `props.style`, and
432
- // its first act is to skip anything that is not an object:
433
- //
434
- // if (key === 'style') {
435
- // // Ignore `style` if it is not an object (or array).
436
- // if (typeof value === 'object' && value != null) {
437
- //
438
- // A callback is a function, so no node was ever attached. Pressable
439
- // still called it, so the `Animated.Value`s it returned reached the
440
- // view as plain objects where colours and numbers belong -- and a
441
- // `backgroundColor` that is an object is not a colour, so the view
442
- // dropped it. The compiled `bg-brand` button rendered with no
443
- // background at all, and its white label with it, for as long as
444
- // this code has existed. Found by the first screenshot anything
445
- // ever took of the acceptance screen (#297).
446
- //
447
- // The state the callback would have supplied is state this
448
- // component already keeps: `pressed` is set from `onPressIn` and
449
- // `onPressOut`, which is what drives Pressable's own flag too.
450
- style={
451
- hozoTransition
452
- ? // Cast because `Animated.createAnimatedComponent` types
453
- // `style` as a resolved ViewStyle, while the whole point of
454
- // an animated component is that it may hold `Animated.Value`s.
455
- ([
456
- resolvedStyle,
457
- {
458
- ...(hozoTransition.opacity ? { opacity } : null),
459
- ...(hozoTransition.transform ? { transform: animatedTransform } : null),
460
- ...(hozoTransition.colors ? animatedColors : null),
461
- },
462
- ] as unknown as StyleProp<ViewStyle>)
463
- : ({ pressed }: PressableStateCallbackType) =>
464
- typeof style === 'function'
465
- ? style({
466
- pressed: pressed || (interaction & PRESSED) !== 0,
467
- hovered: (interaction & HOVERED) !== 0,
468
- focused: (interaction & FOCUSED) !== 0,
469
- focusVisible: (interaction & FOCUS_VISIBLE) !== 0,
470
- })
471
- : style
472
- }
473
- />
474
- </InteractionContext.Provider>
430
+ <PressableComponent
431
+ {...props}
432
+ // An array when there is a transition, a callback when there is
433
+ // not, and the difference is not a preference.
434
+ //
435
+ // `AnimatedProps` builds the animated node from `props.style`, and
436
+ // its first act is to skip anything that is not an object:
437
+ //
438
+ // if (key === 'style') {
439
+ // // Ignore `style` if it is not an object (or array).
440
+ // if (typeof value === 'object' && value != null) {
441
+ //
442
+ // A callback is a function, so no node was ever attached. Pressable
443
+ // still called it, so the `Animated.Value`s it returned reached the
444
+ // view as plain objects where colours and numbers belong -- and a
445
+ // `backgroundColor` that is an object is not a colour, so the view
446
+ // dropped it. The compiled `bg-brand` button rendered with no
447
+ // background at all, and its white label with it, for as long as
448
+ // this code has existed. Found by the first screenshot anything
449
+ // ever took of the acceptance screen (#297).
450
+ //
451
+ // The state the callback would have supplied is state the enclosing
452
+ // event owner already keeps: `pressed` is set from `onPressIn` and
453
+ // `onPressOut`, which is what drives Pressable's own flag too.
454
+ style={
455
+ // Cast because `Animated.createAnimatedComponent` types
456
+ // `style` as a resolved ViewStyle, while the whole point of
457
+ // an animated component is that it may hold `Animated.Value`s.
458
+ [
459
+ resolvedStyle,
460
+ {
461
+ ...(hozoTransition.opacity ? { opacity } : null),
462
+ ...(hozoTransition.transform ? { transform: animatedTransform } : null),
463
+ ...(hozoTransition.colors ? animatedColors : null),
464
+ },
465
+ ] as unknown as StyleProp<ViewStyle>
466
+ }
467
+ />
475
468
  )
476
469
  }
477
470
 
@@ -482,56 +475,71 @@ export interface HozoTextProps extends Omit<TextProps, 'style'> {
482
475
 
483
476
  /** Text whose interaction state and transition are owned by an enclosing HozoPressable. */
484
477
  export function HozoText({ style, ...props }: HozoTextProps) {
478
+ // Public Text is valid outside an owner. Dependency arrays run before
479
+ // early returns, so the former shared component's context.transition
480
+ // dependency threw there. Keep the nullable gate here; the motion child
481
+ // mounts only with a real owner and an enabled colour transition.
485
482
  const context = useContext(InteractionContext)
486
483
  const state = context ?? { pressed: false, hovered: false, focused: false, focusVisible: false }
487
484
  const resolved = typeof style === 'function' ? style(state) : style
485
+ if (!context?.transition?.colors || typeof style !== 'function') {
486
+ return <Text {...props} style={resolved} />
487
+ }
488
+ return <TransitionText {...props} context={context} resolved={resolved} />
489
+ }
490
+
491
+ function TransitionText({
492
+ context,
493
+ resolved,
494
+ ...props
495
+ }: Omit<HozoTextProps, 'style'> & {
496
+ context: InteractionContextValue
497
+ resolved: StyleProp<TextStyle>
498
+ }) {
499
+ const transition = context.transition!
500
+ const state = context
488
501
  const target = StyleSheet.flatten(resolved)?.color
489
502
  const progress = useRef(new Animated.Value(1)).current
503
+ const animation = useRef<Animated.CompositeAnimation | null>(null)
490
504
  const fraction = useRef(1)
491
- const previousTarget = useRef(typeof target === 'string' ? target : '')
492
- const range = useRef<ColorRange>({ from: previousTarget.current, to: previousTarget.current })
493
- const interaction = `${state.pressed}:${state.hovered}:${state.focused}`
505
+ const initialColor = typeof target === 'string' ? target : ''
506
+ const range = useRef<ColorRange>({ from: initialColor, to: initialColor })
507
+ const interaction = `${state.pressed}:${state.hovered}:${state.focused}:${state.focusVisible}`
494
508
  const previousInteraction = useRef(interaction)
495
- const pending = previousInteraction.current !== interaction && typeof target === 'string'
509
+ // Carry the state key, not just true/false. Consecutive interaction
510
+ // changes can both be pending: a boolean effect dependency would skip
511
+ // the second transition, even though its colour target changed.
512
+ const pending =
513
+ previousInteraction.current !== interaction && typeof target === 'string' ? interaction : null
496
514
  if (pending) {
497
515
  range.current = {
498
516
  from: blendColor(range.current.from, range.current.to, fraction.current),
499
517
  to: target as string,
500
518
  }
501
519
  previousInteraction.current = interaction
502
- previousTarget.current = target as string
503
520
  }
504
521
  useEffect(() => {
505
522
  const listener = progress.addListener(({ value }) => {
506
523
  fraction.current = value
507
524
  })
508
- return () => progress.removeListener(listener)
525
+ return () => {
526
+ progress.removeListener(listener)
527
+ animation.current?.stop()
528
+ }
509
529
  }, [progress])
510
530
  useLayoutEffect(() => {
511
- if (!pending || !context?.transition?.colors) return
531
+ if (!pending) return
512
532
  progress.setValue(0)
513
533
  fraction.current = 0
514
- Animated.timing(progress, {
515
- toValue: 1,
516
- duration: context.transition.duration,
517
- delay: context.transition.delay ?? 0,
518
- easing: easingFor(context.transition.easing),
519
- useNativeDriver: false,
520
- }).start()
521
- // `context?`, not `context`: the context defaults to null, and this
522
- // component is explicitly written to work without one -- see the
523
- // `if (!context ...)` below. A dependency array is evaluated on every
524
- // render, before any of them, so `context.transition` threw for a
525
- // HozoText used outside a HozoPressable.
526
- }, [context?.transition, pending, progress])
527
- const animatedColor =
528
- context?.transition?.colors && range.current.from
529
- ? progress.interpolate({
530
- inputRange: [0, 1],
531
- outputRange: [range.current.from, range.current.to],
532
- })
533
- : undefined
534
- if (!context || typeof style !== 'function') return <Text {...props} style={resolved} />
534
+ animation.current = transitionTiming(progress, 1, transition, false)
535
+ animation.current.start()
536
+ }, [transition, pending, progress])
537
+ const animatedColor = range.current.from
538
+ ? progress.interpolate({
539
+ inputRange: [0, 1],
540
+ outputRange: [range.current.from, range.current.to],
541
+ })
542
+ : undefined
535
543
  return (
536
544
  <AnimatedText {...props} style={[resolved, animatedColor ? { color: animatedColor } : null]} />
537
545
  )