coily 0.12.2 → 0.13.1

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.
package/README.md CHANGED
@@ -1,254 +1,171 @@
1
- # `coily`
1
+ # coily
2
2
 
3
- Spring Physics Utilities
3
+ Simulate values using spring physics.
4
4
 
5
- ## Installation & Setup
5
+ Coily animates numbers — and whole numeric shapes — with damped spring motion. Each frame is computed from the closed-form solution of the spring equation — underdamped, critically damped, or overdamped — rather than numerical integration, so motion doesn't accumulate error and springs can be retargeted mid-flight without losing momentum.
6
6
 
7
- `coily` is available on npm and can be installed with your favorite package manager:
7
+ The core has zero dependencies and runs anywhere (it falls back from `requestAnimationFrame` to `setTimeout` outside the browser). Vue and Nuxt integrations ship as separate entry points; `vue` and `@nuxt/kit` are optional peer dependencies.
8
8
 
9
- ```shell
10
- $ yarn add coily
11
- # or
12
- $ npm i coily
13
- ```
14
-
15
- Then import the creator from the package in your code:
16
-
17
- ```typescript
18
- import { createSpring } from 'coily'
9
+ ## Install
19
10
 
20
- const spring = createSpring(0, { mass: 1, tension: 100, friction: 25 })
11
+ ```sh
12
+ pnpm add coily
21
13
  ```
22
14
 
23
- ## Usage
15
+ ## Quick start
24
16
 
25
- ### Creating a Spring
17
+ ```ts
18
+ import { createSpringSystem, defineSpring } from 'coily'
26
19
 
27
- The `createSpring` function takes the following arguments:
28
-
29
- - `initial: number`
30
- The initial value of the spring, and its target. All springs start in a resting state, but you can set `spring.target`
31
- at any time
32
-
33
- - `config: SpringConfig`
34
- The configuration for the spring. `SpringConfig` takes the following parameters:
35
- - `config.mass: number`
36
- How massive the spring is. A lower number will allow the spring to speed up and slow down more quickly than a
37
- larger number. Larger numbers are more likely to overshoot the `target`
20
+ const system = createSpringSystem()
21
+ system.start()
38
22
 
39
- - `config.tension: number`
40
- How much force the spring experiences toward its `target`. A higher value will move the spring more quickly, and
41
- allow the spring to potentially overshoot.
23
+ const spring = system.createSpring(0, defineSpring({ tension: 500, damping: 40 }))
42
24
 
43
- - `config.friction: number`
44
- How much dampening the spring experiences against its tension. A higher friction will make sure the spring doesn't
45
- move too quickly, and slows down dramatically as it approaches the `target`
25
+ spring.onUpdate(() => {
26
+ ball.style.setProperty('--x', String(spring.value))
27
+ })
46
28
 
