@mun-ui/ui 0.0.0-stage → 0.2.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.
Files changed (176) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -2
  3. package/bin/compile.mjs +38 -0
  4. package/bin/desktop.mjs +143 -0
  5. package/bin/dev-protocol.mjs +94 -0
  6. package/bin/formatter.mjs +109 -0
  7. package/bin/hot-reload.mjs +38 -0
  8. package/bin/mun.mjs +538 -0
  9. package/bin/native.mjs +133 -0
  10. package/bin/pnpm-workspace.mjs +58 -0
  11. package/bin/program-patch.mjs +104 -0
  12. package/bin/project.mjs +322 -0
  13. package/bin/watch.mjs +316 -0
  14. package/bin/workflow.mjs +261 -0
  15. package/dist/astro.d.ts +3 -0
  16. package/dist/astro.d.ts.map +1 -0
  17. package/dist/astro.js +3 -0
  18. package/dist/astro.js.map +1 -0
  19. package/dist/closures.d.ts +2 -0
  20. package/dist/closures.d.ts.map +1 -0
  21. package/dist/closures.js +2 -0
  22. package/dist/closures.js.map +1 -0
  23. package/dist/compiler/index.d.ts +2 -0
  24. package/dist/compiler/index.d.ts.map +1 -0
  25. package/dist/compiler/index.js +2 -0
  26. package/dist/compiler/index.js.map +1 -0
  27. package/dist/core.d.ts +3 -0
  28. package/dist/core.d.ts.map +1 -0
  29. package/dist/core.js +3 -0
  30. package/dist/core.js.map +1 -0
  31. package/dist/experimental.d.ts +2 -0
  32. package/dist/experimental.d.ts.map +1 -0
  33. package/dist/experimental.js +2 -0
  34. package/dist/experimental.js.map +1 -0
  35. package/dist/index.d.ts +3 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +3 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/jsx-dev-runtime.d.ts +2 -0
  40. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  41. package/dist/jsx-dev-runtime.js +2 -0
  42. package/dist/jsx-dev-runtime.js.map +1 -0
  43. package/dist/jsx-runtime.d.ts +2 -0
  44. package/dist/jsx-runtime.d.ts.map +1 -0
  45. package/dist/jsx-runtime.js +2 -0
  46. package/dist/jsx-runtime.js.map +1 -0
  47. package/dist/legacy.d.ts +3 -0
  48. package/dist/legacy.d.ts.map +1 -0
  49. package/dist/legacy.js +3 -0
  50. package/dist/legacy.js.map +1 -0
  51. package/dist/mun.d.ts +5 -0
  52. package/dist/mun.d.ts.map +1 -0
  53. package/dist/mun.js +4 -0
  54. package/dist/mun.js.map +1 -0
  55. package/dist/progressive-blur/index.d.ts +8 -0
  56. package/dist/progressive-blur/index.d.ts.map +1 -0
  57. package/dist/progressive-blur/index.js +8 -0
  58. package/dist/progressive-blur/index.js.map +1 -0
  59. package/dist/progressive-blur/plan.d.ts +3 -0
  60. package/dist/progressive-blur/plan.d.ts.map +1 -0
  61. package/dist/progressive-blur/plan.js +3 -0
  62. package/dist/progressive-blur/plan.js.map +1 -0
  63. package/dist/react-types.d.ts +2 -0
  64. package/dist/react-types.d.ts.map +1 -0
  65. package/dist/react-types.js +2 -0
  66. package/dist/react-types.js.map +1 -0
  67. package/dist/rendering-quality.d.ts +4 -0
  68. package/dist/rendering-quality.d.ts.map +1 -0
  69. package/dist/rendering-quality.js +4 -0
  70. package/dist/rendering-quality.js.map +1 -0
  71. package/dist/state.d.ts +2 -0
  72. package/dist/state.d.ts.map +1 -0
  73. package/dist/state.js +2 -0
  74. package/dist/state.js.map +1 -0
  75. package/dist/types.d.ts +2 -0
  76. package/dist/types.d.ts.map +1 -0
  77. package/dist/types.js +2 -0
  78. package/dist/types.js.map +1 -0
  79. package/dist/vite.d.ts +2 -0
  80. package/dist/vite.d.ts.map +1 -0
  81. package/dist/vite.js +2 -0
  82. package/dist/vite.js.map +1 -0
  83. package/editors/install.mjs +102 -0
  84. package/editors/lsp/mun-lsp.mjs +123 -0
  85. package/editors/lsp/service.mjs +306 -0
  86. package/editors/lsp/source.mjs +58 -0
  87. package/editors/vscode/client.mjs +40 -0
  88. package/editors/vscode/dev-client.mjs +83 -0
  89. package/editors/vscode/discovery.mjs +46 -0
  90. package/editors/vscode/export.mjs +42 -0
  91. package/editors/vscode/extension.cjs +226 -0
  92. package/editors/vscode/language-configuration.json +15 -0
  93. package/editors/vscode/package.json +119 -0
  94. package/editors/vscode/protocol.mjs +29 -0
  95. package/editors/vscode/syntaxes/mun.tmLanguage.json +130 -0
  96. package/native/Cargo.lock +3581 -0
  97. package/native/Cargo.toml +21 -0
  98. package/native/README.md +21 -0
  99. package/native/mun-native/Cargo.toml +23 -0
  100. package/native/mun-native/src/accessibility.rs +738 -0
  101. package/native/mun-native/src/dev.rs +604 -0
  102. package/native/mun-native/src/host_services.rs +202 -0
  103. package/native/mun-native/src/lib.rs +2843 -0
  104. package/native/mun-native/src/main.rs +204 -0
  105. package/native/mun-native/src/offscreen.rs +393 -0
  106. package/native/mun-native/src/rect.wgsl +63 -0
  107. package/native/mun-native/src/text.rs +401 -0
  108. package/native/mun-native/tests/offscreen_rendering.rs +161 -0
  109. package/native/mun-native/tests/stress.rs +408 -0
  110. package/native/mun-native/tests/window_lifecycle.rs +183 -0
  111. package/native/mun-runtime/Cargo.toml +13 -0
  112. package/native/mun-runtime/src/accessibility.rs +193 -0
  113. package/native/mun-runtime/src/collection.rs +1090 -0
  114. package/native/mun-runtime/src/gesture.rs +1070 -0
  115. package/native/mun-runtime/src/input.rs +325 -0
  116. package/native/mun-runtime/src/ir.rs +852 -0
  117. package/native/mun-runtime/src/kinetics.rs +500 -0
  118. package/native/mun-runtime/src/layout.rs +258 -0
  119. package/native/mun-runtime/src/layout_cache.rs +209 -0
  120. package/native/mun-runtime/src/lib.rs +52 -0
  121. package/native/mun-runtime/src/motion.rs +1162 -0
  122. package/native/mun-runtime/src/retained.rs +574 -0
  123. package/native/mun-runtime/src/runtime.rs +7449 -0
  124. package/native/mun-runtime/src/scene.rs +567 -0
  125. package/native/mun-runtime/src/scroll.rs +521 -0
  126. package/native/mun-runtime/src/scroll_view.rs +220 -0
  127. package/native/mun-runtime/src/text_edit.rs +670 -0
  128. package/native/mun-runtime/src/timeline.rs +1534 -0
  129. package/native/mun-runtime/src/validate.rs +677 -0
  130. package/native/mun-runtime/tests/accessibility_semantics.rs +168 -0
  131. package/native/mun-runtime/tests/compiler_contract.rs +110 -0
  132. package/native/mun-runtime/tests/flexible_frames.rs +47 -0
  133. package/native/mun-runtime/tests/host_services.rs +107 -0
  134. package/native/mun-runtime/tests/hot_update.rs +367 -0
  135. package/native/mun-runtime/tests/incremental_runtime.rs +323 -0
  136. package/native/mun-runtime/tests/ir_validation.rs +167 -0
  137. package/native/mun-runtime/tests/keyed_collections.rs +251 -0
  138. package/native/mun-runtime/tests/minimum_window_size.rs +80 -0
  139. package/native/mun-runtime/tests/native_controls_style.rs +491 -0
  140. package/native/mun-runtime/tests/native_demo.rs +285 -0
  141. package/native/mun-runtime/tests/native_layout_style.rs +175 -0
  142. package/native/mun-runtime/tests/native_settings_pane.rs +152 -0
  143. package/native/mun-runtime/tests/priority_proposals.rs +69 -0
  144. package/native/mun-runtime/tests/scroll_view.rs +403 -0
  145. package/native/mun-runtime/tests/text_editing.rs +491 -0
  146. package/native/mun-runtime/tests/text_proposals.rs +42 -0
  147. package/native/mun-runtime/tests/typography.rs +63 -0
  148. package/package.json +213 -3
  149. package/schemas/README.md +19 -0
  150. package/schemas/semantic-ui-ir-v1.schema.json +2061 -0
  151. package/templates/desktop/gitignore +5 -0
  152. package/templates/desktop/package.json +10 -0
  153. package/templates/desktop/src-tauri/Cargo.toml +14 -0
  154. package/templates/desktop/src-tauri/build.rs +1 -0
  155. package/templates/desktop/src-tauri/capabilities/main.json +12 -0
  156. package/templates/desktop/src-tauri/icons/icon.icns +0 -0
  157. package/templates/desktop/src-tauri/icons/icon.ico +0 -0
  158. package/templates/desktop/src-tauri/icons/icon.png +0 -0
  159. package/templates/desktop/src-tauri/src/main.rs +2 -0
  160. package/templates/desktop/src-tauri/tauri.conf.json +42 -0
  161. package/templates/desktop/vite.config.ts +10 -0
  162. package/templates/native/App.mun +15 -0
  163. package/templates/native/gitignore +3 -0
  164. package/templates/native/mun.toml +8 -0
  165. package/templates/project/gitignore +5 -0
  166. package/templates/project/index.html +13 -0
  167. package/templates/project/package.json +24 -0
  168. package/templates/project/src/App.mun +13 -0
  169. package/templates/project/src/index.css +30 -0
  170. package/templates/project/src/main.ts +5 -0
  171. package/templates/project/tsconfig.json +20 -0
  172. package/templates/project/vite.config.ts +6 -0
  173. package/templates/vite/src/App.css +134 -0
  174. package/templates/vite/src/App.tsx +91 -0
  175. package/templates/vite/src/index.css +23 -0
  176. package/templates/vite/vite.config.ts +10 -0
