@rafaelaugusto/jolt 0.1.0-beta.14 → 0.1.0-beta.15

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/src/size.ts ADDED
@@ -0,0 +1,302 @@
1
+ import { Application } from '@nativescript/core'
2
+ import type { View } from '@nativescript/core'
3
+ import { toView } from './animate.js'
4
+ import { onReducedMotion, reducedMotion } from './config.js'
5
+ import { getDriver } from './driver/index.js'
6
+ import type { Animation } from './engine.js'
7
+ import { createClock, type PlaybackClock } from './playback.js'
8
+ import { createTrack, type Track } from './track.js'
9
+ import {
10
+ resolveTransition,
11
+ springs,
12
+ type Spring,
13
+ type SpringName,
14
+ type Tween,
15
+ } from './transition.js'
16
+ import {
17
+ dimension,
18
+ sizeLayout,
19
+ type SizeAxis,
20
+ type SizePixels,
21
+ type SizeValues,
22
+ } from './size-layout.js'
23
+ import type { Target } from './types.js'
24
+
25
+ export type SizeDimensions = SizeValues
26
+ export type SizeOptions =
27
+ | Omit<Spring, 'repeat' | 'repeatType' | 'repeatDelay'>
28
+ | Omit<Tween, 'repeat' | 'repeatType' | 'repeatDelay' | 'times' | 'easeTrack'>
29
+ export interface SizeAnimation extends Animation {
30
+ pause(): void
31
+ play(): void
32
+ readonly paused: boolean
33
+ /** Hold the current size; restore:true releases the temporary size back to the original declaration. */
34
+ stop(options?: { restore?: boolean }): void
35
+ }
36
+ const owners = new WeakMap<
37
+ View,
38
+ { animation: SizeAnimation; axes: readonly SizeAxis[] }
39
+ >()
40
+
41
+ /** Animate the actual layout box, including intrinsic auto sizes. Layout runs in JS on the UI thread. */
42
+ export function animateSize(
43
+ target: Target,
44
+ dimensions: SizeDimensions,
45
+ options?: SizeOptions | SpringName,
46
+ ): SizeAnimation
47
+ export function animateSize(
48
+ target: Target,
49
+ dimensions: SizeDimensions,
50
+ change: () => void,
51
+ options?: SizeOptions | SpringName,
52
+ ): SizeAnimation
53
+ export function animateSize(
54
+ target: Target,
55
+ dimensions: SizeDimensions,
56
+ changeOrOptions?: (() => void) | SizeOptions | SpringName,
57
+ options?: SizeOptions | SpringName,
58
+ ): SizeAnimation {
59
+ const view = toView(target)
60
+ if (!dimensions || typeof dimensions !== 'object' || Array.isArray(dimensions))
61
+ throw new TypeError('animateSize takes a width/height object.')
62
+ const axes = Object.keys(dimensions) as SizeAxis[]
63
+ if (!axes.length || axes.some((axis) => axis !== 'width' && axis !== 'height'))
64
+ throw new TypeError('animateSize needs width and/or height.')
65
+ for (const axis of axes) dimension(dimensions[axis], axis)
66
+ const destination = { ...dimensions }
67
+ const change = typeof changeOrOptions === 'function' ? changeOrOptions : undefined
68
+ if (change?.constructor.name === 'AsyncFunction')
69
+ throw new TypeError('animateSize changes must be synchronous.')
70
+ const transition = normalize(
71
+ change ? options : (changeOrOptions as SizeOptions | SpringName | undefined),
72
+ )
73
+ // Solve before ownership changes, including custom easing/physical-spring validation.
74
+ const validation = createTrack('x', [0, 100], transition, 0)
75
+ if (!Number.isFinite(validation.end) || !validation.values.every(Number.isFinite))
76
+ throw new RangeError('animateSize needs a finite curve with finite samples.')
77
+ const previous = owners.get(view)
78
+ const driver = getDriver()
79
+ const layout = sizeLayout(view, axes, previous?.axes, () => {
80
+ const frame = driver.layoutFrame?.(view)
81
+ return frame ? { width: frame.width, height: frame.height } : view.getActualSize()
82
+ })
83
+ // Release the previous overlay only after every caller-supplied input was validated.
84
+ const start = layout.read()
85
+ previous?.animation.stop({ restore: true })
86
+ let resolve!: (value: boolean) => void
87
+ let reject!: (error: unknown) => void
88
+ const finished = new Promise<boolean>((done, fail) => {
89
+ resolve = done
90
+ reject = fail
91
+ })
92
+ let settled = false
93
+ let paused = false
94
+ let initialized = false
95
+ let cancelFrame: (() => void) | undefined
96
+ let unwatch: (() => void) | undefined
97
+ let clock: PlaybackClock | undefined
98
+ let tracks = new Map<SizeAxis, Track>()
99
+ let endpoint: SizePixels | undefined
100
+ const cleanup = () => {
101
+ cancelFrame?.()
102
+ cancelFrame = undefined
103
+ clock?.cancel()
104
+ clock = undefined
105
+ unwatch?.()
106
+ layout.dispose()
107
+ view.off('unloaded', unloaded)
108
+ Application.off(Application.suspendEvent, unloaded)
109
+ if (owners.get(view)?.animation === animation) owners.delete(view)
110
+ }
111
+ const finish = (success: boolean, error?: unknown) => {
112
+ if (settled) return
113
+ settled = true
114
+ cleanup()
115
+ if (error !== undefined) reject(error)
116
+ else resolve(success)
117
+ }
118
+ const complete = () => {
119
+ layout.commit(destination)
120
+ layout.layout()
121
+ finish(true)
122
+ }
123
+ const stop = (restore = false) => {
124
+ if (settled) return
125
+ layout.commit(restore ? undefined : layout.read())
126
+ finish(false)
127
+ view.requestLayout()
128
+ }
129
+ function unloaded() {
130
+ stop(true)
131
+ }
132
+ const schedule = () => {
133
+ if (!cancelFrame && !settled && !paused) cancelFrame = driver.frame(tick)
134
+ }
135
+ function tick() {
136
+ cancelFrame = undefined
137
+ if (settled || paused) return
138
+ try {
139
+ if (!view.isLoaded || view.visibility === 'collapse' || !view.nativeViewProtected) {
140
+ stop(true)
141
+ return
142
+ }
143
+ const next = layout.measure(destination)
144
+ if (settled) return
145
+ if (axes.some((axis) => !Number.isFinite(next[axis]) || next[axis] < 0))
146
+ throw new Error('animateSize measured an invalid native size.')
147
+ if (reducedMotion()) {
148
+ complete()
149
+ return
150
+ }
151
+ if (
152
+ !initialized &&
153
+ axes.every((axis) => Math.abs(next[axis] - start[axis]) < 0.5)
154
+ ) {
155
+ complete()
156
+ return
157
+ }
158
+ const elapsed = clock?.time() ?? 0
159
+ if (
160
+ !endpoint ||
161
+ axes.some((axis) => Math.abs(next[axis] - endpoint![axis]) > 0.5)
162
+ ) {
163
+ const from = initialized ? layout.read() : start
164
+ const fresh = new Map<SizeAxis, Track>()
165
+ for (const axis of axes)
166
+ fresh.set(
167
+ axis,
168
+ createTrack(
169
+ 'x',
170
+ [from[axis], next[axis]],
171
+ initialized ? { ...transition, delay: 0 } : transition,
172
+ tracks.get(axis)?.velocityAt(elapsed) ?? 0,
173
+ ),
174
+ )
175
+ tracks = fresh
176
+ endpoint = next
177
+ clock?.cancel()
178
+ const end = Math.max(...[...tracks.values()].map((track) => track.end))
179
+ clock = driver.clock?.(end) ?? createClock(() => driver.now())
180
+ initialized = true
181
+ }
182
+ const time = clock!.time()
183
+ if ([...tracks.values()].every((track) => time >= track.end)) {
184
+ complete()
185
+ return
186
+ }
187
+ const values: SizeValues = {}
188
+ for (const [axis, track] of tracks) values[axis] = Math.max(0, track.valueAt(time))
189
+ layout.write(values)
190
+ layout.layout()
191
+ if (settled) return
192
+ schedule()
193
+ } catch (error) {
194
+ layout.commit()
195
+ view.requestLayout()
196
+ finish(false, error)
197
+ }
198
+ }
199
+ const animation: SizeAnimation = {
200
+ finished,
201
+ then: (done, fail) => finished.then(done, fail),
202
+ get paused() {
203
+ return paused
204
+ },
205
+ stop: (options) => stop(options?.restore === true),
206
+ pause() {
207
+ if (settled || paused) return
208
+ paused = true
209
+ clock?.pause()
210
+ cancelFrame?.()
211
+ cancelFrame = undefined
212
+ },
213
+ play() {
214
+ if (settled || !paused) return
215
+ paused = false
216
+ clock?.play()
217
+ schedule()
218
+ },
219
+ }
220
+ owners.set(view, { animation, axes })
221
+ try {
222
+ layout.watch(() => stop(true))
223
+ layout.write(start)
224
+ view.on('unloaded', unloaded)
225
+ Application.on(Application.suspendEvent, unloaded)
226
+ unwatch = onReducedMotion((reduced) => {
227
+ if (reduced && !settled) {
228
+ try {
229
+ complete()
230
+ } catch (error) {
231
+ finish(false, error)
232
+ }
233
+ }
234
+ })
235
+ const result: unknown = change?.()
236
+ if (result && typeof (result as PromiseLike<unknown>).then === 'function')
237
+ throw new TypeError('animateSize changes must be synchronous.')
238
+ if (!view.isLoaded || view.visibility === 'collapse' || !layout.ready()) {
239
+ layout.commit(destination)
240
+ finish(false)
241
+ } else schedule()
242
+ } catch (error) {
243
+ stop(true)
244
+ throw error
245
+ }
246
+ return animation
247
+ }
248
+
249
+ function normalize(input?: SizeOptions | SpringName) {
250
+ if (typeof input === 'string') {
251
+ if (!Object.hasOwn(springs, input))
252
+ throw new TypeError(`Unknown size spring "${input}".`)
253
+ input = springs[input]
254
+ }
255
+ if (
256
+ input !== undefined &&
257
+ (!input || typeof input !== 'object' || Array.isArray(input))
258
+ )
259
+ throw new TypeError('Invalid animateSize options.')
260
+ const allowed = new Set([
261
+ 'type',
262
+ 'duration',
263
+ 'ease',
264
+ 'stiffness',
265
+ 'damping',
266
+ 'mass',
267
+ 'bounce',
268
+ 'velocity',
269
+ 'delay',
270
+ ])
271
+ for (const [key, value] of Object.entries(input ?? {})) {
272
+ if (!allowed.has(key))
273
+ throw new TypeError(
274
+ `Unsupported animateSize option "${key}"; repeat and seek are not supported.`,
275
+ )
276
+ if (value === undefined) continue
277
+ if (
278
+ key !== 'type' &&
279
+ key !== 'ease' &&
280
+ (typeof value !== 'number' || !Number.isFinite(value))
281
+ )
282
+ throw new RangeError(`animateSize ${key} must be finite.`)
283
+ if (key === 'type' && value !== 'spring' && value !== 'tween')
284
+ throw new TypeError('Invalid size transition type.')
285
+ if (typeof value === 'number') {
286
+ if (['duration', 'delay', 'damping'].includes(key) && value < 0)
287
+ throw new RangeError(`${key} must be nonnegative.`)
288
+ if (['mass', 'stiffness'].includes(key) && value <= 0)
289
+ throw new RangeError(`${key} must be positive.`)
290
+ if (key === 'bounce' && (value < -1 || value > 1))
291
+ throw new RangeError('bounce must be between -1 and 1.')
292
+ }
293
+ }
294
+ const resolved = resolveTransition(input ?? {}, 'x', 2)
295
+ if (
296
+ resolved.curve.type === 'spring' &&
297
+ input?.duration === 0 &&
298
+ !('stiffness' in input || 'damping' in input || 'mass' in input)
299
+ )
300
+ throw new RangeError('Use a zero-duration tween for immediate sizing.')
301
+ return resolved
302
+ }