47
- - `options: SpringOptions`
48
- Additional options for the spring. `SpringOptions` takes the following parameters:
49
- - `options.restingDistance: number`
50
- The minimum difference between the `target` and `value` at which the spring will consider itself "at" the `target`
29
+ // Animate toward a new target at any time. Position and velocity
30
+ // carry over, so interruptions look natural.
31
+ spring.target = 300
32
+ ```
51
33
 
52
- - `options.restingVelocity: number`
53
- The minimum velocity at which the spring will consider itself "not moving"
34
+ ## Configuring springs
54
35
 
55
- - `options.arrivalBehavior: 'bounce' | 'clamp' | 'none' | number | ((velocity: number) => number)`
56
- How the spring's `velocity` behaves when it arrives at its `target` value.
57
- `velocity` is expressed in unit/second. Defaults to `none`.
58
- - `'bounce'`: multiplies the velocity by -1, bouncing the value back in the direction from which it came
59
- - `'clamp'`: multiplies the velocity by 0, instantly stopping the spring at its value
60
- - `'none'`: multiplies the velocity by 1, allowing the spring to overshoot as necessary
61
- - `number`: multiplies the velocity by the given number
62
- - `(velocity: number) => number`: sets the velocity to the result of a function whose only argument is the
63
- previous velocity
36
+ `defineSpring` accepts several input shapes; whatever you leave out is derived:
64
37
 
65
- #### Spring Config Tips
38
+ ```ts
39
+ defineSpring({ tension: 500, damping: 40 }) // direct physical parameters
40
+ defineSpring({ tension: 500, dampingRatio: 0.7 }) // damping derived
41
+ defineSpring({ tension: 500, bounce: 0.3 }) // bounce = 1 - dampingRatio
42
+ defineSpring({ duration: 750, dampingRatio: 1 }) // tuned to settle in ~750ms
43
+ defineSpring({ duration: 750, bounce: 0.5 })
44
+ ```
66
45
 
67
- The configuration object above provides a good starting point when picking your config:
46
+ - **`tension`** — stiffness (> 0)
47
+ - **`damping`** — friction (≥ 0)
48
+ - **`dampingRatio`** — 0 = undamped, < 1 = bouncy, 1 = critically damped, > 1 = overdamped
49
+ - **`bounce`** — friendlier alias for damping ratio: −1 (overdamped) to 1 (max bounce)
50
+ - **`duration`** — target settle time in ms. Assumes an initial displacement of 1; pass `displacement` matching your animation range for accurate timing
51
+ - **`mass`** — defaults to 1
52
+ - **`precision`** — decimal places of the resting threshold (default 2). A spring is _resting_ once its remaining motion cannot reach half a unit in the last place — 0.005 at the default. Values are never rounded; set precision to match your domain's resolution (see [PRECISION.md](https://github.com/tkofh/coily/blob/main/PRECISION.md))
68
53
 
69
- ```typescript
70
- createSpring(0, { mass: 1, tension: 100, friction: 25 })
71
- ```
54
+ Without a config, springs are critically damped with a ~500ms settle time.
72
55
 
73
- Don't be afraid to make `mass` a decimal, and don't be afraid of large tensions and frictions either. Picking the
74
- configuration is more of an art than a science.
56
+ ## Spring API
75
57
 
76
- #### Spring Options
58
+ - `spring.target` — set to animate toward a new value
59
+ - `spring.value` — current value; writable to displace the spring
60
+ - `spring.velocity` — current velocity; writable to fling
61
+ - `spring.jumpTo(v)` — snap to a value with no animation
62
+ - `spring.config` — assign a new `SpringConfig`, or `null` to revert to the default (or the leader's, if following)
63
+ - `spring.isResting`, `spring.timeRemaining` — settle state and estimated ms until rest
64
+ - `spring.settled` — a promise that resolves when the spring next comes to rest (immediately if already resting). Retargeting mid-flight extends the wait; disposing resolves it. `await spring.settled` to sequence animations
65
+ - `spring.onUpdate(cb)` / `onStart(cb)` / `onStop(cb)` / `onDispose(cb)` — subscribe; each returns an unsubscribe function. `start` fires when the spring leaves rest, `stop` when it settles — the two always alternate, and retargeting mid-flight fires neither
66
+ - `spring.dispose()` — release the spring (calling it twice is a no-op)
77
67
 
78
- The spring options object is helpful in reducing the amount of computation your springs perform. If the spring was
79
- allowed to wait until its `velocity` and difference (`value` - `target`) were _at_ zero, it would imperceptibly update
80
- every frame for a very long time.
68
+ ### Chaining
81
69
 
82
- The `restingDistance` and `restingVelocity` options help combat this, by telling the spring at what point it should
83
- consider itself on target and resting. Once the velocity is less than `restingVelocity` and the difference
84
- between `value` and `target` is less than `restingDistance`, the spring sets its `value` to its `target` and enters
85
- the `resting` state.
70
+ A spring can follow another spring's live value instead of a fixed number:
86
71
 
87
- ### Working With Springs
72
+ ```ts
73
+ const leader = system.createSpring(0)
74
+ const follower = system.createSpring({ target: leader })
75
+ const trailing = system.createSpring({ target: { spring: leader, offset: 20 } })
76
+ ```
88
77
 
89
- #### Reading Information
78
+ Followers inherit the leader's config unless given their own. Assigning a number to `target` unfollows.
90
79
 
91
- The spring exposes some readonly information such as its `value`, `state` and `velocity`:
80
+ ### Objects
92
81
 
93
- ```typescript
94
- /**
95
- * The current value of the spring
96
- */
97
- spring.value
82
+ `system.createSpringObject(value, config?)` springs over any numeric shape — a plain object or array whose leaves are all numbers, nested arbitrarily. Each leaf becomes an independent channel behind one composite API:
98
83
 