@@ -0,0 +1,1070 @@
1
+ //! Renderer-neutral gesture recognition recovered from Mün's inherited animation stack.
2
+ //!
3
+ //! This layer owns pointer-sample interpretation only. It reports semantic drag state
4
+ //! and release velocity; kinetic continuation remains owned by the motion scheduler.
5
+
6
+ use std::collections::VecDeque;
7
+
8
+ use crate::{
9
+ input::{InputPoint, PointerId},
10
+ motion::{InertiaSpec, KineticSpec, KineticSpecError},
11
+ };
12
+
13
+ const DEFAULT_WINDOW_SECONDS: f64 = 0.120;
14
+ const DEFAULT_MAX_SAMPLES: usize = 12;
15
+ const DEFAULT_MAX_VELOCITY: f64 = 100_000.0;
16
+
17
+ #[derive(Clone, Copy, Debug, PartialEq)]
18
+ pub struct VelocityTrackerConfig {
19
+ pub window_seconds: f64,
20
+ pub max_samples: usize,
21
+ pub max_velocity: f64,
22
+ }
23
+
24
+ impl Default for VelocityTrackerConfig {
25
+ fn default() -> Self {
26
+ Self {
27
+ window_seconds: DEFAULT_WINDOW_SECONDS,
28
+ max_samples: DEFAULT_MAX_SAMPLES,
29
+ max_velocity: DEFAULT_MAX_VELOCITY,
30
+ }
31
+ }
32
+ }
33
+
34
+ #[derive(Clone, Copy, Debug, PartialEq)]
35
+ struct VelocitySample {
36
+ value: f64,
37
+ time_seconds: f64,
38
+ }
39
+
40
+ #[derive(Clone, Debug)]
41
+ pub struct VelocityTracker {
42
+ config: VelocityTrackerConfig,
43
+ samples: VecDeque<VelocitySample>,
44
+ }
45
+
46
+ impl Default for VelocityTracker {
47
+ fn default() -> Self {
48
+ Self::new(VelocityTrackerConfig::default())
49
+ }
50
+ }
51
+
52
+ impl VelocityTracker {
53
+ pub fn new(config: VelocityTrackerConfig) -> Self {
54
+ let config = VelocityTrackerConfig {
55
+ window_seconds: finite_or(config.window_seconds, DEFAULT_WINDOW_SECONDS).max(0.016),
56
+ max_samples: config.max_samples.max(2),
57
+ max_velocity: finite_or(config.max_velocity, DEFAULT_MAX_VELOCITY)
58
+ .abs()
59
+ .max(1.0),
60
+ };
61
+ Self {
62
+ samples: VecDeque::with_capacity(config.max_samples),
63
+ config,
64
+ }
65
+ }
66
+
67
+ pub fn reset(&mut self, value: f64, time_seconds: f64) {
68
+ self.samples.clear();
69
+ self.add(value, time_seconds);
70
+ }
71
+
72
+ pub fn add(&mut self, value: f64, time_seconds: f64) {
73
+ let value = finite_or(value, 0.0);
74
+ let time_seconds = if time_seconds.is_finite() {
75
+ time_seconds
76
+ } else {
77
+ self.samples
78
+ .back()
79
+ .map(|sample| sample.time_seconds)
80
+ .unwrap_or(0.0)
81
+ };
82
+
83
+ if let Some(last) = self.samples.back_mut() {
84
+ if time_seconds < last.time_seconds {
85
+ return;
86
+ }
87
+ if time_seconds == last.time_seconds {
88
+ last.value = value;
89
+ return;
90
+ }
91
+ }
92
+
93
+ if self.samples.len() == self.config.max_samples {
94
+ self.samples.pop_front();
95
+ }
96
+ self.samples.push_back(VelocitySample {
97
+ value,
98
+ time_seconds,
99
+ });
100
+
101
+ let cutoff = time_seconds - self.config.window_seconds;
102
+ while self.samples.len() > 2
103
+ && self
104
+ .samples
105
+ .front()
106
+ .is_some_and(|sample| sample.time_seconds < cutoff)
107
+ {
108
+ self.samples.pop_front();
109
+ }
110
+ }
111
+
112
+ pub fn velocity(&self) -> f64 {
113
+ if self.samples.len() < 2 {
114
+ return 0.0;
115
+ }
116
+
117
+ let latest = self
118
+ .samples
119
+ .back()
120
+ .expect("velocity tracker has samples")
121
+ .time_seconds;
122
+ let weight_scale = 0.024_f64.max(self.config.window_seconds * 0.55);
123
+ let mut weight_sum = 0.0;
124
+ let mut mean_time = 0.0;
125
+ let mut mean_value = 0.0;
126
+
127
+ for sample in &self.samples {
128
+ let age = latest - sample.time_seconds;
129
+ let weight = (-age / weight_scale).exp();
130
+ let relative_time = sample.time_seconds - latest;
131
+ weight_sum += weight;
132
+ mean_time += relative_time * weight;
133
+ mean_value += sample.value * weight;
134
+ }
135
+
136
+ if weight_sum <= 0.0 {
137
+ return 0.0;
138
+ }
139
+ mean_time /= weight_sum;
140
+ mean_value /= weight_sum;
141
+
142
+ let mut numerator = 0.0;
143
+ let mut denominator = 0.0;
144
+ for sample in &self.samples {
145
+ let age = latest - sample.time_seconds;
146
+ let weight = (-age / weight_scale).exp();
147
+ let time = sample.time_seconds - latest - mean_time;
148
+ let value = sample.value - mean_value;
149
+ numerator += weight * time * value;
150
+ denominator += weight * time * time;
151
+ }
152
+
153
+ if denominator < 1e-9 {
154
+ return 0.0;
155
+ }
156
+
157
+ (numerator / denominator).clamp(-self.config.max_velocity, self.config.max_velocity)
158
+ }
159
+
160
+ pub fn sample_count(&self) -> usize {
161
+ self.samples.len()
162
+ }
163
+ }
164
+
165
+ pub fn rubber_band_distance(distance: f32, dimension: f32, constant: f32) -> f32 {
166
+ let sign = distance.signum();
167
+ let distance = finite_f32_or(distance, 0.0).abs();
168
+ let dimension = finite_f32_or(dimension, 320.0).abs().max(1.0);
169
+ let constant = finite_f32_or(constant, 0.55).max(0.0);
170
+ if distance == 0.0 || constant == 0.0 {
171
+ return 0.0;
172
+ }
173
+
174
+ sign * ((distance * constant * dimension) / (dimension + constant * distance))
175
+ }
176
+
177
+ #[derive(Clone, Copy, Debug, PartialEq)]
178
+ pub struct DragAxisConstraint {
179
+ pub min: f32,
180
+ pub max: f32,
181
+ pub rubber_band: bool,
182
+ pub rubber_band_constant: f32,
183
+ pub rubber_band_dimension: Option<f32>,
184
+ }
185
+
186
+ impl Default for DragAxisConstraint {
187
+ fn default() -> Self {
188
+ Self {
189
+ min: f32::NEG_INFINITY,
190
+ max: f32::INFINITY,
191
+ rubber_band: true,
192
+ rubber_band_constant: 0.55,
193
+ rubber_band_dimension: None,
194
+ }
195
+ }
196
+ }
197
+
198
+ /// Apply the inherited live-drag value rule: start value plus pointer translation,
199
+ /// constrained by optional rubber-band bounds.
200
+ pub fn constrained_drag_axis_value(
201
+ start_value: f32,
202
+ translation: f32,
203
+ constraint: DragAxisConstraint,
204
+ ) -> Result<f32, KineticSpecError> {
205
+ let start_value = finite_f32_or(start_value, 0.0);
206
+ let translation = finite_f32_or(translation, 0.0);
207
+ let min = if constraint.min.is_finite() {
208
+ constraint.min
209
+ } else {
210
+ f32::NEG_INFINITY
211
+ };
212
+ let max = if constraint.max.is_finite() {
213
+ constraint.max
214
+ } else {
215
+ f32::INFINITY
216
+ };
217
+ if min > max {
218
+ return Err(KineticSpecError::InvalidBounds);
219
+ }
220
+
221
+ Ok(constrain_with_rubber_band(
222
+ start_value + translation,
223
+ min,
224
+ max,
225
+ constraint.rubber_band,
226
+ constraint.rubber_band_constant,
227
+ constraint.rubber_band_dimension,
228
+ ))
229
+ }
230
+
231
+ pub fn constrain_with_rubber_band(
232
+ value: f32,
233
+ min: f32,
234
+ max: f32,
235
+ enabled: bool,
236
+ constant: f32,
237
+ dimension: Option<f32>,
238
+ ) -> f32 {
239
+ assert!(min <= max, "gesture min cannot be greater than max");
240
+
241
+ if value < min {
242
+ if !enabled {
243
+ return min;
244
+ }
245
+ let size = dimension.unwrap_or_else(|| {
246
+ if (max - min).is_finite() {
247
+ max - min
248
+ } else {
249
+ 320.0
250
+ }
251
+ });
252
+ return min + rubber_band_distance(value - min, size, constant);
253
+ }
254
+
255
+ if value > max {
256
+ if !enabled {
257
+ return max;
258
+ }
259
+ let size = dimension.unwrap_or_else(|| {
260
+ if (max - min).is_finite() {
261
+ max - min
262
+ } else {
263
+ 320.0
264
+ }
265
+ });
266
+ return max + rubber_band_distance(value - max, size, constant);
267
+ }
268
+
269
+ value
270
+ }
271
+
272
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
273
+ pub enum DragAxis {
274
+ X,
275
+ Y,
276
+ Both,
277
+ }
278
+
279
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
280
+ pub enum GesturePhase {
281
+ Began,
282
+ Changed,
283
+ Ended,
284
+ Cancelled,
285
+ }
286
+
287
+ #[derive(Clone, Copy, Debug, PartialEq)]
288
+ pub struct DragRecognizerConfig {
289
+ pub axis: DragAxis,
290
+ pub direction_lock: bool,
291
+ pub direction_lock_threshold: f32,
292
+ pub velocity: VelocityTrackerConfig,
293
+ }
294
+
295
+ impl Default for DragRecognizerConfig {
296
+ fn default() -> Self {
297
+ Self {
298
+ axis: DragAxis::Both,
299
+ direction_lock: false,
300
+ direction_lock_threshold: 8.0,
301
+ velocity: VelocityTrackerConfig::default(),
302
+ }
303
+ }
304
+ }
305
+
306
+ #[derive(Clone, Copy, Debug, PartialEq)]
307
+ pub struct GestureAxisRelease {
308
+ pub position: f32,
309
+ pub velocity: f32,
310
+ }
311
+
312
+ #[derive(Clone, Copy, Debug, PartialEq)]
313
+ pub struct DragSettleSpec {
314
+ pub response: f32,
315
+ pub damping_ratio: f32,
316
+ }
317
+
318
+ impl Default for DragSettleSpec {
319
+ fn default() -> Self {
320
+ Self {
321
+ response: 0.28,
322
+ damping_ratio: 0.82,
323
+ }
324
+ }
325
+ }
326
+
327
+ #[derive(Clone, Copy, Debug, PartialEq)]
328
+ pub struct DragReleaseOptions {
329
+ pub momentum: bool,
330
+ pub min: f32,
331
+ pub max: f32,
332
+ pub inertia: InertiaSpec,
333
+ pub settle: DragSettleSpec,
334
+ }
335
+
336
+ impl Default for DragReleaseOptions {
337
+ fn default() -> Self {
338
+ Self {
339
+ momentum: true,
340
+ min: f32::NEG_INFINITY,
341
+ max: f32::INFINITY,
342
+ inertia: InertiaSpec::default(),
343
+ settle: DragSettleSpec::default(),
344
+ }
345
+ }
346
+ }
347
+
348
+ #[derive(Clone, Copy, Debug, PartialEq)]
349
+ pub enum DragCancelPlan {
350
+ /// Cancel without settling: leave the current motion value untouched.
351
+ Preserve { current: f32 },
352
+ /// Settled cancellation while already inside bounds: keep the value and
353
+ /// explicitly zero the motion channel velocity.
354
+ Stop { position: f32 },
355
+ /// Settled cancellation outside bounds: spring back to the nearest bound
356
+ /// with the inherited cancellation spring.
357
+ Settle {
358
+ current: f32,
359
+ target: f32,
360
+ response: f32,
361
+ damping_ratio: f32,
362
+ },
363
+ }
364
+
365
+ pub fn plan_drag_axis_cancel(
366
+ current: f32,
367
+ constraint: DragAxisConstraint,
368
+ settle: bool,
369
+ ) -> Result<DragCancelPlan, KineticSpecError> {
370
+ let current = finite_f32_or(current, 0.0);
371
+ let min = if constraint.min.is_finite() {
372
+ constraint.min
373
+ } else {
374
+ f32::NEG_INFINITY
375
+ };
376
+ let max = if constraint.max.is_finite() {
377
+ constraint.max
378
+ } else {
379
+ f32::INFINITY
380
+ };
381
+ if min > max {
382
+ return Err(KineticSpecError::InvalidBounds);
383
+ }
384
+
385
+ if !settle {
386
+ return Ok(DragCancelPlan::Preserve { current });
387
+ }
388
+
389
+ let target = current.clamp(min, max);
390
+ if target == current {
391
+ Ok(DragCancelPlan::Stop { position: current })
392
+ } else {
393
+ Ok(DragCancelPlan::Settle {
394
+ current,
395
+ target,
396
+ response: 0.25,
397
+ damping_ratio: 0.9,
398
+ })
399
+ }
400
+ }
401
+
402
+ #[derive(Clone, Copy, Debug, PartialEq)]
403
+ pub enum DragReleasePlan {
404
+ Hold {
405
+ position: f32,
406
+ },
407
+ Settle {
408
+ current: f32,
409
+ target: f32,
410
+ initial_velocity: f32,
411
+ response: f32,
412
+ damping_ratio: f32,
413
+ },
414
+ Inertia {
415
+ current: f32,
416
+ spec: KineticSpec,
417
+ },
418
+ }
419
+
420
+ pub fn nearest_snap(target: f32, points: &[f32]) -> f32 {
421
+ let target = finite_f32_or(target, 0.0);
422
+ let mut best = target;
423
+ let mut best_distance = f32::INFINITY;
424
+
425
+ for &point in points {
426
+ if !point.is_finite() {
427
+ continue;
428
+ }
429
+ let distance = (point - target).abs();
430
+ if distance < best_distance {
431
+ best = point;
432
+ best_distance = distance;
433
+ }
434
+ }
435
+
436
+ best
437
+ }
438
+
439
+ /// Resolve inherited drag-release semantics without starting an animation.
440
+ ///
441
+ /// The caller owns the current motion value. This planner returns either a
442
+ /// stable hold, an explicit spring-back contract, or an inertia spec ready for
443
+ /// the existing MotionScheduler velocity continuation path.
444
+ pub fn plan_drag_axis_release(
445
+ current: f32,
446
+ velocity: f32,
447
+ options: DragReleaseOptions,
448
+ snap_points: &[f32],
449
+ ) -> Result<DragReleasePlan, KineticSpecError> {
450
+ let current = finite_f32_or(current, 0.0);
451
+ let velocity = finite_f32_or(velocity, 0.0);
452
+ let min = if options.min.is_finite() {
453
+ options.min
454
+ } else {
455
+ f32::NEG_INFINITY
456
+ };
457
+ let max = if options.max.is_finite() {
458
+ options.max
459
+ } else {
460
+ f32::INFINITY
461
+ };
462
+ if min > max {
463
+ return Err(KineticSpecError::InvalidBounds);
464
+ }
465
+
466
+ let outside = current < min || current > max;
467
+ if !options.momentum {
468
+ if !outside {
469
+ return Ok(DragReleasePlan::Hold { position: current });
470
+ }
471
+
472
+ let settle = options.settle;
473
+ return Ok(DragReleasePlan::Settle {
474
+ current,
475
+ target: current.clamp(min, max),
476
+ initial_velocity: velocity,
477
+ response: finite_f32_or(settle.response, 0.28).max(f32::EPSILON),
478
+ damping_ratio: finite_f32_or(settle.damping_ratio, 0.82).max(0.0),
479
+ });
480
+ }
481
+
482
+ let mut inertia = options.inertia;
483
+ let projected = crate::motion::kinetics::project_decay_target(
484
+ current as f64,
485
+ velocity as f64,
486
+ inertia.time_constant,
487
+ inertia.power,
488
+ inertia.target_override,
489
+ ) as f32;
490
+ let snapped = nearest_snap(projected, snap_points);
491
+
492
+ inertia.velocity = Some(velocity as f64);
493
+ inertia.min = min as f64;
494
+ inertia.max = max as f64;
495
+ inertia.target_override = Some(snapped as f64);
496
+
497
+ Ok(DragReleasePlan::Inertia {
498
+ current,
499
+ spec: KineticSpec::Inertia(inertia),
500
+ })
501
+ }
502
+
503
+ #[derive(Clone, Copy, Debug, PartialEq)]
504
+ pub struct DragState {
505
+ pub phase: GesturePhase,
506
+ pub pointer: PointerId,
507
+ pub start: InputPoint,
508
+ pub position: InputPoint,
509
+ pub translation: InputPoint,
510
+ pub velocity: InputPoint,
511
+ pub locked_axis: Option<DragAxis>,
512
+ }
513
+
514
+ impl DragState {
515
+ pub fn release(&self, axis: DragAxis) -> Option<GestureAxisRelease> {
516
+ match axis {
517
+ DragAxis::X if self.locked_axis != Some(DragAxis::Y) => Some(GestureAxisRelease {
518
+ position: self.translation.x,
519
+ velocity: self.velocity.x,
520
+ }),
521
+ DragAxis::Y if self.locked_axis != Some(DragAxis::X) => Some(GestureAxisRelease {
522
+ position: self.translation.y,
523
+ velocity: self.velocity.y,
524
+ }),
525
+ DragAxis::Both => None,
526
+ _ => None,
527
+ }
528
+ }
529
+ }
530
+
531
+ #[derive(Clone, Debug)]
532
+ pub struct DragRecognizer {
533
+ config: DragRecognizerConfig,
534
+ active_pointer: Option<PointerId>,
535
+ start: InputPoint,
536
+ position: InputPoint,
537
+ locked_axis: Option<DragAxis>,
538
+ tracker_x: VelocityTracker,
539
+ tracker_y: VelocityTracker,
540
+ }
541
+
542
+ impl DragRecognizer {
543
+ pub fn new(config: DragRecognizerConfig) -> Self {
544
+ let velocity = config.velocity;
545
+ Self {
546
+ config: DragRecognizerConfig {
547
+ direction_lock_threshold: finite_f32_or(config.direction_lock_threshold, 8.0)
548
+ .max(0.0),
549
+ ..config
550
+ },
551
+ active_pointer: None,
552
+ start: InputPoint::default(),
553
+ position: InputPoint::default(),
554
+ locked_axis: None,
555
+ tracker_x: VelocityTracker::new(velocity),
556
+ tracker_y: VelocityTracker::new(velocity),
557
+ }
558
+ }
559
+
560
+ pub fn is_active(&self) -> bool {
561
+ self.active_pointer.is_some()
562
+ }
563
+
564
+ pub fn begin(
565
+ &mut self,
566
+ pointer: PointerId,
567
+ position: InputPoint,
568
+ time_seconds: f64,
569
+ ) -> DragState {
570
+ self.active_pointer = Some(pointer);
571
+ self.start = position;
572
+ self.position = position;
573
+ self.locked_axis = None;
574
+ self.tracker_x.reset(position.x as f64, time_seconds);
575
+ self.tracker_y.reset(position.y as f64, time_seconds);
576
+ self.state(GesturePhase::Began)
577
+ }
578
+
579
+ pub fn move_pointer(
580
+ &mut self,
581
+ pointer: PointerId,
582
+ position: InputPoint,
583
+ time_seconds: f64,
584
+ ) -> Option<DragState> {
585
+ if self.active_pointer != Some(pointer) {
586
+ return None;
587
+ }
588
+
589
+ self.position = position;
590
+ self.tracker_x.add(position.x as f64, time_seconds);
591
+ self.tracker_y.add(position.y as f64, time_seconds);
592
+ self.resolve_direction_lock();
593
+ Some(self.state(GesturePhase::Changed))
594
+ }
595
+
596
+ pub fn end(&mut self, pointer: PointerId, time_seconds: f64) -> Option<DragState> {
597
+ if self.active_pointer != Some(pointer) {
598
+ return None;
599
+ }
600
+
601
+ self.tracker_x.add(self.position.x as f64, time_seconds);
602
+ self.tracker_y.add(self.position.y as f64, time_seconds);
603
+ self.resolve_direction_lock();
604
+ let state = self.state(GesturePhase::Ended);
605
+ self.active_pointer = None;
606
+ Some(state)
607
+ }
608
+
609
+ pub fn cancel(&mut self, pointer: Option<PointerId>) -> Option<DragState> {
610
+ let active = self.active_pointer?;
611
+ if pointer.is_some() && pointer != Some(active) {
612
+ return None;
613
+ }
614
+
615
+ let mut state = self.state(GesturePhase::Cancelled);
616
+ state.velocity = InputPoint::default();
617
+ self.active_pointer = None;
618
+ Some(state)
619
+ }
620
+
621
+ fn resolve_direction_lock(&mut self) {
622
+ if !self.config.direction_lock || self.locked_axis.is_some() {
623
+ return;
624
+ }
625
+
626
+ let dx = self.position.x - self.start.x;
627
+ let dy = self.position.y - self.start.y;
628
+ if dx.hypot(dy) < self.config.direction_lock_threshold {
629
+ return;
630
+ }
631
+
632
+ self.locked_axis = Some(match self.config.axis {
633
+ DragAxis::X => DragAxis::X,
634
+ DragAxis::Y => DragAxis::Y,
635
+ DragAxis::Both => {
636
+ if dx.abs() >= dy.abs() {
637
+ DragAxis::X
638
+ } else {
639
+ DragAxis::Y
640
+ }
641
+ }
642
+ });
643
+ }
644
+
645
+ fn state(&self, phase: GesturePhase) -> DragState {
646
+ let dx = self.position.x - self.start.x;
647
+ let dy = self.position.y - self.start.y;
648
+ let (translation, velocity) = if self.config.direction_lock && self.locked_axis.is_none() {
649
+ (InputPoint::default(), InputPoint::default())
650
+ } else {
651
+ (
652
+ self.filter_axes(InputPoint::new(dx, dy)),
653
+ self.filter_axes(InputPoint::new(
654
+ self.tracker_x.velocity() as f32,
655
+ self.tracker_y.velocity() as f32,
656
+ )),
657
+ )
658
+ };
659
+
660
+ DragState {
661
+ phase,
662
+ pointer: self
663
+ .active_pointer
664
+ .expect("drag state requires an active pointer"),
665
+ start: self.start,
666
+ position: self.position,
667
+ translation,
668
+ velocity,
669
+ locked_axis: self.locked_axis.or(match self.config.axis {
670
+ DragAxis::X => Some(DragAxis::X),
671
+ DragAxis::Y => Some(DragAxis::Y),
672
+ DragAxis::Both => None,
673
+ }),
674
+ }
675
+ }
676
+
677
+ fn filter_axes(&self, point: InputPoint) -> InputPoint {
678
+ match self.locked_axis.unwrap_or(self.config.axis) {
679
+ DragAxis::X => InputPoint::new(point.x, 0.0),
680
+ DragAxis::Y => InputPoint::new(0.0, point.y),
681
+ DragAxis::Both => point,
682
+ }
683
+ }
684
+ }
685
+
686
+ fn finite_or(value: f64, fallback: f64) -> f64 {
687
+ if value.is_finite() { value } else { fallback }
688
+ }
689
+
690
+ fn finite_f32_or(value: f32, fallback: f32) -> f32 {
691
+ if value.is_finite() { value } else { fallback }
692
+ }
693
+
694
+ #[cfg(test)]
695
+ mod tests {
696
+ use super::*;
697
+ use crate::{
698
+ ir::MotionProperty,
699
+ motion::{MotionChannelKey, MotionScheduler},
700
+ };
701
+
702
+ fn point(x: f32, y: f32) -> InputPoint {
703
+ InputPoint::new(x, y)
704
+ }
705
+
706
+ #[test]
707
+ fn velocity_tracker_recovers_weighted_linear_velocity() {
708
+ let mut tracker = VelocityTracker::default();
709
+ tracker.reset(0.0, 0.0);
710
+ tracker.add(4.0, 0.04);
711
+ tracker.add(8.0, 0.08);
712
+ tracker.add(12.0, 0.12);
713
+
714
+ assert!((tracker.velocity() - 100.0).abs() < 0.001);
715
+ }
716
+
717
+ #[test]
718
+ fn velocity_tracker_replaces_equal_time_and_ignores_time_regression() {
719
+ let mut tracker = VelocityTracker::default();
720
+ tracker.reset(0.0, 0.0);
721
+ tracker.add(5.0, 0.05);
722
+ tracker.add(6.0, 0.05);
723
+ tracker.add(100.0, 0.04);
724
+
725
+ assert_eq!(tracker.sample_count(), 2);
726
+ assert!((tracker.velocity() - 120.0).abs() < 0.001);
727
+ }
728
+
729
+ #[test]
730
+ fn velocity_tracker_trims_old_samples_but_keeps_regression_pair() {
731
+ let mut tracker = VelocityTracker::new(VelocityTrackerConfig {
732
+ window_seconds: 0.016,
733
+ max_samples: 4,
734
+ max_velocity: 100_000.0,
735
+ });
736
+ tracker.reset(0.0, 0.0);
737
+ tracker.add(1.0, 0.010);
738
+ tracker.add(2.0, 0.020);
739
+ tracker.add(10.0, 1.0);
740
+
741
+ assert_eq!(tracker.sample_count(), 2);
742
+ }
743
+
744
+ #[test]
745
+ fn constrained_drag_value_preserves_start_value_and_rubber_band() {
746
+ let constraint = DragAxisConstraint {
747
+ min: 0.0,
748
+ max: 100.0,
749
+ ..Default::default()
750
+ };
751
+
752
+ let value = constrained_drag_axis_value(40.0, 80.0, constraint).unwrap();
753
+ assert!(value > 100.0);
754
+ assert!(value < 120.0);
755
+
756
+ assert_eq!(
757
+ constrained_drag_axis_value(
758
+ 40.0,
759
+ 80.0,
760
+ DragAxisConstraint {
761
+ rubber_band: false,
762
+ ..constraint
763
+ }
764
+ )
765
+ .unwrap(),
766
+ 100.0
767
+ );
768
+ assert_eq!(
769
+ constrained_drag_axis_value(40.0, 80.0, DragAxisConstraint::default()).unwrap(),
770
+ 120.0
771
+ );
772
+ }
773
+
774
+ #[test]
775
+ fn constrained_drag_value_rejects_invalid_bounds() {
776
+ assert_eq!(
777
+ constrained_drag_axis_value(
778
+ 0.0,
779
+ 10.0,
780
+ DragAxisConstraint {
781
+ min: 20.0,
782
+ max: -20.0,
783
+ ..Default::default()
784
+ }
785
+ ),
786
+ Err(KineticSpecError::InvalidBounds)
787
+ );
788
+ }
789
+
790
+ #[test]
791
+ fn drag_direction_lock_waits_for_threshold_and_filters_velocity() {
792
+ let mut drag = DragRecognizer::new(DragRecognizerConfig {
793
+ direction_lock: true,
794
+ direction_lock_threshold: 8.0,
795
+ ..Default::default()
796
+ });
797
+
798
+ let began = drag.begin(PointerId(7), point(0.0, 0.0), 0.0);
799
+ assert_eq!(began.phase, GesturePhase::Began);
800
+ assert_eq!(began.translation, point(0.0, 0.0));
801
+
802
+ let pending = drag
803
+ .move_pointer(PointerId(7), point(4.0, 3.0), 0.04)
804
+ .expect("active pointer move");
805
+ assert_eq!(pending.locked_axis, None);
806
+ assert_eq!(pending.translation, point(0.0, 0.0));
807
+
808
+ let changed = drag
809
+ .move_pointer(PointerId(7), point(12.0, 5.0), 0.08)
810
+ .expect("direction-locking move");
811
+ assert_eq!(changed.locked_axis, Some(DragAxis::X));
812
+ assert_eq!(changed.translation, point(12.0, 0.0));
813
+ assert_eq!(changed.velocity.y, 0.0);
814
+ assert!(changed.velocity.x > 0.0);
815
+
816
+ let ended = drag.end(PointerId(7), 0.10).expect("drag end");
817
+ assert_eq!(ended.phase, GesturePhase::Ended);
818
+ assert_eq!(ended.locked_axis, Some(DragAxis::X));
819
+ assert!(!drag.is_active());
820
+ }
821
+
822
+ #[test]
823
+ fn drag_ignores_non_owner_pointer_and_cancels_owner() {
824
+ let mut drag = DragRecognizer::new(Default::default());
825
+ drag.begin(PointerId(1), point(10.0, 20.0), 0.0);
826
+
827
+ assert!(
828
+ drag.move_pointer(PointerId(2), point(30.0, 40.0), 0.02)
829
+ .is_none()
830
+ );
831
+ assert!(drag.cancel(Some(PointerId(2))).is_none());
832
+
833
+ let cancelled = drag.cancel(Some(PointerId(1))).expect("owner cancellation");
834
+ assert_eq!(cancelled.phase, GesturePhase::Cancelled);
835
+ assert_eq!(cancelled.velocity, point(0.0, 0.0));
836
+ assert!(!drag.is_active());
837
+ }
838
+
839
+ #[test]
840
+ fn drag_cancel_without_settle_preserves_current_value() {
841
+ assert_eq!(
842
+ plan_drag_axis_cancel(
843
+ 120.0,
844
+ DragAxisConstraint {
845
+ min: 0.0,
846
+ max: 100.0,
847
+ ..Default::default()
848
+ },
849
+ false,
850
+ )
851
+ .unwrap(),
852
+ DragCancelPlan::Preserve { current: 120.0 }
853
+ );
854
+ }
855
+
856
+ #[test]
857
+ fn settled_drag_cancel_stops_inside_bounds_and_springs_outside() {
858
+ let constraint = DragAxisConstraint {
859
+ min: 0.0,
860
+ max: 100.0,
861
+ ..Default::default()
862
+ };
863
+
864
+ assert_eq!(
865
+ plan_drag_axis_cancel(40.0, constraint, true).unwrap(),
866
+ DragCancelPlan::Stop { position: 40.0 }
867
+ );
868
+ assert_eq!(
869
+ plan_drag_axis_cancel(120.0, constraint, true).unwrap(),
870
+ DragCancelPlan::Settle {
871
+ current: 120.0,
872
+ target: 100.0,
873
+ response: 0.25,
874
+ damping_ratio: 0.9,
875
+ }
876
+ );
877
+ assert_eq!(
878
+ plan_drag_axis_cancel(-20.0, constraint, true).unwrap(),
879
+ DragCancelPlan::Settle {
880
+ current: -20.0,
881
+ target: 0.0,
882
+ response: 0.25,
883
+ damping_ratio: 0.9,
884
+ }
885
+ );
886
+ }
887
+
888
+ #[test]
889
+ fn drag_cancel_rejects_invalid_bounds_before_motion_handoff() {
890
+ assert_eq!(
891
+ plan_drag_axis_cancel(
892
+ 0.0,
893
+ DragAxisConstraint {
894
+ min: 1.0,
895
+ max: -1.0,
896
+ ..Default::default()
897
+ },
898
+ true,
899
+ ),
900
+ Err(KineticSpecError::InvalidBounds)
901
+ );
902
+ }
903
+
904
+ #[test]
905
+ fn nearest_snap_matches_inherited_first_nearest_semantics() {
906
+ assert_eq!(nearest_snap(40.0, &[]), 40.0);
907
+ assert_eq!(
908
+ nearest_snap(40.0, &[f32::NAN, 20.0, 60.0, f32::INFINITY]),
909
+ 20.0
910
+ );
911
+ }
912
+
913
+ #[test]
914
+ fn release_without_momentum_holds_inside_bounds_and_settles_outside() {
915
+ let options = DragReleaseOptions {
916
+ momentum: false,
917
+ min: 0.0,
918
+ max: 100.0,
919
+ ..Default::default()
920
+ };
921
+
922
+ assert_eq!(
923
+ plan_drag_axis_release(40.0, 120.0, options, &[0.0, 100.0]).unwrap(),
924
+ DragReleasePlan::Hold { position: 40.0 }
925
+ );
926
+
927
+ assert_eq!(
928
+ plan_drag_axis_release(120.0, 75.0, options, &[0.0, 100.0]).unwrap(),
929
+ DragReleasePlan::Settle {
930
+ current: 120.0,
931
+ target: 100.0,
932
+ initial_velocity: 75.0,
933
+ response: 0.28,
934
+ damping_ratio: 0.82,
935
+ }
936
+ );
937
+ }
938
+
939
+ #[test]
940
+ fn momentum_release_projects_then_snaps_before_kinetic_handoff() {
941
+ let options = DragReleaseOptions {
942
+ min: 0.0,
943
+ max: 100.0,
944
+ inertia: InertiaSpec {
945
+ velocity: Some(-999.0),
946
+ time_constant: 0.325,
947
+ power: 0.8,
948
+ ..Default::default()
949
+ },
950
+ ..Default::default()
951
+ };
952
+
953
+ let plan = plan_drag_axis_release(10.0, 100.0, options, &[0.0, 50.0, 100.0]).unwrap();
954
+ let DragReleasePlan::Inertia { current, spec } = plan else {
955
+ panic!("expected inertia release");
956
+ };
957
+ assert_eq!(current, 10.0);
958
+
959
+ let KineticSpec::Inertia(spec) = spec else {
960
+ panic!("expected inertia spec");
961
+ };
962
+ assert_eq!(spec.velocity, Some(100.0));
963
+ assert_eq!(spec.min, 0.0);
964
+ assert_eq!(spec.max, 100.0);
965
+ assert_eq!(spec.target_override, Some(50.0));
966
+ }
967
+
968
+ #[test]
969
+ fn pre_resolved_modify_target_is_snapped_after_projection() {
970
+ let options = DragReleaseOptions {
971
+ inertia: InertiaSpec {
972
+ target_override: Some(72.0),
973
+ ..Default::default()
974
+ },
975
+ ..Default::default()
976
+ };
977
+
978
+ let plan = plan_drag_axis_release(0.0, 10.0, options, &[50.0, 100.0]).unwrap();
979
+ let DragReleasePlan::Inertia { spec, .. } = plan else {
980
+ panic!("expected inertia release");
981
+ };
982
+ let KineticSpec::Inertia(spec) = spec else {
983
+ panic!("expected inertia spec");
984
+ };
985
+ assert_eq!(spec.target_override, Some(50.0));
986
+ }
987
+
988
+ #[test]
989
+ fn release_planner_rejects_invalid_bounds_before_motion_mutation() {
990
+ let result = plan_drag_axis_release(
991
+ 0.0,
992
+ 0.0,
993
+ DragReleaseOptions {
994
+ min: 10.0,
995
+ max: -10.0,
996
+ ..Default::default()
997
+ },
998
+ &[],
999
+ );
1000
+ assert_eq!(result, Err(KineticSpecError::InvalidBounds));
1001
+ }
1002
+
1003
+ #[test]
1004
+ fn drag_release_velocity_hands_off_to_existing_motion_scheduler() {
1005
+ let mut drag = DragRecognizer::new(DragRecognizerConfig {
1006
+ axis: DragAxis::X,
1007
+ ..Default::default()
1008
+ });
1009
+ let pointer = PointerId(17);
1010
+ drag.begin(pointer, point(0.0, 0.0), 0.0);
1011
+ drag.move_pointer(pointer, point(12.0, 0.0), 0.04)
1012
+ .expect("drag sample");
1013
+ drag.move_pointer(pointer, point(28.0, 0.0), 0.08)
1014
+ .expect("drag sample");
1015
+ let ended = drag.end(pointer, 0.10).expect("drag release");
1016
+ let release = ended.release(DragAxis::X).expect("x-axis release");
1017
+ assert!(release.velocity > 0.0);
1018
+
1019
+ let key = MotionChannelKey {
1020
+ node_id: "drag-target".into(),
1021
+ property: MotionProperty::TranslationX,
1022
+ };
1023
+ let mut scheduler = MotionScheduler::default();
1024
+ let plan = plan_drag_axis_release(
1025
+ release.position,
1026
+ release.velocity,
1027
+ DragReleaseOptions {
1028
+ min: -500.0,
1029
+ max: 500.0,
1030
+ inertia: InertiaSpec {
1031
+ power: 1.0,
1032
+ ..Default::default()
1033
+ },
1034
+ ..Default::default()
1035
+ },
1036
+ &[],
1037
+ )
1038
+ .expect("release plan");
1039
+ let DragReleasePlan::Inertia { current, spec } = plan else {
1040
+ panic!("expected kinetic handoff");
1041
+ };
1042
+ scheduler
1043
+ .animate_velocity(key.clone(), current, &spec)
1044
+ .expect("kinetic handoff");
1045
+
1046
+ let start = scheduler.value(&key).expect("kinetic presentation");
1047
+ let velocity = scheduler.velocity(&key).expect("kinetic velocity");
1048
+ assert!((start - release.position).abs() < 0.001);
1049
+ assert!((velocity - release.velocity).abs() < 0.001);
1050
+
1051
+ scheduler.step(1.0 / 60.0);
1052
+ assert!(scheduler.value(&key).expect("advanced presentation") > start);
1053
+ }
1054
+
1055
+ #[test]
1056
+ fn rubber_band_matches_inherited_bounded_constraint() {
1057
+ let constrained = constrain_with_rubber_band(120.0, 0.0, 100.0, true, 0.55, Some(100.0));
1058
+ assert!(constrained > 100.0);
1059
+ assert!(constrained < 120.0);
1060
+
1061
+ assert_eq!(
1062
+ constrain_with_rubber_band(120.0, 0.0, 100.0, false, 0.55, Some(100.0)),
1063
+ 100.0
1064
+ );
1065
+ assert_eq!(
1066
+ constrain_with_rubber_band(40.0, 0.0, 100.0, true, 0.55, Some(100.0)),
1067
+ 40.0
1068
+ );
1069
+ }
1070
+ }