File size: 1,193 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { isAnimatedString } from '@react-spring/shared'
import { AnimatedObject } from './AnimatedObject'
import { AnimatedString } from './AnimatedString'
import { AnimatedValue } from './AnimatedValue'

type Value = number | string
type Source = AnimatedValue<Value>[]

/** An array of animated nodes */
export class AnimatedArray<
  T extends ReadonlyArray<Value> = Value[],
> extends AnimatedObject {
  declare protected source: Source
  constructor(source: T) {
    super(source)
  }

  /** @internal */
  static create<T extends ReadonlyArray<Value>>(source: T) {
    return new AnimatedArray(source)
  }

  getValue(): T {
    return this.source.map(node => node.getValue()) as any
  }

  setValue(source: T) {
    const payload = this.getPayload()
    // Reuse the payload when lengths are equal.
    if (source.length == payload.length) {
      return payload.map((node, i) => node.setValue(source[i])).some(Boolean)
    }
    // Remake the payload when length changes.
    super.setValue(source.map(makeAnimated))
    return true
  }
}

function makeAnimated(value: any) {
  const nodeType = isAnimatedString(value) ? AnimatedString : AnimatedValue
  return nodeType.create(value)
}