99
- /**
100
- * In which state the spring is currently. Will be one of:
101
- * - "resting"
102
- * - "moving"
103
- * - "frozen"
104
- */
105
- spring.state
84
+ ```ts
85
+ const spring = system.createSpringObject({ position: { x: 0, y: 0 }, opacity: 1 })
106
86
 
107
- /**
108
- * How fast the spring is currently moving, and in which direction
109
- */
110
- spring.velocity
87
+ spring.target = { position: { x: 100 } } // partial — other channels are left alone
88
+ spring.value // { position: { x, y }, opacity } — a stable, read-only mirror
111
89
  ```
112
90
 
113
- Additionally, `target` and `config` can be updated whenever:
114
-
115
- ```typescript
116
- /**
117
- * Get & Set the target of the spring
118
- */
119
- console.log(spring.target)
120
- spring.target = 10
91
+ The shape is fixed at creation, and unknown channels throw with their path (`position.z`). `value`, `velocity`, and `jumpTo` take the same partial shapes. Composite events are coalesced: `update` fires at most once per frame with every channel in its final per-frame state, and `stop` always lands after that frame's final `update`. `settled` and reduced motion compose channel-wise.
121
92
 
122
- /**
123
- * Get & Set the config of the spring
124
- */
125
- console.log(spring.config)
126
- spring.config = { mass: 0.1, tension: 500, friction: 5 }
127
- ```
93
+ Shapes are validated at compile time too (the `Shape` type — interfaces like your own `Vector2` work without index signatures): non-numeric, optional, or `undefined`-typed channels are rejected where they're declared.
128
94
 
129
- #### Updating
95
+ Configs apply per channel. Pass a single `SpringConfig` for every channel, or a shape mirroring the value with configs (or `null` to revert) at any level — a config at a subtree covers every channel below it:
130
96
 
131
- To simulate the spring and update its value, call the `simulate` method and pass in the number of milliseconds since the
132
- last update:
97
+ ```ts
98
+ spring.config = { position: stiff, opacity: defineSpring({ duration: 300, dampingRatio: 1 }) }
99
+ ```
133
100
 
134
- ```typescript
135
- // Tickloop is a library that exposes a simple requestAnimationFrame based update loop
136
- import { createTicker } from 'tickloop'
137
- import { createSpring } from 'coily'
101
+ Configs are `SpringConfig` instances — build them with `defineSpring`. Unlike the scalar `useSpring` above, config positions here don't accept bare option objects: a plain object is always a per-channel shape, so any non-config leaf it reaches throws with its path.
138
102
 
139
- const spring = createSpring(0, { mass: 1, tension: 100, friction: 20 })
103
+ Spring objects chain channel-wise. Assign another spring object of the exact same shape (optionally with a partial offset shape), and a partial numeric target detaches only the channels it names:
140
104
 
141
- const ticker = createTicker()
142
- ticker.add((_, delta) => {
143
- spring.simulate(delta)
144
- })
105
+ ```ts
106
+ follower.target = leader
107
+ trailing.target = { spring: leader, offset: { position: { x: 20 } } }
145
108
  ```
146
109
 
147
- #### Freezing
110
+ ## Reduced motion
148
111
 
149
- To hold a spring in place (while maintaining its velocity), use the `freeze()` (and `unfreeze()`) methods.
150
- Calling `freeze()` will set the spring's `state` to `'frozen'`
112
+ Coily respects `prefers-reduced-motion` by default. When it's active, springs snap to their targets instead of animating: retargets and value writes apply instantly, velocity impulses are ignored, and springs created displaced start at their target. Events stay coherent — one `update` per change, no `start`/`stop`, and `settled` resolves immediately — so code written against the animated path keeps working.
151
113
 
152
- ```typescript
153
- const spring = createSpring(0, { mass: 1, tension: 100, friction: 20 })
114
+ Control it with the `reducedMotion` system option: `'user'` (default — follow the OS setting, including live changes, which finish in-flight animations instantly), `'always'`, or `'never'`. Read `system.reducedMotion` to gate purely decorative effects (particles, flourishes) in your own code.
154
115
 
