blob: a5104a1a3ef7a551e981029c82a05cf67020adb6 (
plain)
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
44
45
|
import { attachSpring, motionValue } from "motion"
import type { SpringOptions } from "motion"
import { createEffect, createSignal, onCleanup } from "solid-js"
type Opt = Partial<Pick<SpringOptions, "visualDuration" | "bounce" | "stiffness" | "damping" | "mass" | "velocity">>
const eq = (a: Opt | undefined, b: Opt | undefined) =>
a?.visualDuration === b?.visualDuration &&
a?.bounce === b?.bounce &&
a?.stiffness === b?.stiffness &&
a?.damping === b?.damping &&
a?.mass === b?.mass &&
a?.velocity === b?.velocity
export function useSpring(target: () => number, options?: Opt | (() => Opt)) {
const read = () => (typeof options === "function" ? options() : options)
const [value, setValue] = createSignal(target())
const source = motionValue(value())
const spring = motionValue(value())
let config = read()
let stop = attachSpring(spring, source, config)
let off = spring.on("change", (next: number) => setValue(next))
createEffect(() => {
source.set(target())
})
createEffect(() => {
if (!options) return
const next = read()
if (eq(config, next)) return
config = next
stop()
stop = attachSpring(spring, source, next)
setValue(spring.get())
})
onCleanup(() => {
off()
stop()
spring.destroy()
source.destroy()
})
return value
}
|