@mun-ui/ui 0.0.0-stage → 0.2.0

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.
Files changed (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/bin/compile.mjs +38 -0
  4. package/bin/dev-protocol.mjs +94 -0
  5. package/bin/formatter.mjs +109 -0
  6. package/bin/hot-reload.mjs +38 -0
  7. package/bin/mun.mjs +521 -0
  8. package/bin/native.mjs +133 -0
  9. package/bin/pnpm-workspace.mjs +58 -0
  10. package/bin/program-patch.mjs +104 -0
  11. package/bin/project.mjs +322 -0
  12. package/bin/watch.mjs +316 -0
  13. package/bin/workflow.mjs +261 -0
  14. package/dist/astro.d.ts +3 -0
  15. package/dist/astro.d.ts.map +1 -0
  16. package/dist/astro.js +3 -0
  17. package/dist/astro.js.map +1 -0
  18. package/dist/closures.d.ts +2 -0
  19. package/dist/closures.d.ts.map +1 -0
  20. package/dist/closures.js +2 -0
  21. package/dist/closures.js.map +1 -0
  22. package/dist/compiler/index.d.ts +2 -0
  23. package/dist/compiler/index.d.ts.map +1 -0
  24. package/dist/compiler/index.js +2 -0
  25. package/dist/compiler/index.js.map +1 -0
  26. package/dist/core.d.ts +3 -0
  27. package/dist/core.d.ts.map +1 -0
  28. package/dist/core.js +3 -0
  29. package/dist/core.js.map +1 -0
  30. package/dist/experimental.d.ts +2 -0
  31. package/dist/experimental.d.ts.map +1 -0
  32. package/dist/experimental.js +2 -0
  33. package/dist/experimental.js.map +1 -0
  34. package/dist/index.d.ts +3 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +3 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/jsx-dev-runtime.d.ts +2 -0
  39. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  40. package/dist/jsx-dev-runtime.js +2 -0
  41. package/dist/jsx-dev-runtime.js.map +1 -0
  42. package/dist/jsx-runtime.d.ts +2 -0
  43. package/dist/jsx-runtime.d.ts.map +1 -0
  44. package/dist/jsx-runtime.js +2 -0
  45. package/dist/jsx-runtime.js.map +1 -0
  46. package/dist/legacy.d.ts +3 -0
  47. package/dist/legacy.d.ts.map +1 -0
  48. package/dist/legacy.js +3 -0
  49. package/dist/legacy.js.map +1 -0
  50. package/dist/mun.d.ts +5 -0
  51. package/dist/mun.d.ts.map +1 -0
  52. package/dist/mun.js +4 -0
  53. package/dist/mun.js.map +1 -0
  54. package/dist/progressive-blur/index.d.ts +8 -0
  55. package/dist/progressive-blur/index.d.ts.map +1 -0
  56. package/dist/progressive-blur/index.js +8 -0
  57. package/dist/progressive-blur/index.js.map +1 -0
  58. package/dist/progressive-blur/plan.d.ts +3 -0
  59. package/dist/progressive-blur/plan.d.ts.map +1 -0
  60. package/dist/progressive-blur/plan.js +3 -0
  61. package/dist/progressive-blur/plan.js.map +1 -0
  62. package/dist/react-types.d.ts +2 -0
  63. package/dist/react-types.d.ts.map +1 -0
  64. package/dist/react-types.js +2 -0
  65. package/dist/react-types.js.map +1 -0
  66. package/dist/rendering-quality.d.ts +4 -0
  67. package/dist/rendering-quality.d.ts.map +1 -0
  68. package/dist/rendering-quality.js +4 -0
  69. package/dist/rendering-quality.js.map +1 -0
  70. package/dist/state.d.ts +2 -0
  71. package/dist/state.d.ts.map +1 -0
  72. package/dist/state.js +2 -0
  73. package/dist/state.js.map +1 -0
  74. package/dist/types.d.ts +2 -0
  75. package/dist/types.d.ts.map +1 -0
  76. package/dist/types.js +2 -0
  77. package/dist/types.js.map +1 -0
  78. package/dist/vite.d.ts +2 -0
  79. package/dist/vite.d.ts.map +1 -0
  80. package/dist/vite.js +2 -0
  81. package/dist/vite.js.map +1 -0
  82. package/editors/install.mjs +102 -0
  83. package/editors/lsp/mun-lsp.mjs +123 -0
  84. package/editors/lsp/service.mjs +306 -0
  85. package/editors/lsp/source.mjs +58 -0
  86. package/editors/vscode/client.mjs +40 -0
  87. package/editors/vscode/dev-client.mjs +83 -0
  88. package/editors/vscode/discovery.mjs +46 -0
  89. package/editors/vscode/export.mjs +42 -0
  90. package/editors/vscode/extension.cjs +226 -0
  91. package/editors/vscode/language-configuration.json +15 -0
  92. package/editors/vscode/package.json +119 -0
  93. package/editors/vscode/protocol.mjs +29 -0
  94. package/editors/vscode/syntaxes/mun.tmLanguage.json +130 -0
  95. package/native/Cargo.lock +3581 -0
  96. package/native/Cargo.toml +21 -0
  97. package/native/README.md +21 -0
  98. package/native/mun-native/Cargo.toml +23 -0
  99. package/native/mun-native/src/accessibility.rs +738 -0
  100. package/native/mun-native/src/dev.rs +604 -0
  101. package/native/mun-native/src/lib.rs +2676 -0
  102. package/native/mun-native/src/main.rs +204 -0
  103. package/native/mun-native/src/offscreen.rs +393 -0
  104. package/native/mun-native/src/rect.wgsl +63 -0
  105. package/native/mun-native/src/text.rs +310 -0
  106. package/native/mun-native/tests/offscreen_rendering.rs +161 -0
  107. package/native/mun-native/tests/stress.rs +408 -0
  108. package/native/mun-native/tests/window_lifecycle.rs +183 -0
  109. package/native/mun-runtime/Cargo.toml +13 -0
  110. package/native/mun-runtime/src/accessibility.rs +193 -0
  111. package/native/mun-runtime/src/collection.rs +1073 -0
  112. package/native/mun-runtime/src/gesture.rs +1070 -0
  113. package/native/mun-runtime/src/input.rs +325 -0
  114. package/native/mun-runtime/src/ir.rs +782 -0
  115. package/native/mun-runtime/src/kinetics.rs +500 -0
  116. package/native/mun-runtime/src/layout.rs +173 -0
  117. package/native/mun-runtime/src/layout_cache.rs +209 -0
  118. package/native/mun-runtime/src/lib.rs +49 -0
  119. package/native/mun-runtime/src/motion.rs +1162 -0
  120. package/native/mun-runtime/src/retained.rs +574 -0
  121. package/native/mun-runtime/src/runtime.rs +7078 -0
  122. package/native/mun-runtime/src/scene.rs +530 -0
  123. package/native/mun-runtime/src/scroll.rs +521 -0
  124. package/native/mun-runtime/src/scroll_view.rs +220 -0
  125. package/native/mun-runtime/src/text_edit.rs +670 -0
  126. package/native/mun-runtime/src/timeline.rs +1534 -0
  127. package/native/mun-runtime/src/validate.rs +677 -0
  128. package/native/mun-runtime/tests/accessibility_semantics.rs +168 -0
  129. package/native/mun-runtime/tests/compiler_contract.rs +110 -0
  130. package/native/mun-runtime/tests/flexible_frames.rs +47 -0
  131. package/native/mun-runtime/tests/hot_update.rs +367 -0
  132. package/native/mun-runtime/tests/incremental_runtime.rs +323 -0
  133. package/native/mun-runtime/tests/ir_validation.rs +167 -0
  134. package/native/mun-runtime/tests/keyed_collections.rs +251 -0
  135. package/native/mun-runtime/tests/native_controls_style.rs +491 -0
  136. package/native/mun-runtime/tests/native_demo.rs +285 -0
  137. package/native/mun-runtime/tests/native_layout_style.rs +175 -0
  138. package/native/mun-runtime/tests/native_settings_pane.rs +152 -0
  139. package/native/mun-runtime/tests/scroll_view.rs +403 -0
  140. package/native/mun-runtime/tests/text_editing.rs +491 -0
  141. package/package.json +210 -3
  142. package/schemas/README.md +19 -0
  143. package/schemas/semantic-ui-ir-v1.schema.json +1972 -0
  144. package/templates/native/App.mun +15 -0
  145. package/templates/native/gitignore +3 -0
  146. package/templates/native/mun.toml +8 -0
  147. package/templates/project/gitignore +5 -0
  148. package/templates/project/index.html +13 -0
  149. package/templates/project/package.json +21 -0
  150. package/templates/project/src/App.mun +13 -0
  151. package/templates/project/src/index.css +21 -0
  152. package/templates/project/src/main.ts +5 -0
  153. package/templates/project/tsconfig.json +20 -0
  154. package/templates/project/vite.config.ts +6 -0
  155. package/templates/vite/src/App.css +134 -0
  156. package/templates/vite/src/App.tsx +91 -0
  157. package/templates/vite/src/index.css +23 -0
  158. package/templates/vite/vite.config.ts +10 -0
@@ -0,0 +1,1534 @@
1
+ //! Renderer-neutral playback clock ported from the existing Mün runtime's `TimelinePlayer`.
2
+ //!
3
+ //! This module owns renderer-neutral time/iteration/direction mapping plus the
4
+ //! first scalar numeric keyframe execution primitive. It does not know about
5
+ //! scene nodes, layout, wgpu, or platform widgets, so future timeline bindings
6
+ //! can reuse these contracts without redefining repeat, seek, or reverse semantics.
7
+
8
+ use std::{error::Error, fmt};
9
+
10
+ const EPSILON: f64 = 1e-9;
11
+
12
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
13
+ pub enum TimelineDirection {
14
+ Normal,
15
+ Reverse,
16
+ Alternate,
17
+ AlternateReverse,
18
+ }
19
+
20
+ #[derive(Clone, Copy, Debug, PartialEq)]
21
+ pub struct TimelineMapping {
22
+ pub iteration: u64,
23
+ pub local_time: f64,
24
+ pub sign: f64,
25
+ }
26
+
27
+ #[derive(Clone, Copy, Debug, PartialEq)]
28
+ pub struct TimelineClock {
29
+ duration: f64,
30
+ iterations: Option<u64>,
31
+ direction: TimelineDirection,
32
+ elapsed_time: f64,
33
+ playback_rate: f64,
34
+ }
35
+
36
+ impl TimelineClock {
37
+ pub fn new(duration: f64, iterations: Option<u64>, direction: TimelineDirection) -> Self {
38
+ assert!(
39
+ duration.is_finite() && duration >= 0.0,
40
+ "timeline duration must be finite and non-negative"
41
+ );
42
+ if let Some(iterations) = iterations {
43
+ assert!(iterations >= 1, "timeline iterations must be at least one");
44
+ }
45
+ Self {
46
+ duration,
47
+ iterations,
48
+ direction,
49
+ elapsed_time: 0.0,
50
+ playback_rate: 1.0,
51
+ }
52
+ }
53
+
54
+ pub fn duration(&self) -> f64 {
55
+ self.duration
56
+ }
57
+
58
+ pub fn elapsed_time(&self) -> f64 {
59
+ self.elapsed_time
60
+ }
61
+
62
+ pub fn playback_rate(&self) -> f64 {
63
+ self.playback_rate
64
+ }
65
+
66
+ pub fn set_playback_rate(&mut self, rate: f64) {
67
+ assert!(rate.is_finite(), "timeline playback rate must be finite");
68
+ self.playback_rate = rate;
69
+ }
70
+
71
+ pub fn reverse(&mut self) {
72
+ self.playback_rate = if self.playback_rate == 0.0 {
73
+ -1.0
74
+ } else {
75
+ -self.playback_rate
76
+ };
77
+ }
78
+
79
+ pub fn total_duration(&self) -> Option<f64> {
80
+ self.iterations
81
+ .map(|iterations| self.duration * iterations as f64)
82
+ }
83
+
84
+ /// Prevent future repeat cycles while allowing the currently sampled cycle
85
+ /// to finish. This matches the existing Mün runtime's generation-based delayed-retarget handoff:
86
+ /// the in-flight control keeps running, but its repeat wrapper is superseded.
87
+ pub fn stop_after_current_iteration(&mut self) {
88
+ let current = self.current_mapping().iteration;
89
+ self.iterations = Some(current.saturating_add(1));
90
+ }
91
+
92
+ pub fn mapping(&self, raw_time: f64, traversal: f64) -> TimelineMapping {
93
+ map_time(
94
+ self.duration,
95
+ self.iterations,
96
+ self.direction,
97
+ raw_time,
98
+ traversal,
99
+ )
100
+ }
101
+
102
+ pub fn current_mapping(&self) -> TimelineMapping {
103
+ self.mapping(self.elapsed_time, self.playback_rate)
104
+ }
105
+
106
+ /// Seek by timeline-local time within an iteration, preserving the existing Mün runtime's
107
+ /// direction-aware raw-time mapping.
108
+ pub fn seek(&mut self, local_time: f64, iteration: u64) -> TimelineMapping {
109
+ if self.duration <= EPSILON {
110
+ self.elapsed_time = 0.0;
111
+ return self.current_mapping();
112
+ }
113
+ let resolved_iteration = match self.iterations {
114
+ Some(iterations) => iteration.min(iterations - 1),
115
+ None => iteration,
116
+ };
117
+ let local = local_time.clamp(0.0, self.duration);
118
+ let sign = direction_sign(self.direction, resolved_iteration);
119
+ let raw_phase = if sign > 0.0 {
120
+ local
121
+ } else {
122
+ self.duration - local
123
+ };
124
+ self.elapsed_time = resolved_iteration as f64 * self.duration + raw_phase;
125
+ self.mapping(self.elapsed_time, 0.0)
126
+ }
127
+
128
+ pub fn seek_progress(&mut self, progress: f64, iteration: u64) -> TimelineMapping {
129
+ self.seek(progress.clamp(0.0, 1.0) * self.duration, iteration)
130
+ }
131
+
132
+ pub fn seek_elapsed(&mut self, elapsed: f64) -> TimelineMapping {
133
+ let mut raw = elapsed.max(0.0);
134
+ if let Some(total) = self.total_duration() {
135
+ raw = raw.min(total);
136
+ }
137
+ self.elapsed_time = raw;
138
+ self.mapping(raw, 0.0)
139
+ }
140
+
141
+ /// Advance the clock in O(1), including across arbitrarily many repeats.
142
+ /// Returns the sampled mapping, number of crossed iteration boundaries, and
143
+ /// whether finite playback reached an endpoint.
144
+ pub fn step(&mut self, dt_seconds: f64) -> TimelineStep {
145
+ let previous = self.current_mapping();
146
+ if !dt_seconds.is_finite() || dt_seconds <= 0.0 || self.playback_rate == 0.0 {
147
+ return TimelineStep {
148
+ mapping: previous,
149
+ crossed_iterations: 0,
150
+ finished: false,
151
+ };
152
+ }
153
+ if self.duration <= EPSILON {
154
+ return TimelineStep {
155
+ mapping: previous,
156
+ crossed_iterations: 0,
157
+ finished: true,
158
+ };
159
+ }
160
+
161
+ let mut next = self.elapsed_time + dt_seconds * self.playback_rate;
162
+ let mut finished = false;
163
+ if let Some(total) = self.total_duration() {
164
+ if self.playback_rate > 0.0 && next >= total - EPSILON {
165
+ next = total;
166
+ finished = true;
167
+ } else if self.playback_rate < 0.0 && next <= EPSILON {
168
+ next = 0.0;
169
+ finished = true;
170
+ }
171
+ } else if self.playback_rate < 0.0 && next <= EPSILON {
172
+ next = 0.0;
173
+ finished = true;
174
+ }
175
+ if next < 0.0 {
176
+ next = 0.0;
177
+ }
178
+
179
+ self.elapsed_time = next;
180
+ let mapping = self.mapping(next, self.playback_rate);
181
+ let crossed_iterations = mapping.iteration as i64 - previous.iteration as i64;
182
+ TimelineStep {
183
+ mapping,
184
+ crossed_iterations,
185
+ finished,
186
+ }
187
+ }
188
+ }
189
+
190
+ #[derive(Clone, Copy, Debug, PartialEq)]
191
+ pub struct TimelineStep {
192
+ pub mapping: TimelineMapping,
193
+ /// Signed count, matching the existing Mün runtime's `onRepeat(iteration, player, crossed)`.
194
+ pub crossed_iterations: i64,
195
+ pub finished: bool,
196
+ }
197
+
198
+ pub fn direction_sign(direction: TimelineDirection, iteration: u64) -> f64 {
199
+ match direction {
200
+ TimelineDirection::Reverse => -1.0,
201
+ TimelineDirection::Alternate => {
202
+ if iteration % 2 == 0 {
203
+ 1.0
204
+ } else {
205
+ -1.0
206
+ }
207
+ }
208
+ TimelineDirection::AlternateReverse => {
209
+ if iteration % 2 == 0 {
210
+ -1.0
211
+ } else {
212
+ 1.0
213
+ }
214
+ }
215
+ TimelineDirection::Normal => 1.0,
216
+ }
217
+ }
218
+
219
+ pub fn map_time(
220
+ duration: f64,
221
+ iterations: Option<u64>,
222
+ direction: TimelineDirection,
223
+ raw_time: f64,
224
+ traversal: f64,
225
+ ) -> TimelineMapping {
226
+ if duration <= EPSILON {
227
+ return TimelineMapping {
228
+ iteration: 0,
229
+ local_time: 0.0,
230
+ sign: 1.0,
231
+ };
232
+ }
233
+
234
+ let total = iterations.map(|iterations| duration * iterations as f64);
235
+ let mut raw = raw_time.max(0.0);
236
+ if let Some(total) = total {
237
+ raw = raw.min(total);
238
+ }
239
+
240
+ let (iteration, phase) = if total.is_some_and(|total| raw >= total - EPSILON) {
241
+ let iterations = iterations.expect("finite total requires finite iterations");
242
+ (iterations.saturating_sub(1), duration)
243
+ } else {
244
+ let boundary = (raw / duration).round();
245
+ let on_boundary = raw > 0.0 && (raw - boundary * duration).abs() <= EPSILON;
246
+ if traversal < 0.0 && on_boundary {
247
+ (boundary.max(1.0) as u64 - 1, duration)
248
+ } else {
249
+ let iteration = (raw / duration).floor().max(0.0) as u64;
250
+ (iteration, raw - iteration as f64 * duration)
251
+ }
252
+ };
253
+
254
+ let sign = direction_sign(direction, iteration);
255
+ let local_time = if sign > 0.0 { phase } else { duration - phase };
256
+ TimelineMapping {
257
+ iteration,
258
+ local_time: local_time.clamp(0.0, duration),
259
+ sign,
260
+ }
261
+ }
262
+
263
+ const EASING_LUT_SIZE: usize = 256;
264
+
265
+ #[derive(Clone, Copy, Debug, PartialEq)]
266
+ pub enum TimelineEasing {
267
+ Linear,
268
+ CubicBezier([f64; 4]),
269
+ }
270
+
271
+ impl Default for TimelineEasing {
272
+ fn default() -> Self {
273
+ Self::Linear
274
+ }
275
+ }
276
+
277
+ #[derive(Clone, Copy, Debug, PartialEq)]
278
+ pub struct ScalarKeyframe {
279
+ pub at: f64,
280
+ pub value: f64,
281
+ /// Segment easing beginning at this frame. The final frame's easing is
282
+ /// ignored, matching the inherited `Timeline` numeric keyframe track.
283
+ pub easing: TimelineEasing,
284
+ }
285
+
286
+ impl ScalarKeyframe {
287
+ pub fn linear(at: f64, value: f64) -> Self {
288
+ Self {
289
+ at,
290
+ value,
291
+ easing: TimelineEasing::Linear,
292
+ }
293
+ }
294
+ }
295
+
296
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
297
+ pub enum TimelineTrackError {
298
+ Empty,
299
+ NonFiniteTime,
300
+ NegativeTime,
301
+ NonFiniteValue,
302
+ NonFiniteDuration,
303
+ NonFiniteEasing,
304
+ }
305
+
306
+ impl fmt::Display for TimelineTrackError {
307
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308
+ let message = match self {
309
+ Self::Empty => "timeline track requires at least one keyframe",
310
+ Self::NonFiniteTime => "keyframe time must be finite",
311
+ Self::NegativeTime => "keyframe time cannot be negative",
312
+ Self::NonFiniteValue => "numeric keyframes require finite values",
313
+ Self::NonFiniteDuration => "shorthand keyframes require a finite non-negative duration",
314
+ Self::NonFiniteEasing => "timeline easing control points must be finite",
315
+ };
316
+ f.write_str(message)
317
+ }
318
+ }
319
+
320
+ impl Error for TimelineTrackError {}
321
+
322
+ #[derive(Clone, Copy, Debug, PartialEq)]
323
+ pub struct TimelineValueSample {
324
+ pub value: f64,
325
+ pub velocity: f64,
326
+ }
327
+
328
+ #[derive(Clone, Debug, PartialEq)]
329
+ enum CompiledTimelineEasing {
330
+ Linear,
331
+ Lut(Box<[f64]>),
332
+ }
333
+
334
+ #[derive(Clone, Debug, PartialEq)]
335
+ pub struct ScalarKeyframeTrack {
336
+ frames: Vec<ScalarKeyframe>,
337
+ easings: Vec<CompiledTimelineEasing>,
338
+ duration: f64,
339
+ }
340
+
341
+ impl ScalarKeyframeTrack {
342
+ /// Stable-sort numeric keyframes by time and let the later authored frame
343
+ /// win when two frames land within the inherited timeline epsilon.
344
+ pub fn new(frames: Vec<ScalarKeyframe>) -> Result<Self, TimelineTrackError> {
345
+ if frames.is_empty() {
346
+ return Err(TimelineTrackError::Empty);
347
+ }
348
+
349
+ let mut ordered = Vec::with_capacity(frames.len());
350
+ for (order, frame) in frames.into_iter().enumerate() {
351
+ validate_frame(frame)?;
352
+ ordered.push((order, frame));
353
+ }
354
+ ordered.sort_by(|(left_order, left), (right_order, right)| {
355
+ left.at
356
+ .total_cmp(&right.at)
357
+ .then_with(|| left_order.cmp(right_order))
358
+ });
359
+
360
+ let mut normalized: Vec<ScalarKeyframe> = Vec::with_capacity(ordered.len());
361
+ for (_, frame) in ordered {
362
+ if let Some(last) = normalized.last_mut() {
363
+ if (last.at - frame.at).abs() <= EPSILON {
364
+ *last = frame;
365
+ continue;
366
+ }
367
+ }
368
+ normalized.push(frame);
369
+ }
370
+
371
+ let mut easings = Vec::with_capacity(normalized.len().saturating_sub(1));
372
+ for frame in normalized.iter().take(normalized.len().saturating_sub(1)) {
373
+ easings.push(compile_timeline_easing(frame.easing)?);
374
+ }
375
+ let duration = normalized.last().expect("non-empty after normalization").at;
376
+ Ok(Self {
377
+ frames: normalized,
378
+ easings,
379
+ duration,
380
+ })
381
+ }
382
+
383
+ /// Legacy shorthand form: evenly distribute scalar values across duration.
384
+ pub fn from_values(
385
+ values: &[f64],
386
+ duration: f64,
387
+ easing: TimelineEasing,
388
+ ) -> Result<Self, TimelineTrackError> {
389
+ if values.is_empty() {
390
+ return Err(TimelineTrackError::Empty);
391
+ }
392
+ if !duration.is_finite() || duration < 0.0 {
393
+ return Err(TimelineTrackError::NonFiniteDuration);
394
+ }
395
+ let denominator = values.len().saturating_sub(1).max(1) as f64;
396
+ let frames = values
397
+ .iter()
398
+ .enumerate()
399
+ .map(|(index, value)| ScalarKeyframe {
400
+ at: duration * index as f64 / denominator,
401
+ value: *value,
402
+ easing,
403
+ })
404
+ .collect();
405
+ Self::new(frames)
406
+ }
407
+
408
+ pub fn duration(&self) -> f64 {
409
+ self.duration
410
+ }
411
+
412
+ pub fn keyframes(&self) -> &[ScalarKeyframe] {
413
+ &self.frames
414
+ }
415
+
416
+ /// Sample renderer-neutral scalar presentation state. `velocity_scale` is
417
+ /// supplied by `TimelineClock` as direction-sign times playback-rate during
418
+ /// playback, or zero while seeking/scrubbing.
419
+ pub fn sample(&self, time: f64, velocity_scale: f64) -> TimelineValueSample {
420
+ let time = if time.is_finite() {
421
+ time.clamp(0.0, self.duration)
422
+ } else {
423
+ 0.0
424
+ };
425
+ let velocity_scale = if velocity_scale.is_finite() {
426
+ velocity_scale
427
+ } else {
428
+ 0.0
429
+ };
430
+
431
+ let count = self.frames.len();
432
+ if count == 1 || time <= self.frames[0].at {
433
+ return TimelineValueSample {
434
+ value: self.frames[0].value,
435
+ velocity: 0.0,
436
+ };
437
+ }
438
+
439
+ let last = count - 1;
440
+ if time >= self.frames[last].at {
441
+ return TimelineValueSample {
442
+ value: self.frames[last].value,
443
+ velocity: 0.0,
444
+ };
445
+ }
446
+
447
+ let index = self
448
+ .frames
449
+ .partition_point(|frame| frame.at <= time)
450
+ .saturating_sub(1)
451
+ .min(last - 1);
452
+ let start = self.frames[index];
453
+ let end = self.frames[index + 1];
454
+ let span = end.at - start.at;
455
+ if span <= EPSILON {
456
+ return TimelineValueSample {
457
+ value: end.value,
458
+ velocity: 0.0,
459
+ };
460
+ }
461
+
462
+ let progress = (time - start.at) / span;
463
+ let easing = &self.easings[index];
464
+ let eased = evaluate_compiled_timeline_easing(easing, progress);
465
+ let delta = end.value - start.value;
466
+ TimelineValueSample {
467
+ value: start.value + delta * eased,
468
+ velocity: if velocity_scale == 0.0 {
469
+ 0.0
470
+ } else {
471
+ delta * derivative_compiled_timeline_easing(easing, progress) / span
472
+ * velocity_scale
473
+ },
474
+ }
475
+ }
476
+ }
477
+
478
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
479
+ pub enum TimelineFill {
480
+ None,
481
+ Forwards,
482
+ Backwards,
483
+ Both,
484
+ }
485
+
486
+ impl TimelineFill {
487
+ fn fills_before(self) -> bool {
488
+ matches!(self, Self::Backwards | Self::Both)
489
+ }
490
+
491
+ fn fills_after(self) -> bool {
492
+ matches!(self, Self::Forwards | Self::Both)
493
+ }
494
+ }
495
+
496
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
497
+ pub enum TimelineClipError {
498
+ NonFiniteStart,
499
+ NegativeStart,
500
+ NonFiniteSpeed,
501
+ NonPositiveSpeed,
502
+ NonFiniteChildDuration,
503
+ NegativeChildDuration,
504
+ }
505
+
506
+ impl fmt::Display for TimelineClipError {
507
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508
+ let message = match self {
509
+ Self::NonFiniteStart => "timeline clip start must be finite",
510
+ Self::NegativeStart => "timeline clip start cannot be negative",
511
+ Self::NonFiniteSpeed => "timeline clip speed must be finite",
512
+ Self::NonPositiveSpeed => "timeline clip speed must be greater than zero",
513
+ Self::NonFiniteChildDuration => "timeline clip child duration must be finite",
514
+ Self::NegativeChildDuration => "timeline clip child duration cannot be negative",
515
+ };
516
+ f.write_str(message)
517
+ }
518
+ }
519
+
520
+ impl Error for TimelineClipError {}
521
+
522
+ #[derive(Clone, Copy, Debug, PartialEq)]
523
+ pub struct TimelineClipSample {
524
+ pub child_time: f64,
525
+ pub velocity_scale: f64,
526
+ }
527
+
528
+ /// Renderer-neutral parent-to-child time mapping recovered from inherited
529
+ /// `TimelineClip` semantics. Target ownership and child track storage remain
530
+ /// separate; this type only decides whether/where a child timeline samples.
531
+ #[derive(Clone, Copy, Debug, PartialEq)]
532
+ pub struct TimelineClipTiming {
533
+ at: f64,
534
+ speed: f64,
535
+ fill: TimelineFill,
536
+ child_duration: f64,
537
+ }
538
+
539
+ impl TimelineClipTiming {
540
+ pub fn new(
541
+ at: f64,
542
+ speed: f64,
543
+ fill: TimelineFill,
544
+ child_duration: f64,
545
+ ) -> Result<Self, TimelineClipError> {
546
+ if !at.is_finite() {
547
+ return Err(TimelineClipError::NonFiniteStart);
548
+ }
549
+ if at < 0.0 {
550
+ return Err(TimelineClipError::NegativeStart);
551
+ }
552
+ if !speed.is_finite() {
553
+ return Err(TimelineClipError::NonFiniteSpeed);
554
+ }
555
+ if speed <= 0.0 {
556
+ return Err(TimelineClipError::NonPositiveSpeed);
557
+ }
558
+ if !child_duration.is_finite() {
559
+ return Err(TimelineClipError::NonFiniteChildDuration);
560
+ }
561
+ if child_duration < 0.0 {
562
+ return Err(TimelineClipError::NegativeChildDuration);
563
+ }
564
+
565
+ Ok(Self {
566
+ at,
567
+ speed,
568
+ fill,
569
+ child_duration,
570
+ })
571
+ }
572
+
573
+ pub fn at(&self) -> f64 {
574
+ self.at
575
+ }
576
+
577
+ pub fn speed(&self) -> f64 {
578
+ self.speed
579
+ }
580
+
581
+ pub fn fill(&self) -> TimelineFill {
582
+ self.fill
583
+ }
584
+
585
+ pub fn child_duration(&self) -> f64 {
586
+ self.child_duration
587
+ }
588
+
589
+ pub fn duration(&self) -> f64 {
590
+ self.child_duration / self.speed
591
+ }
592
+
593
+ pub fn end(&self) -> f64 {
594
+ self.at + self.duration()
595
+ }
596
+
597
+ /// Map parent timeline time into the child timeline.
598
+ ///
599
+ /// Fill samples clamp to the child endpoint with zero velocity. Active
600
+ /// samples scale both child time and inherited real-time velocity by
601
+ /// `speed`, exactly matching the existing timeline runtime.
602
+ pub fn map(&self, parent_time: f64, velocity_scale: f64) -> Option<TimelineClipSample> {
603
+ let parent_time = if parent_time.is_finite() {
604
+ parent_time
605
+ } else {
606
+ 0.0
607
+ };
608
+ let velocity_scale = if velocity_scale.is_finite() {
609
+ velocity_scale
610
+ } else {
611
+ 0.0
612
+ };
613
+
614
+ if parent_time < self.at {
615
+ return self.fill.fills_before().then_some(TimelineClipSample {
616
+ child_time: 0.0,
617
+ velocity_scale: 0.0,
618
+ });
619
+ }
620
+
621
+ let end = self.end();
622
+ if parent_time > end {
623
+ return self.fill.fills_after().then_some(TimelineClipSample {
624
+ child_time: self.child_duration,
625
+ velocity_scale: 0.0,
626
+ });
627
+ }
628
+
629
+ Some(TimelineClipSample {
630
+ child_time: ((parent_time - self.at) * self.speed).clamp(0.0, self.child_duration),
631
+ velocity_scale: velocity_scale * self.speed,
632
+ })
633
+ }
634
+ }
635
+
636
+ #[derive(Clone, Copy, Debug, PartialEq)]
637
+ pub struct ScalarTimelineStep {
638
+ pub mapping: TimelineMapping,
639
+ pub sample: TimelineValueSample,
640
+ pub crossed_iterations: i64,
641
+ pub finished: bool,
642
+ }
643
+
644
+ /// Runtime execution primitive for one inherited numeric keyframe track.
645
+ ///
646
+ /// It deliberately reuses `TimelineClock` for repeat/direction/seek/reverse
647
+ /// semantics. It does not create a second wall clock and does not claim the
648
+ /// source-facing `Timeline`/`PhaseTimeline` API yet.
649
+ #[derive(Clone, Debug, PartialEq)]
650
+ pub struct ScalarTimelinePlayer {
651
+ track: ScalarKeyframeTrack,
652
+ clock: TimelineClock,
653
+ sample: TimelineValueSample,
654
+ }
655
+
656
+ impl ScalarTimelinePlayer {
657
+ pub fn new(
658
+ track: ScalarKeyframeTrack,
659
+ iterations: Option<u64>,
660
+ direction: TimelineDirection,
661
+ ) -> Self {
662
+ let clock = TimelineClock::new(track.duration(), iterations, direction);
663
+ let mapping = clock.current_mapping();
664
+ let sample = track.sample(mapping.local_time, 0.0);
665
+ Self {
666
+ track,
667
+ clock,
668
+ sample,
669
+ }
670
+ }
671
+
672
+ pub fn track(&self) -> &ScalarKeyframeTrack {
673
+ &self.track
674
+ }
675
+
676
+ pub fn clock(&self) -> &TimelineClock {
677
+ &self.clock
678
+ }
679
+
680
+ pub fn current_sample(&self) -> TimelineValueSample {
681
+ self.sample
682
+ }
683
+
684
+ pub fn current_mapping(&self) -> TimelineMapping {
685
+ self.clock.current_mapping()
686
+ }
687
+
688
+ pub fn set_playback_rate(&mut self, rate: f64) {
689
+ self.clock.set_playback_rate(rate);
690
+ }
691
+
692
+ pub fn reverse(&mut self) {
693
+ self.clock.reverse();
694
+ }
695
+
696
+ pub fn seek(&mut self, local_time: f64, iteration: u64) -> TimelineValueSample {
697
+ let mapping = self.clock.seek(local_time, iteration);
698
+ self.sample = self.track.sample(mapping.local_time, 0.0);
699
+ self.sample
700
+ }
701
+
702
+ pub fn seek_progress(&mut self, progress: f64, iteration: u64) -> TimelineValueSample {
703
+ let mapping = self.clock.seek_progress(progress, iteration);
704
+ self.sample = self.track.sample(mapping.local_time, 0.0);
705
+ self.sample
706
+ }
707
+
708
+ pub fn seek_elapsed(&mut self, elapsed: f64) -> TimelineValueSample {
709
+ let mapping = self.clock.seek_elapsed(elapsed);
710
+ self.sample = self.track.sample(mapping.local_time, 0.0);
711
+ self.sample
712
+ }
713
+
714
+ pub fn step(&mut self, dt_seconds: f64) -> ScalarTimelineStep {
715
+ if !dt_seconds.is_finite() || dt_seconds <= 0.0 || self.clock.playback_rate() == 0.0 {
716
+ return ScalarTimelineStep {
717
+ mapping: self.clock.current_mapping(),
718
+ sample: self.sample,
719
+ crossed_iterations: 0,
720
+ finished: false,
721
+ };
722
+ }
723
+
724
+ let step = self.clock.step(dt_seconds);
725
+ let velocity_scale = if step.finished {
726
+ 0.0
727
+ } else {
728
+ step.mapping.sign * self.clock.playback_rate()
729
+ };
730
+ self.sample = self.track.sample(step.mapping.local_time, velocity_scale);
731
+ ScalarTimelineStep {
732
+ mapping: step.mapping,
733
+ sample: self.sample,
734
+ crossed_iterations: step.crossed_iterations,
735
+ finished: step.finished,
736
+ }
737
+ }
738
+ }
739
+
740
+ #[derive(Clone, Debug, PartialEq)]
741
+ pub struct ScalarPhase {
742
+ pub name: String,
743
+ pub value: Option<f64>,
744
+ /// Time spent transitioning from the previous phase into this phase.
745
+ /// `None` uses the phase timeline's default duration.
746
+ pub duration: Option<f64>,
747
+ pub hold: f64,
748
+ /// Easing for the transition arriving at this phase.
749
+ pub easing: Option<TimelineEasing>,
750
+ }
751
+
752
+ impl ScalarPhase {
753
+ pub fn new(name: impl Into<String>, value: Option<f64>) -> Self {
754
+ Self {
755
+ name: name.into(),
756
+ value,
757
+ duration: None,
758
+ hold: 0.0,
759
+ easing: None,
760
+ }
761
+ }
762
+ }
763
+
764
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
765
+ pub enum PhaseTimelineError {
766
+ Empty,
767
+ NonFiniteDefaultDuration,
768
+ NegativeDefaultDuration,
769
+ MissingInitialValue,
770
+ NonFiniteTiming,
771
+ Track(TimelineTrackError),
772
+ }
773
+
774
+ impl fmt::Display for PhaseTimelineError {
775
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
776
+ let message = match self {
777
+ Self::Empty => "phase timeline requires at least one phase",
778
+ Self::NonFiniteDefaultDuration => "phase default duration must be finite",
779
+ Self::NegativeDefaultDuration => "phase default duration cannot be negative",
780
+ Self::MissingInitialValue => {
781
+ "initial phase requires a scalar value or an explicit initial fallback"
782
+ }
783
+ Self::NonFiniteTiming => "phase duration/hold produced a non-finite timeline time",
784
+ Self::Track(error) => return error.fmt(f),
785
+ };
786
+ f.write_str(message)
787
+ }
788
+ }
789
+
790
+ impl Error for PhaseTimelineError {
791
+ fn source(&self) -> Option<&(dyn Error + 'static)> {
792
+ match self {
793
+ Self::Track(error) => Some(error),
794
+ _ => None,
795
+ }
796
+ }
797
+ }
798
+
799
+ impl From<TimelineTrackError> for PhaseTimelineError {
800
+ fn from(value: TimelineTrackError) -> Self {
801
+ Self::Track(value)
802
+ }
803
+ }
804
+
805
+ /// Scalar renderer-neutral subset of the inherited `PhaseTimeline`.
806
+ ///
807
+ /// The source runtime supports multiple structured targets. This primitive
808
+ /// recovers only phase timing/choreography for one scalar channel and delegates
809
+ /// actual interpolation/playback to `ScalarKeyframeTrack`/`ScalarTimelinePlayer`.
810
+ /// Later phases may omit a value to hold the previous one. The first phase may
811
+ /// omit it only when an explicit runtime initial value is supplied.
812
+ #[derive(Clone, Debug, PartialEq)]
813
+ pub struct ScalarPhaseTimeline {
814
+ names: Vec<String>,
815
+ arrivals: Vec<f64>,
816
+ track: ScalarKeyframeTrack,
817
+ }
818
+
819
+ impl ScalarPhaseTimeline {
820
+ pub fn new(
821
+ initial_value: Option<f64>,
822
+ phases: Vec<ScalarPhase>,
823
+ ) -> Result<Self, PhaseTimelineError> {
824
+ Self::with_options(
825
+ initial_value,
826
+ phases,
827
+ 0.2,
828
+ TimelineEasing::CubicBezier([0.22, 1.0, 0.36, 1.0]),
829
+ )
830
+ }
831
+
832
+ pub fn with_options(
833
+ initial_value: Option<f64>,
834
+ phases: Vec<ScalarPhase>,
835
+ default_duration: f64,
836
+ default_easing: TimelineEasing,
837
+ ) -> Result<Self, PhaseTimelineError> {
838
+ if phases.is_empty() {
839
+ return Err(PhaseTimelineError::Empty);
840
+ }
841
+ if !default_duration.is_finite() {
842
+ return Err(PhaseTimelineError::NonFiniteDefaultDuration);
843
+ }
844
+ if default_duration < 0.0 {
845
+ return Err(PhaseTimelineError::NegativeDefaultDuration);
846
+ }
847
+ if let Some(initial) = initial_value {
848
+ if !initial.is_finite() {
849
+ return Err(PhaseTimelineError::Track(
850
+ TimelineTrackError::NonFiniteValue,
851
+ ));
852
+ }
853
+ }
854
+
855
+ let names = phases
856
+ .iter()
857
+ .map(|phase| phase.name.clone())
858
+ .collect::<Vec<_>>();
859
+ let mut arrivals = vec![0.0; phases.len()];
860
+ let mut current = phases[0]
861
+ .value
862
+ .or(initial_value)
863
+ .ok_or(PhaseTimelineError::MissingInitialValue)?;
864
+ let next_easing = phases
865
+ .get(1)
866
+ .and_then(|phase| phase.easing)
867
+ .unwrap_or(default_easing);
868
+ let mut frames = vec![ScalarKeyframe {
869
+ at: 0.0,
870
+ value: current,
871
+ easing: next_easing,
872
+ }];
873
+
874
+ let mut time = 0.0;
875
+ let first_hold = inherited_nonnegative_phase_time(phases[0].hold)?;
876
+ if first_hold > 0.0 {
877
+ time += first_hold;
878
+ if !time.is_finite() {
879
+ return Err(PhaseTimelineError::NonFiniteTiming);
880
+ }
881
+ frames.push(ScalarKeyframe {
882
+ at: time,
883
+ value: current,
884
+ easing: next_easing,
885
+ });
886
+ }
887
+
888
+ for index in 1..phases.len() {
889
+ let phase = &phases[index];
890
+ let transition = match phase.duration {
891
+ None => default_duration,
892
+ Some(duration) => inherited_nonnegative_phase_time(duration)?,
893
+ };
894
+ let phase_easing = phase.easing.unwrap_or(default_easing);
895
+ if let Some(last) = frames.last_mut() {
896
+ last.easing = phase_easing;
897
+ }
898
+
899
+ time += transition;
900
+ if !time.is_finite() {
901
+ return Err(PhaseTimelineError::NonFiniteTiming);
902
+ }
903
+ arrivals[index] = time;
904
+
905
+ if let Some(value) = phase.value {
906
+ current = value;
907
+ }
908
+ let following_easing = phases
909
+ .get(index + 1)
910
+ .and_then(|following| following.easing)
911
+ .unwrap_or(default_easing);
912
+ frames.push(ScalarKeyframe {
913
+ at: time,
914
+ value: current,
915
+ easing: following_easing,
916
+ });
917
+
918
+ let hold = inherited_nonnegative_phase_time(phase.hold)?;
919
+ if hold > 0.0 {
920
+ time += hold;
921
+ if !time.is_finite() {
922
+ return Err(PhaseTimelineError::NonFiniteTiming);
923
+ }
924
+ frames.push(ScalarKeyframe {
925
+ at: time,
926
+ value: current,
927
+ easing: following_easing,
928
+ });
929
+ }
930
+ }
931
+
932
+ Ok(Self {
933
+ names,
934
+ arrivals,
935
+ track: ScalarKeyframeTrack::new(frames)?,
936
+ })
937
+ }
938
+
939
+ pub fn names(&self) -> &[String] {
940
+ &self.names
941
+ }
942
+
943
+ pub fn arrivals(&self) -> &[f64] {
944
+ &self.arrivals
945
+ }
946
+
947
+ pub fn track(&self) -> &ScalarKeyframeTrack {
948
+ &self.track
949
+ }
950
+
951
+ pub fn duration(&self) -> f64 {
952
+ self.track.duration()
953
+ }
954
+
955
+ pub fn phase_at(&self, time_seconds: f64) -> &str {
956
+ let time = if time_seconds.is_nan() {
957
+ 0.0
958
+ } else {
959
+ time_seconds.clamp(0.0, self.duration())
960
+ };
961
+ let mut index = 0;
962
+ for arrival in self.arrivals.iter().skip(1) {
963
+ if *arrival <= time + EPSILON {
964
+ index += 1;
965
+ } else {
966
+ break;
967
+ }
968
+ }
969
+ &self.names[index]
970
+ }
971
+
972
+ pub fn sample(&self, time_seconds: f64, velocity_scale: f64) -> TimelineValueSample {
973
+ self.track.sample(time_seconds, velocity_scale)
974
+ }
975
+
976
+ pub fn player(
977
+ &self,
978
+ iterations: Option<u64>,
979
+ direction: TimelineDirection,
980
+ ) -> ScalarTimelinePlayer {
981
+ ScalarTimelinePlayer::new(self.track.clone(), iterations, direction)
982
+ }
983
+ }
984
+
985
+ fn inherited_nonnegative_phase_time(value: f64) -> Result<f64, PhaseTimelineError> {
986
+ if value.is_nan() || value <= 0.0 {
987
+ return Ok(0.0);
988
+ }
989
+ if !value.is_finite() {
990
+ return Err(PhaseTimelineError::NonFiniteTiming);
991
+ }
992
+ Ok(value)
993
+ }
994
+
995
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
996
+ pub enum StaggerOrigin {
997
+ First,
998
+ Last,
999
+ Center,
1000
+ Index(isize),
1001
+ }
1002
+
1003
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1004
+ pub enum StaggerError {
1005
+ NonFiniteInterval,
1006
+ NegativeInterval,
1007
+ NonFiniteStart,
1008
+ Easing(TimelineTrackError),
1009
+ }
1010
+
1011
+ impl fmt::Display for StaggerError {
1012
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013
+ let message = match self {
1014
+ Self::NonFiniteInterval => "stagger interval must be finite",
1015
+ Self::NegativeInterval => "stagger interval cannot be negative",
1016
+ Self::NonFiniteStart => "stagger start must be finite",
1017
+ Self::Easing(error) => return error.fmt(f),
1018
+ };
1019
+ f.write_str(message)
1020
+ }
1021
+ }
1022
+
1023
+ impl Error for StaggerError {
1024
+ fn source(&self) -> Option<&(dyn Error + 'static)> {
1025
+ match self {
1026
+ Self::Easing(error) => Some(error),
1027
+ _ => None,
1028
+ }
1029
+ }
1030
+ }
1031
+
1032
+ #[derive(Clone, Debug, PartialEq)]
1033
+ pub struct StaggerSchedule {
1034
+ interval: f64,
1035
+ start: f64,
1036
+ origin: StaggerOrigin,
1037
+ easing: Option<CompiledTimelineEasing>,
1038
+ }
1039
+
1040
+ impl StaggerSchedule {
1041
+ pub fn new(interval: f64) -> Result<Self, StaggerError> {
1042
+ Self::with_options(interval, 0.0, StaggerOrigin::First, None)
1043
+ }
1044
+
1045
+ pub fn with_options(
1046
+ interval: f64,
1047
+ start: f64,
1048
+ origin: StaggerOrigin,
1049
+ easing: Option<TimelineEasing>,
1050
+ ) -> Result<Self, StaggerError> {
1051
+ if !interval.is_finite() {
1052
+ return Err(StaggerError::NonFiniteInterval);
1053
+ }
1054
+ if interval < 0.0 {
1055
+ return Err(StaggerError::NegativeInterval);
1056
+ }
1057
+ if !start.is_finite() {
1058
+ return Err(StaggerError::NonFiniteStart);
1059
+ }
1060
+ let easing = easing
1061
+ .map(compile_timeline_easing)
1062
+ .transpose()
1063
+ .map_err(StaggerError::Easing)?;
1064
+
1065
+ Ok(Self {
1066
+ interval,
1067
+ start,
1068
+ origin,
1069
+ easing,
1070
+ })
1071
+ }
1072
+
1073
+ /// Resolve one item's delay from already-integer native collection
1074
+ /// coordinates. Index and numeric origin are clamped to the resolved item
1075
+ /// range, preserving the inherited stagger rank calculation.
1076
+ pub fn delay(&self, index: isize, total: usize) -> f64 {
1077
+ let count = total.max(1);
1078
+ let last = count - 1;
1079
+ let item = index.clamp(0, last as isize) as usize;
1080
+
1081
+ let rank = match self.origin {
1082
+ StaggerOrigin::First => item as f64,
1083
+ StaggerOrigin::Last => (last - item) as f64,
1084
+ StaggerOrigin::Center => (item as f64 - last as f64 / 2.0).abs(),
1085
+ StaggerOrigin::Index(origin) => {
1086
+ let origin = origin.clamp(0, last as isize) as usize;
1087
+ item.abs_diff(origin) as f64
1088
+ }
1089
+ };
1090
+
1091
+ let Some(easing) = &self.easing else {
1092
+ return self.start + rank * self.interval;
1093
+ };
1094
+ if count <= 1 {
1095
+ return self.start + rank * self.interval;
1096
+ }
1097
+
1098
+ let max_rank = if self.origin == StaggerOrigin::Center {
1099
+ (last as f64 / 2.0).max(0.5)
1100
+ } else {
1101
+ last as f64
1102
+ };
1103
+ let normalized = if max_rank <= EPSILON {
1104
+ 0.0
1105
+ } else {
1106
+ rank / max_rank
1107
+ };
1108
+ self.start
1109
+ + evaluate_compiled_timeline_easing(easing, normalized) * max_rank * self.interval
1110
+ }
1111
+ }
1112
+
1113
+ fn validate_frame(frame: ScalarKeyframe) -> Result<(), TimelineTrackError> {
1114
+ if !frame.at.is_finite() {
1115
+ return Err(TimelineTrackError::NonFiniteTime);
1116
+ }
1117
+ if frame.at < 0.0 {
1118
+ return Err(TimelineTrackError::NegativeTime);
1119
+ }
1120
+ if !frame.value.is_finite() {
1121
+ return Err(TimelineTrackError::NonFiniteValue);
1122
+ }
1123
+ Ok(())
1124
+ }
1125
+
1126
+ fn compile_timeline_easing(
1127
+ easing: TimelineEasing,
1128
+ ) -> Result<CompiledTimelineEasing, TimelineTrackError> {
1129
+ match easing {
1130
+ TimelineEasing::Linear => Ok(CompiledTimelineEasing::Linear),
1131
+ TimelineEasing::CubicBezier(curve) => {
1132
+ if curve.iter().any(|value| !value.is_finite()) {
1133
+ return Err(TimelineTrackError::NonFiniteEasing);
1134
+ }
1135
+ if curve[0] == curve[1] && curve[2] == curve[3] {
1136
+ return Ok(CompiledTimelineEasing::Linear);
1137
+ }
1138
+ let mut values = vec![0.0; EASING_LUT_SIZE + 1];
1139
+ for (index, value) in values.iter_mut().enumerate() {
1140
+ *value = evaluate_timeline_bezier(curve, index as f64 / EASING_LUT_SIZE as f64);
1141
+ }
1142
+ Ok(CompiledTimelineEasing::Lut(values.into_boxed_slice()))
1143
+ }
1144
+ }
1145
+ }
1146
+
1147
+ fn evaluate_compiled_timeline_easing(easing: &CompiledTimelineEasing, progress: f64) -> f64 {
1148
+ let progress = progress.clamp(0.0, 1.0);
1149
+ match easing {
1150
+ CompiledTimelineEasing::Linear => progress,
1151
+ CompiledTimelineEasing::Lut(values) => {
1152
+ let scaled = progress * EASING_LUT_SIZE as f64;
1153
+ let index = (scaled.floor() as usize).min(EASING_LUT_SIZE - 1);
1154
+ let fraction = scaled - index as f64;
1155
+ values[index] + (values[index + 1] - values[index]) * fraction
1156
+ }
1157
+ }
1158
+ }
1159
+
1160
+ fn derivative_compiled_timeline_easing(easing: &CompiledTimelineEasing, progress: f64) -> f64 {
1161
+ let progress = progress.clamp(0.0, 1.0);
1162
+ match easing {
1163
+ CompiledTimelineEasing::Linear => 1.0,
1164
+ CompiledTimelineEasing::Lut(values) => {
1165
+ let scaled = progress * EASING_LUT_SIZE as f64;
1166
+ let index = (scaled.floor() as usize).min(EASING_LUT_SIZE - 1);
1167
+ (values[index + 1] - values[index]) * EASING_LUT_SIZE as f64
1168
+ }
1169
+ }
1170
+ }
1171
+
1172
+ fn timeline_sample_curve(a1: f64, a2: f64, t: f64) -> f64 {
1173
+ let inverse = 1.0 - t;
1174
+ 3.0 * inverse * inverse * t * a1 + 3.0 * inverse * t * t * a2 + t * t * t
1175
+ }
1176
+
1177
+ fn timeline_sample_derivative(a1: f64, a2: f64, t: f64) -> f64 {
1178
+ 3.0 * (1.0 - t) * (1.0 - t) * a1 + 6.0 * (1.0 - t) * t * (a2 - a1) + 3.0 * t * t * (1.0 - a2)
1179
+ }
1180
+
1181
+ fn evaluate_timeline_bezier(curve: [f64; 4], progress: f64) -> f64 {
1182
+ let [x1, y1, x2, y2] = curve;
1183
+ let x = progress.clamp(0.0, 1.0);
1184
+ if x1 == y1 && x2 == y2 {
1185
+ return x;
1186
+ }
1187
+
1188
+ let mut t = x;
1189
+ for _ in 0..5 {
1190
+ let estimate = timeline_sample_curve(x1, x2, t) - x;
1191
+ let derivative = timeline_sample_derivative(x1, x2, t);
1192
+ if derivative.abs() < 1e-7 {
1193
+ break;
1194
+ }
1195
+ t = (t - estimate / derivative).clamp(0.0, 1.0);
1196
+ }
1197
+
1198
+ let mut low = 0.0;
1199
+ let mut high = 1.0;
1200
+ for _ in 0..8 {
1201
+ let estimate = timeline_sample_curve(x1, x2, t);
1202
+ if (estimate - x).abs() < 1e-6 {
1203
+ break;
1204
+ }
1205
+ if estimate < x {
1206
+ low = t;
1207
+ } else {
1208
+ high = t;
1209
+ }
1210
+ t = (low + high) * 0.5;
1211
+ }
1212
+
1213
+ timeline_sample_curve(y1, y2, t)
1214
+ }
1215
+
1216
+ #[cfg(test)]
1217
+ mod tests {
1218
+ use super::*;
1219
+
1220
+ #[test]
1221
+ fn alternate_iteration_boundary_matches_legacy_without_endpoint_jump() {
1222
+ let mut clock = TimelineClock::new(1.0, Some(2), TimelineDirection::Alternate);
1223
+ let first = clock.step(1.0);
1224
+ assert_eq!(first.mapping.iteration, 1);
1225
+ assert_eq!(first.mapping.local_time, 1.0);
1226
+ assert_eq!(first.mapping.sign, -1.0);
1227
+ assert_eq!(first.crossed_iterations, 1);
1228
+
1229
+ let middle = clock.step(0.5);
1230
+ assert!((middle.mapping.local_time - 0.5).abs() < 1e-12);
1231
+ let end = clock.step(0.5);
1232
+ assert_eq!(end.mapping.local_time, 0.0);
1233
+ assert!(end.finished);
1234
+ }
1235
+
1236
+ #[test]
1237
+ fn reverse_traversal_assigns_exact_boundary_to_previous_iteration() {
1238
+ let clock = TimelineClock::new(1.0, Some(4), TimelineDirection::Normal);
1239
+ let forward = clock.mapping(2.0, 1.0);
1240
+ assert_eq!(forward.iteration, 2);
1241
+ assert_eq!(forward.local_time, 0.0);
1242
+
1243
+ let backward = clock.mapping(2.0, -1.0);
1244
+ assert_eq!(backward.iteration, 1);
1245
+ assert_eq!(backward.local_time, 1.0);
1246
+ }
1247
+
1248
+ #[test]
1249
+ fn large_gap_crosses_repeats_in_constant_time() {
1250
+ let mut clock = TimelineClock::new(1.0, None, TimelineDirection::Normal);
1251
+ let step = clock.step(3_600.0);
1252
+ assert_eq!(step.mapping.iteration, 3600);
1253
+ assert_eq!(step.crossed_iterations, 3600);
1254
+ assert!(!step.finished);
1255
+ }
1256
+
1257
+ #[test]
1258
+ fn seek_and_reverse_match_legacy_time_mapping() {
1259
+ let mut clock = TimelineClock::new(1.0, Some(3), TimelineDirection::Alternate);
1260
+ let sought = clock.seek_progress(0.75, 1);
1261
+ assert_eq!(sought.iteration, 1);
1262
+ assert!((sought.local_time - 0.75).abs() < 1e-12);
1263
+
1264
+ clock.reverse();
1265
+ let stepped = clock.step(0.1);
1266
+ // Iteration 1 is already reversed by `alternate`; reversing playback
1267
+ // therefore traverses that reversed segment back toward its end.
1268
+ assert!(stepped.mapping.local_time > 0.75);
1269
+ assert_eq!(stepped.mapping.sign, -1.0);
1270
+ }
1271
+
1272
+ #[test]
1273
+ fn scalar_keyframes_stable_sort_and_collapse_duplicate_times_last_wins() {
1274
+ let track = ScalarKeyframeTrack::new(vec![
1275
+ ScalarKeyframe::linear(1.0, 100.0),
1276
+ ScalarKeyframe::linear(0.5, 40.0),
1277
+ ScalarKeyframe::linear(0.0, 0.0),
1278
+ ScalarKeyframe::linear(0.5, 60.0),
1279
+ ])
1280
+ .expect("valid keyframes");
1281
+
1282
+ assert_eq!(track.keyframes().len(), 3);
1283
+ assert_eq!(track.keyframes()[1].value, 60.0);
1284
+ assert_eq!(
1285
+ track.sample(0.5, 1.0),
1286
+ TimelineValueSample {
1287
+ value: 60.0,
1288
+ velocity: 80.0,
1289
+ }
1290
+ );
1291
+ }
1292
+
1293
+ #[test]
1294
+ fn scalar_keyframe_velocity_scales_with_playback_direction() {
1295
+ let track = ScalarKeyframeTrack::from_values(&[0.0, 100.0], 2.0, TimelineEasing::Linear)
1296
+ .expect("valid shorthand keyframes");
1297
+ let forward = track.sample(0.5, 1.0);
1298
+ assert!((forward.value - 25.0).abs() < 1e-12);
1299
+ assert!((forward.velocity - 50.0).abs() < 1e-12);
1300
+
1301
+ let reversed_fast = track.sample(0.5, -2.0);
1302
+ assert!((reversed_fast.value - 25.0).abs() < 1e-12);
1303
+ assert!((reversed_fast.velocity + 100.0).abs() < 1e-12);
1304
+ }
1305
+
1306
+ #[test]
1307
+ fn scalar_timeline_player_seek_and_reverse_reuse_clock_mapping() {
1308
+ let track = ScalarKeyframeTrack::from_values(&[0.0, 100.0], 1.0, TimelineEasing::Linear)
1309
+ .expect("valid timeline");
1310
+ let mut player = ScalarTimelinePlayer::new(track, Some(2), TimelineDirection::Alternate);
1311
+
1312
+ let sought = player.seek_progress(0.75, 1);
1313
+ assert!((sought.value - 75.0).abs() < 1e-12);
1314
+ assert_eq!(sought.velocity, 0.0);
1315
+
1316
+ player.reverse();
1317
+ let stepped = player.step(0.1);
1318
+ assert_eq!(stepped.mapping.iteration, 1);
1319
+ assert!(stepped.mapping.local_time > 0.75);
1320
+ assert!((stepped.sample.value - 85.0).abs() < 1e-12);
1321
+ assert!((stepped.sample.velocity - 100.0).abs() < 1e-12);
1322
+ }
1323
+
1324
+ #[test]
1325
+ fn scalar_timeline_finished_endpoint_zeroes_velocity() {
1326
+ let track = ScalarKeyframeTrack::new(vec![
1327
+ ScalarKeyframe {
1328
+ at: 0.0,
1329
+ value: 0.0,
1330
+ easing: TimelineEasing::CubicBezier([0.42, 0.0, 0.58, 1.0]),
1331
+ },
1332
+ ScalarKeyframe::linear(0.2, 10.0),
1333
+ ])
1334
+ .expect("valid eased timeline");
1335
+ let mut player = ScalarTimelinePlayer::new(track, Some(1), TimelineDirection::Normal);
1336
+
1337
+ let middle = player.step(0.1);
1338
+ assert!(middle.sample.value > 0.0 && middle.sample.value < 10.0);
1339
+ assert!(middle.sample.velocity > 0.0);
1340
+
1341
+ let end = player.step(0.1);
1342
+ assert!(end.finished);
1343
+ assert_eq!(end.sample.value, 10.0);
1344
+ assert_eq!(end.sample.velocity, 0.0);
1345
+ }
1346
+
1347
+ #[test]
1348
+ fn timeline_clip_maps_offset_speed_and_velocity_scale() {
1349
+ let clip = TimelineClipTiming::new(1.0, 2.0, TimelineFill::None, 2.0).expect("valid clip");
1350
+ assert_eq!(clip.duration(), 1.0);
1351
+ assert_eq!(clip.end(), 2.0);
1352
+
1353
+ assert_eq!(
1354
+ clip.map(1.25, 3.0),
1355
+ Some(TimelineClipSample {
1356
+ child_time: 0.5,
1357
+ velocity_scale: 6.0,
1358
+ })
1359
+ );
1360
+ assert_eq!(
1361
+ clip.map(2.0, -2.0),
1362
+ Some(TimelineClipSample {
1363
+ child_time: 2.0,
1364
+ velocity_scale: -4.0,
1365
+ })
1366
+ );
1367
+ }
1368
+
1369
+ #[test]
1370
+ fn timeline_clip_fill_applies_only_outside_active_interval() {
1371
+ let none = TimelineClipTiming::new(1.0, 1.0, TimelineFill::None, 1.0).expect("valid clip");
1372
+ assert_eq!(none.map(0.5, 4.0), None);
1373
+ assert_eq!(none.map(2.5, 4.0), None);
1374
+
1375
+ let backwards =
1376
+ TimelineClipTiming::new(1.0, 1.0, TimelineFill::Backwards, 1.0).expect("valid clip");
1377
+ assert_eq!(
1378
+ backwards.map(0.5, 4.0),
1379
+ Some(TimelineClipSample {
1380
+ child_time: 0.0,
1381
+ velocity_scale: 0.0,
1382
+ })
1383
+ );
1384
+ assert_eq!(backwards.map(2.5, 4.0), None);
1385
+
1386
+ let forwards =
1387
+ TimelineClipTiming::new(1.0, 1.0, TimelineFill::Forwards, 1.0).expect("valid clip");
1388
+ assert_eq!(forwards.map(0.5, 4.0), None);
1389
+ assert_eq!(
1390
+ forwards.map(2.5, 4.0),
1391
+ Some(TimelineClipSample {
1392
+ child_time: 1.0,
1393
+ velocity_scale: 0.0,
1394
+ })
1395
+ );
1396
+
1397
+ let both = TimelineClipTiming::new(1.0, 1.0, TimelineFill::Both, 1.0).expect("valid clip");
1398
+ assert_eq!(both.map(0.5, 4.0).unwrap().velocity_scale, 0.0);
1399
+ assert_eq!(both.map(2.5, 4.0).unwrap().velocity_scale, 0.0);
1400
+ assert_eq!(
1401
+ both.map(1.0, 4.0),
1402
+ Some(TimelineClipSample {
1403
+ child_time: 0.0,
1404
+ velocity_scale: 4.0,
1405
+ })
1406
+ );
1407
+ assert_eq!(
1408
+ both.map(2.0, 4.0),
1409
+ Some(TimelineClipSample {
1410
+ child_time: 1.0,
1411
+ velocity_scale: 4.0,
1412
+ })
1413
+ );
1414
+ }
1415
+
1416
+ #[test]
1417
+ fn timeline_clip_rejects_non_positive_speed() {
1418
+ assert_eq!(
1419
+ TimelineClipTiming::new(0.0, 0.0, TimelineFill::None, 1.0),
1420
+ Err(TimelineClipError::NonPositiveSpeed)
1421
+ );
1422
+ }
1423
+
1424
+ #[test]
1425
+ fn scalar_phase_timeline_matches_named_choreography_and_arrival_boundaries() {
1426
+ let phases = ScalarPhaseTimeline::with_options(
1427
+ None,
1428
+ vec![
1429
+ ScalarPhase::new("idle", Some(1.0)),
1430
+ ScalarPhase {
1431
+ name: "pressed".into(),
1432
+ value: Some(0.94),
1433
+ duration: Some(0.1),
1434
+ hold: 0.05,
1435
+ easing: Some(TimelineEasing::Linear),
1436
+ },
1437
+ ScalarPhase {
1438
+ name: "release".into(),
1439
+ value: Some(1.0),
1440
+ duration: Some(0.2),
1441
+ hold: 0.0,
1442
+ easing: Some(TimelineEasing::Linear),
1443
+ },
1444
+ ],
1445
+ 0.2,
1446
+ TimelineEasing::CubicBezier([0.22, 1.0, 0.36, 1.0]),
1447
+ )
1448
+ .expect("valid scalar phase timeline");
1449
+
1450
+ assert!((phases.duration() - 0.35).abs() < 1e-12);
1451
+ assert!((phases.sample(0.1, 1.0).value - 0.94).abs() < 1e-12);
1452
+ assert_eq!(phases.phase_at(0.099), "idle");
1453
+ assert_eq!(phases.phase_at(0.1), "pressed");
1454
+ assert_eq!(phases.phase_at(0.14), "pressed");
1455
+ assert_eq!(phases.phase_at(0.35), "release");
1456
+ }
1457
+
1458
+ #[test]
1459
+ fn scalar_phase_timeline_preserves_final_hold_and_missing_value_carry_forward() {
1460
+ let phases = ScalarPhaseTimeline::with_options(
1461
+ Some(3.0),
1462
+ vec![
1463
+ ScalarPhase::new("a", None),
1464
+ ScalarPhase {
1465
+ name: "b".into(),
1466
+ value: Some(10.0),
1467
+ duration: Some(0.2),
1468
+ hold: 0.3,
1469
+ easing: Some(TimelineEasing::Linear),
1470
+ },
1471
+ ScalarPhase {
1472
+ name: "c".into(),
1473
+ value: None,
1474
+ duration: Some(0.1),
1475
+ hold: 0.0,
1476
+ easing: Some(TimelineEasing::Linear),
1477
+ },
1478
+ ],
1479
+ 0.2,
1480
+ TimelineEasing::Linear,
1481
+ )
1482
+ .expect("valid scalar phase timeline");
1483
+
1484
+ assert!((phases.duration() - 0.6).abs() < 1e-12);
1485
+ assert_eq!(phases.sample(0.4, 1.0).value, 10.0);
1486
+ assert_eq!(phases.sample(0.6, 1.0).value, 10.0);
1487
+ assert_eq!(phases.phase_at(0.599), "b");
1488
+ assert_eq!(phases.phase_at(0.6), "c");
1489
+ assert_eq!(
1490
+ ScalarPhaseTimeline::new(None, vec![ScalarPhase::new("a", None)]),
1491
+ Err(PhaseTimelineError::MissingInitialValue)
1492
+ );
1493
+ }
1494
+
1495
+ #[test]
1496
+ fn stagger_schedule_preserves_first_last_center_and_numeric_origins() {
1497
+ let first = StaggerSchedule::new(0.1).expect("valid stagger");
1498
+ assert_eq!(first.delay(0, 3), 0.0);
1499
+ assert_eq!(first.delay(1, 3), 0.1);
1500
+ assert_eq!(first.delay(2, 3), 0.2);
1501
+
1502
+ let last = StaggerSchedule::with_options(0.1, 0.2, StaggerOrigin::Last, None)
1503
+ .expect("valid stagger");
1504
+ assert!((last.delay(0, 3) - 0.4).abs() < 1e-12);
1505
+ assert!((last.delay(1, 3) - 0.3).abs() < 1e-12);
1506
+ assert!((last.delay(2, 3) - 0.2).abs() < 1e-12);
1507
+
1508
+ let center = StaggerSchedule::with_options(0.1, 0.0, StaggerOrigin::Center, None)
1509
+ .expect("valid stagger");
1510
+ assert_eq!(center.delay(1, 3), 0.0);
1511
+ assert_eq!(center.delay(0, 3), center.delay(2, 3));
1512
+
1513
+ let numeric = StaggerSchedule::with_options(0.1, 0.0, StaggerOrigin::Index(1), None)
1514
+ .expect("valid stagger");
1515
+ assert_eq!(numeric.delay(1, 3), 0.0);
1516
+ assert_eq!(numeric.delay(-5, 3), 0.1);
1517
+ assert_eq!(numeric.delay(99, 3), 0.1);
1518
+ }
1519
+
1520
+ #[test]
1521
+ fn stagger_schedule_applies_easing_to_normalized_rank() {
1522
+ let eased = StaggerSchedule::with_options(
1523
+ 0.1,
1524
+ 0.0,
1525
+ StaggerOrigin::First,
1526
+ Some(TimelineEasing::CubicBezier([0.42, 0.0, 1.0, 1.0])),
1527
+ )
1528
+ .expect("valid eased stagger");
1529
+
1530
+ assert!(eased.delay(1, 3) < 0.1);
1531
+ assert_eq!(eased.delay(0, 3), 0.0);
1532
+ assert!((eased.delay(2, 3) - 0.2).abs() < 1e-12);
1533
+ }
1534
+ }