155
- spring.target = 100
116
+ ## Vue
156
117
 
157
- console.log(spring.value) // 0
118
+ Call `useSpringSystem()` once near the root of your app. It returns the spring system provided by this component or an ancestor; if none exists, it creates one, provides it to descendants, and starts/stops it with the component lifecycle. It's idempotent, and options apply only when a system is actually created:
158
119
 
159
- spring.freeze()
160
- spring.simulate(1000)
120
+ ```ts
121
+ import { useSpringSystem } from 'coily/vue'
161
122
 
162
- console.log(spring.value) // 0
123
+ const system = useSpringSystem() // e.g. read system.reducedMotion to gate decorative effects
163
124
  ```
164
125
 
165
- ### Creating a Spring System
126
+ (`provideSpringSystem(system, app?)` remains for plugging in a system you created yourself — mostly useful in tests. You manage `start()`/`stop()` for it.)
166
127
 
167
- Manually updating every spring with its `simulate` method would be tedious to say the least. Where possible, prefer
168
- using a `SpringSystem` to group springs together and provide a single call site for updating each spring:
128
+ Then animate anywhere below:
169
129
 
170
- ```typescript
171
- import { createSpringSystem } from 'coily'
130
+ ```vue
131
+ <script setup>
132
+ import { useSpring } from 'coily/vue'
172
133
 
173
- // First, create the system
174
- const system = createSpringSystem()
175
-
176
- // Then, create some springs
177
- const spring1 = system.createSpring(0, { mass: 1, tension: 100, friction: 20 })
178
- const spring2 = system.createSpring(0, { mass: 0.25, tension: 50, friction: 10 })
134
+ const target = ref(0)
135
+ const x = useSpring(target, { duration: 500, bounce: 0.3 })
136
+ </script>
179
137
 
180
- // Simulate all springs at once from the system
181
- system.simulate(16)
138
+ <template>
139
+ <div class="ball" :style="{ translate: `${x}px 0` }" @click="target = 300" />
140
+ </template>
182
141
  ```
183
142
 
184
- Should a spring become irrelevant for some reason, remember to call the `cleanup` method so that the system stops
185
- updating it:
186
-
187
- ```typescript
188
- import { createSpringSystem } from 'coily'
143
+ `useSpring` returns a `SpringRef`: a writable ref of the animated value with `velocity`, `isResting`, and `timeRemaining` refs plus `jumpTo()` attached. The target can be a ref, a getter, or another `SpringRef` (which chains the springs). Options are also reactive — swap configs and the spring reconfigures in place.
189
144
 
190
- const system = createSpringSystem()
145
+ Numeric shapes work the same way: pass a record or array (plain, ref, or getter) and get a `SpringObjectRef`. Reads are the deep-readonly composite value, writes take partial shapes, options accept reactive per-channel config shapes, and passing another `SpringObjectRef` follows it channel-wise. Deeply reactive targets retarget on nested mutation. For several _independent_ scalar springs, map over the targets — composables are loop-safe: `targets.map((t) => useSpring(t))`.
191
146
 
192
- const spring = system.createSpring(0, { mass: 1, tension: 100, friction: 20 })
147
+ There's also a renderless `<SpringValue :target="n">` component exposing `{ value, velocity, isResting, timeRemaining, jumpTo }` through its default slot.
193
148
 
194
- // Later
149
+ For imperative work — a dynamic set of springs created and disposed at arbitrary times (particles, per-item effects) — `useSpringPool()` returns `createSpring`/`createSpringObject` bound to the provided system. Every spring created through the pool is disposed automatically when the component's scope is torn down, so leaked motions are structurally impossible; disposing a spring manually before that is fine.
195
150
 
