Skip to content

Commit 7b0ac88

Browse files
Create adapter MotionValues lazily
Allow Three.js targets to animate directly and let vgpu uniforms animate from explicit keyframes without requiring prior effect registration. Co-authored-by: Cursor <[email protected]>
1 parent 15aead8 commit 7b0ac88

5 files changed

Lines changed: 183 additions & 16 deletions

File tree

‎packages/motion/src/__tests__/three.test.ts‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,15 @@ describe("motion/three", () => {
8080
expect(uniforms.opacity.value).toBe(1)
8181
})
8282

83+
it("animates uniforms without registration", async () => {
84+
const uniforms = { opacity: { value: 0 } }
85+
86+
await animate(uniforms, { opacity: 1 }, { duration: 0.001 })
87+
await nextFrame()
88+
89+
expect(uniforms.opacity.value).toBe(1)
90+
})
91+
8392
it("updates Three.js color uniforms without replacing them", async () => {
8493
const color = { set: jest.fn() }
8594
const uniforms = { tint: { value: color } }
@@ -121,7 +130,36 @@ describe("motion/three", () => {
121130
expect(mesh.material.opacity).toBe(0.5)
122131
})
123132

124-
it("throws when the target has no registered effect", () => {
125-
expect(() => animate({}, { opacity: 1 })).toThrow()
133+
it("animates Three.js objects without registration", async () => {
134+
const mesh = {
135+
position: { x: 0, y: 0, z: 0 },
136+
rotation: { x: 0, y: 0, z: 0 },
137+
scale: { x: 1, y: 1, z: 1 },
138+
material: { opacity: 1 },
139+
}
140+
141+
await animate(
142+
mesh,
143+
{ x: 2, rotateY: 180, opacity: 0.5 },
144+
{ duration: 0.001 }
145+
)
146+
await nextFrame()
147+
148+
expect(mesh.position.x).toBe(2)
149+
expect(mesh.rotation.y).toBeCloseTo(Math.PI)
150+
expect(mesh.material.opacity).toBe(0.5)
151+
})
152+
153+
it("reads and mutates Three.js colors", async () => {
154+
const color = {
155+
getStyle: () => "#000",
156+
set: jest.fn(),
157+
}
158+
const material = { color }
159+
160+
await animate(material, { color: "#fff" }, { duration: 0.001 })
161+
await nextFrame()
162+
163+
expect(color.set).toHaveBeenLastCalledWith("#fff")
126164
})
127165
})

‎packages/motion/src/__tests__/vgpu.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,15 @@ describe("motion/vgpu", () => {
8282
expect(uniforms.set).toHaveBeenLastCalledWith({ progress: 1 })
8383
})
8484

85+
it("animates unregistered uniforms from explicit keyframes", async () => {
86+
const uniforms = { set: jest.fn() }
87+
88+
await animate(uniforms, { progress: [0, 1] }, { duration: 0.001 })
89+
await nextFrame()
90+
91+
expect(uniforms.set).toHaveBeenLastCalledWith({ progress: 1 })
92+
})
93+
8594
it("throws when animating an unregistered uniform", () => {
8695
expect(() => animate({ set: jest.fn() }, { progress: 1 })).toThrow()
8796
})

‎packages/motion/src/three.ts‎

Lines changed: 93 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ const uniformAdapter = createEffectAdapter<Uniforms>((uniforms, values) => {
4040
const objectAdapter = createEffectAdapter<ThreeObject>(setObjectValues)
4141
const animateEffect = createEffectAnimate(
4242
[uniformAdapter, objectAdapter],
43-
"Three.js uniform or object"
43+
"Three.js uniform or object",
44+
resolveThreeEffect
4445
)
4546

4647
/**
@@ -67,7 +68,7 @@ export function objectEffect(
6768
}
6869

6970
/**
70-
* Animates MotionValues registered with a Three.js uniform or object effect.
71+
* Animates Three.js uniforms and flattened object properties.
7172
*/
7273
export function animate<T extends object>(
7374
subject: ThreeUniforms<T>,
@@ -99,6 +100,96 @@ const transformMap = {
99100
scaleZ: ["scale", "z"],
100101
} as const
101102

103+
function resolveThreeEffect(
104+
subject: object,
105+
key: string,
106+
_target: unknown,
107+
adapter: typeof uniformAdapter | typeof objectAdapter | undefined
108+
) {
109+
const object = subject as ThreeObject
110+
const resolvedAdapter =
111+
adapter ??
112+
(isUniform(object[key]) ? uniformAdapter : objectAdapter)
113+
const initial =
114+
resolvedAdapter === uniformAdapter
115+
? getAnimatableValue((object as Uniforms)[key]?.value)
116+
: getObjectValue(object, key)
117+
118+
return initial === undefined
119+
? undefined
120+
: { adapter: resolvedAdapter, initial }
121+
}
122+
123+
function getObjectValue(object: ThreeObject, key: string) {
124+
const transform = transformMap[key as keyof typeof transformMap]
125+
126+
if (transform) {
127+
const [name, axis] = transform
128+
const value = object[name]?.[axis]
129+
return key.startsWith("rotate") && typeof value === "number"
130+
? value * (180 / Math.PI)
131+
: getAnimatableValue(value)
132+
}
133+
134+
if (key === "scale") {
135+
return getAnimatableValue(object.scale?.x)
136+
}
137+
138+
const value =
139+
getProperty(object, key) ??
140+
getProperty(object.material, key) ??
141+
getUniformValue(object.material?.uniforms ?? object.uniforms, key) ??
142+
getVectorComponent(object, key) ??
143+
getVectorComponent(object.material, key) ??
144+
getUniformComponent(
145+
object.material?.uniforms ?? object.uniforms,
146+
key
147+
)
148+
149+
return value
150+
}
151+
152+
function getProperty(target: ThreeObject | undefined, key: string) {
153+
return target && key in target
154+
? getAnimatableValue(target[key])
155+
: undefined
156+
}
157+
158+
function getUniformValue(uniforms: Uniforms | undefined, key: string) {
159+
return getAnimatableValue(uniforms?.[key]?.value)
160+
}
161+
162+
function getVectorComponent(target: ThreeObject | undefined, key: string) {
163+
const axis = key.slice(-1).toLowerCase()
164+
const vector = target?.[key.slice(0, -1)]
165+
return vector && ["x", "y", "z", "w"].includes(axis)
166+
? getAnimatableValue(vector[axis])
167+
: undefined
168+
}
169+
170+
function getUniformComponent(uniforms: Uniforms | undefined, key: string) {
171+
const uniform = uniforms?.[key.slice(0, -1)]
172+
return uniform
173+
? getVectorComponent(
174+
{ value: uniform.value },
175+
`value${key.slice(-1)}`
176+
)
177+
: undefined
178+
}
179+
180+
function getAnimatableValue(value: unknown) {
181+
if (typeof value === "string" || typeof value === "number") return value
182+
183+
return value &&
184+
typeof (value as ThreeObject).getStyle === "function"
185+
? (value as ThreeObject).getStyle()
186+
: undefined
187+
}
188+
189+
function isUniform(value: unknown): value is ThreeUniform {
190+
return Boolean(value && typeof value === "object" && "value" in value)
191+
}
192+
102193
function setObjectValues(object: ThreeObject, values: Record<string, unknown>) {
103194
for (const key in values) {
104195
setObjectValue(object, key, values[key])

‎packages/motion/src/utils/create-effect.ts‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
frame,
55
GroupAnimationWithThen,
66
invariant,
7+
motionValue,
78
type AnimationOptions,
89
type AnimationPlaybackControlsWithThen,
910
type MotionValue,
@@ -86,6 +87,18 @@ export interface EffectAdapter<Subject extends object> {
8687
has(subject: Subject): boolean
8788
}
8889

90+
export interface ResolvedEffect {
91+
adapter: EffectAdapter<any>
92+
initial: string | number
93+
}
94+
95+
export type EffectResolver = (
96+
subject: object,
97+
key: string,
98+
target: unknown,
99+
adapter: EffectAdapter<any> | undefined
100+
) => ResolvedEffect | undefined
101+
89102
export function createEffectAdapter<Subject extends object>(
90103
apply: (subject: Subject, values: Record<string, unknown>) => void
91104
): EffectAdapter<Subject> {
@@ -115,19 +128,15 @@ export function createEffectAdapter<Subject extends object>(
115128

116129
export function createEffectAnimate(
117130
adapters: Array<EffectAdapter<any>>,
118-
type: string
131+
type: string,
132+
resolve?: EffectResolver
119133
) {
120134
return <T extends object>(
121135
subject: object,
122136
keyframes: EffectAnimationTarget<T>,
123137
options: AnimationOptions = {}
124138
): AnimationPlaybackControlsWithThen => {
125-
const adapter = adapters.find((candidate) => candidate.has(subject))
126-
127-
invariant(
128-
Boolean(adapter),
129-
`No ${type} effect is registered for this subject.`
130-
)
139+
let adapter = adapters.find((candidate) => candidate.has(subject))
131140

132141
const { onComplete, ...transition } = options
133142
if (typeof transition.delay === "function") {
@@ -137,14 +146,25 @@ export function createEffectAnimate(
137146
const entries: Array<[string, MotionValue, any]> = []
138147

139148
for (const key in keyframes) {
140-
const value = adapter!.get(subject, key)
149+
const target = keyframes[key]
150+
let value = adapter?.get(subject, key)
151+
152+
if (!value) {
153+
const resolved = resolve?.(subject, key, target, adapter)
154+
155+
if (resolved) {
156+
adapter = resolved.adapter
157+
value = motionValue(resolved.initial)
158+
adapter.effect(subject, { [key]: value })
159+
}
160+
}
141161

142162
invariant(
143163
Boolean(value),
144-
`No MotionValue is registered for "${key}".`
164+
`No MotionValue is registered for "${key}" on this ${type}.`
145165
)
146166

147-
entries.push([key, value!, keyframes[key]])
167+
entries.push([key, value!, target])
148168
}
149169

150170
const animations = entries.map(([key, value, target]) =>

‎packages/motion/src/vgpu.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,16 @@ interface VGPUUniforms {
2424
const uniformAdapter = createEffectAdapter<VGPUUniforms>((uniforms, values) =>
2525
uniforms.set(values)
2626
)
27-
const animateEffect = createEffectAnimate([uniformAdapter], "vgpu uniform")
27+
const animateEffect = createEffectAnimate(
28+
[uniformAdapter],
29+
"vgpu uniform",
30+
(_subject, _key, target, adapter) => {
31+
const initial = Array.isArray(target) ? target[0] : undefined
32+
return typeof initial === "string" || typeof initial === "number"
33+
? { adapter: adapter ?? uniformAdapter, initial }
34+
: undefined
35+
}
36+
)
2837

2938
/**
3039
* Binds MotionValues to vgpu SharedUniforms, batching changed values into one
@@ -41,7 +50,7 @@ export function uniformEffect<T extends object>(
4150
}
4251

4352
/**
44-
* Animates MotionValues registered with a vgpu uniform effect.
53+
* Animates vgpu uniforms. Unregistered uniforms require explicit keyframes.
4554
*/
4655
export function animate<T extends object>(
4756
subject: UniformEffectSubject<T>,

0 commit comments

Comments
 (0)