196
- system.cleanup(spring)
197
- ```
151
+ ## Nuxt
198
152
 
199
- ### Spring Chains
200
-
201
- Sometimes the `target` of one spring should be the `value` of another.
202
- This can be tedious to set up manually and involves juggling multiple updates per frame to get a good look at the
203
- current state.
204
-
205
- Spring Chains help with this problem by building on the `createSpring` API. You'll still supply an `initial` target,
206
- a `SpringConfig`, and an optional `SpringOptions`. You'll also pass an array of chain "links" that describe additional
207
- values in the chain.
208
-
209
- The links take one of two forms:
210
-
211
- - A fixed, additive offset from the previous value, e.g. `50` will make Spring 2 target Spring 1's current value plus 50.
212
- - A function with the following signature:
213
- ```typescript
214
- const link = (
215
- previousSpringValue: number,
216
- previousSpringTarget: number,
217
- currentSpringValue?: number,
218
- currentSpringTarget?: number
219
- ): number => /* ... */
220
- ```
221
- The `currentSpringTarget` and `currentSpringValue` will be `undefined` the first time the function is called, as the
222
- targets are initialized for all springs.
223
-
224
- #### Creating
225
-
226
- ```typescript
227
- const chain = createSpringChain(
228
- 0, // initial
229
- [50, 50, (value) => value * 1.25],
230
- { mass: 10, tension: 3000, friction: 300 }, // config
231
- )
153
+ ```ts
154
+ export default defineNuxtConfig({
155
+ modules: ['coily/nuxt'],
156
+ coily: {
157
+ debug: false, // debug logs active motion counts
158
+ reducedMotion: 'user', // 'user' | 'always' | 'never'
159
+ },
160
+ })
232
161
  ```
233
162
 
234
- #### Reading State
163
+ The module provides a spring system for the whole app (started on the client), auto-imports `useSpring`, `useSpringSystem`, `useSpringPool`, and `defineSpring`, and registers the `SpringValue` component.
235
164
 
236
- Spring Chains have almost the same interface as Springs do.
165
+ ## Timing
237
166
 
238
- Instead of a single `value`, they have an array of numbers as their value. The same goes for `targets`, `states`,
239
- and `velocities`. Each of these arrays are updated _in place_, which means it is safe to grab a reference to the value
240
- and read from it later.
167
+ The built-in ticker advances springs once per displayed frame, so motion is as smooth as the screen it runs on — 60Hz, 120Hz, or adaptive sync. The loop sleeps while every spring is at rest (an idle system schedules no frames) and wakes on the next write. Set `fps` (option/property) to cap the rate; caps are paced to whole display frames, and each tick still receives the true elapsed time. Large frame gaps — e.g. returning from a backgrounded tab — are clamped via `lagThreshold` (default 500ms) and `adjustedLag` (default 33ms), so springs don't teleport. For manual stepping, skip `system.start()` and call `system.advance(dtMs)` yourself.
241
168
 
242
- Additionally, Spring Chains have a singular `state` property which indicates if _any_ of its links are in a `'moving'` state or not.
169
+ ## License
243
170
 
244
- There is also a singular `target` property which returns the first target in the chain. Setting this will update the springs as well.
245
-
246
- ```typescript
247
- chain.values // readonly number[]
248
- chain.velocities // readonly number[]
249
- chain.targets // readonly number[]
250
- chain.states // readonly number[]
251
-
252
- chain.target = 10 // get and set the first target
253
- chain.state // if any children are 'moving', this will be moving. if the chain is frozen, it will be 'frozen'. otherwise, it is 'resting'.
254
- ```
171
+ MIT
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { _ as defineSpring, a as Spring2D, c as Spring2DWithOffset, d as SpringPosition, f as SpringTarget, g as SpringState, h as SpringOptions, i as TickerOptions, l as Vector2, m as SpringConfig, n as SpringSystemOptions, o as Spring2DPosition, p as SpringWithOffset, r as createSpringSystem, s as Spring2DTarget, t as SpringSystem, u as Spring } from "./system-coAFNYnb.js";
2
- export { type Spring, type Spring2D, type Spring2DPosition, type Spring2DTarget, type Spring2DWithOffset, type SpringConfig, type SpringOptions, type SpringPosition, type SpringState, type SpringSystem, type SpringSystemOptions, type SpringTarget, type SpringWithOffset, type TickerOptions, type Vector2, createSpringSystem, defineSpring };
1
+ import { _ as SpringOptions, a as ConfigShape, c as Shape, d as SpringObjectWithOffset, f as Spring, g as SpringConfig, h as SpringWithOffset, i as TickerOptions, l as SpringObject, m as SpringTarget, n as SpringSystemOptions, o as PartialShape, p as SpringPosition, r as createSpringSystem, s as ReadonlyShape, t as SpringSystem, u as SpringObjectTarget, v as SpringState, y as defineSpring } from "./system-86fsXJN_.js";
2
+ export { type ConfigShape, type PartialShape, type ReadonlyShape, type Shape, type Spring, type SpringConfig, type SpringObject, type SpringObjectTarget, type SpringObjectWithOffset, type SpringOptions, type SpringPosition, type SpringState, type SpringSystem, type SpringSystemOptions, type SpringTarget, type SpringWithOffset, type TickerOptions, createSpringSystem, defineSpring };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { r as defineSpring, t as createSpringSystem } from "./system-Bzrx4uso.js";
1
+ import { r as defineSpring, t as createSpringSystem } from "./system-Csho09XW.js";
2
2
  export { createSpringSystem, defineSpring };
package/dist/nuxt.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  import { NuxtModule } from "@nuxt/schema";
2
-
3
2
  //#region src/vue/nuxt.d.ts
4
3
  interface CoilyModuleOptions {
5
4
  debug?: boolean;
5
+ fps?: number;
6
+ lagThreshold?: number;
7
+ adjustedLag?: number;
8
+ reducedMotion?: 'user' | 'always' | 'never';
6
9
  }
7
10
  declare const coilyModule: NuxtModule;
8
11
  //#endregion
package/dist/nuxt.js CHANGED
@@ -1,12 +1,18 @@
1
1
  import { addComponent, addImports, addPluginTemplate, defineNuxtModule } from "@nuxt/kit";
2
2
  //#region src/vue/nuxt.ts
3
3
  function getPluginTemplate(options) {
4
+ const systemOptions = {};
5
+ if (options.debug) systemOptions.debug = true;
6
+ if (options.fps !== void 0) systemOptions.fps = options.fps;
7
+ if (options.lagThreshold !== void 0) systemOptions.lagThreshold = options.lagThreshold;
8
+ if (options.adjustedLag !== void 0) systemOptions.adjustedLag = options.adjustedLag;
9
+ if (options.reducedMotion) systemOptions.reducedMotion = options.reducedMotion;
4
10
  return `import { createSpringSystem } from 'coily'
5
11
  import { provideSpringSystem } from 'coily/vue'
6
12
 
7
13
  export default defineNuxtPlugin((nuxtApp) => {
8
14
  nuxtApp.hook('app:created', (vueApp) => {
9
- const system = createSpringSystem(${options.debug ? "{ debug: true }" : ""})
15
+ const system = createSpringSystem(${Object.keys(systemOptions).length > 0 ? JSON.stringify(systemOptions) : ""})
10
16
  provideSpringSystem(system, vueApp)
11
17
 
12
18
  if(import.meta.client) {
@@ -35,7 +41,11 @@ const coilyModule = defineNuxtModule({
35
41
  },
36
42
  {
37
43
  from: "coily/vue",
38
- name: "useSpring2D"
44
+ name: "useSpringSystem"
45
+ },
46
+ {
47
+ from: "coily/vue",
48
+ name: "useSpringPool"
39
49
  },
40
50
  {
41
51
  from: "coily/vue",
@@ -44,7 +54,12 @@ const coilyModule = defineNuxtModule({
44
54
  },
45
55
  {
46
56
  from: "coily/vue",
47
- name: "SpringRef2D",
57
+ name: "SpringObjectRef",
58
+ type: true
59
+ },
60
+ {
61
+ from: "coily/vue",
62
+ name: "SpringPool",
48
63
  type: true
49
64
  },
50
65
  {