1use crate::{Node, Value};
2
3#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4pub enum DialInputMode {
5 #[default]
6 Circular,
7 Horizontal,
8 Vertical,
9}
10
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12pub enum ScrollSnapMode {
13 #[default]
14 None,
15 Always,
16 OnRelease,
17}
18
19#[derive(Clone, Copy, Debug, PartialEq)]
21pub enum RangeAction {
22 SetFraction(f64),
23 CommitFraction(f64),
24 SetValue(f64),
25 SetPoint { x: f64, y: f64 },
26 Decrease,
27 Increase,
28 Step(i64),
29 Minimum,
30 Maximum,
31 Release,
32}
33
34impl RangeAction {
35 pub fn is_release(self) -> bool {
36 matches!(self, Self::Release | Self::CommitFraction(_))
37 }
38}
39
40pub(crate) fn step_float(
42 value: f64,
43 limits: (f64, f64),
44 step: f64,
45 steps: i64,
46 wrap: bool,
47 normalize: impl Fn(f64) -> f64,
48) -> f64 {
49 let (min, max) = limits;
50 if step == 0.0 || steps == 0 || min == max {
51 return value;
52 }
53 let forward = steps > 0;
54 let amount = steps.unsigned_abs() as f64;
55 let signed_step = if forward { step } else { -step };
56 let advance = |from, count| normalize(signed_step.mul_add(count, from));
57 let limit = if forward { max } else { min };
58 let fits = |candidate| {
59 if forward {
60 candidate <= limit
61 } else {
62 candidate >= limit
63 }
64 };
65 let next = advance(value, amount);
66 if !wrap || fits(next) {
67 return next.clamp(min, max);
68 }
69 let steps_in_range = |from: f64| {
70 let distance = limit - from;
71 let estimate = if distance.is_finite() {
72 distance / signed_step
73 } else {
74 (limit * 0.5 - from * 0.5) / (signed_step * 0.5)
75 }
76 .floor()
77 .min(amount);
78 if estimate < amount && fits(advance(from, estimate + 1.0)) {
79 estimate + 1.0
80 } else if estimate > 0.0 && !fits(advance(from, estimate)) {
81 estimate - 1.0
82 } else {
83 estimate
84 }
85 };
86 let start = if forward { min } else { max };
87 let remaining = (amount - steps_in_range(value) - 1.0).max(0.0);
88 let cycle = steps_in_range(start) + 1.0;
89 advance(start, remaining % cycle).clamp(min, max)
90}
91
92#[derive(Clone, Copy, Debug, PartialEq)]
93pub struct SliderRange {
94 min: f64,
95 max: f64,
96 value: f64,
97 step: f64,
98 wrap: bool,
99 snap: ScrollSnapMode,
100}
101
102impl SliderRange {
103 pub fn from_node(node: &Node) -> Self {
104 let min = node.number("minimum").unwrap_or(0.0);
105 let max = node.number("maximum").unwrap_or(100.0).max(min);
106 Self {
107 min,
108 max,
109 value: node.number("value").unwrap_or(0.0).clamp(min, max),
110 step: node.number("step").unwrap_or(1.0).max(0.0),
111 wrap: node.kind == "Dial" && node.boolean("wrap", false),
112 snap: match node.properties.get("snap-mode") {
113 Some(Value::ScrollSnapMode(mode)) => *mode,
114 _ => ScrollSnapMode::None,
115 },
116 }
117 }
118
119 pub fn with_value(mut self, value: f64) -> Self {
120 if value.is_finite() {
121 self.value = value.clamp(self.min, self.max);
122 }
123 self
124 }
125
126 pub fn snap_mode(self) -> ScrollSnapMode {
127 self.snap
128 }
129
130 pub fn preview_fraction(self, fraction: f64) -> f64 {
131 self.with_value(
132 self.apply(RangeAction::SetFraction(fraction))
133 .unwrap_or(self.value),
134 )
135 .fraction()
136 }
137
138 fn snap_value(self, value: f64) -> f64 {
139 let value = value.clamp(self.min, self.max);
140 if self.step == 0.0 || value == self.min || value == self.max {
141 return value;
142 }
143 let steps = ((value - self.min) / self.step).round();
144 if !steps.is_finite() {
145 return value;
146 }
147 let snapped = steps.mul_add(self.step, self.min).clamp(self.min, self.max);
148 if self.max - value < (snapped - value).abs() {
149 self.max
150 } else {
151 snapped
152 }
153 }
154
155 pub fn value(self) -> f64 {
156 self.value
157 }
158
159 pub fn fraction(self) -> f64 {
160 if self.max == self.min {
161 return 0.0;
162 }
163 let span = self.max - self.min;
164 if span.is_finite() {
165 (self.value - self.min) / span
166 } else {
167 (self.value * 0.5 - self.min * 0.5) / (self.max * 0.5 - self.min * 0.5)
169 }
170 }
171
172 pub fn apply(self, action: RangeAction) -> Option<f64> {
173 let next = match action {
174 RangeAction::SetFraction(fraction) | RangeAction::CommitFraction(fraction)
175 if fraction.is_finite() =>
176 {
177 let t = fraction.clamp(0.0, 1.0);
178 let value = self.min * (1.0 - t) + self.max * t;
179 if self.snap == ScrollSnapMode::Always
180 || self.snap == ScrollSnapMode::OnRelease && action.is_release()
181 {
182 self.snap_value(value)
183 } else {
184 value
185 }
186 }
187 RangeAction::SetValue(value) if value.is_finite() => {
188 if self.snap == ScrollSnapMode::None {
189 value
190 } else {
191 self.snap_value(value)
192 }
193 }
194 RangeAction::Decrease => self.value - self.step,
195 RangeAction::Increase => self.value + self.step,
196 RangeAction::Step(steps) => step_float(
197 self.value,
198 (self.min, self.max),
199 self.step,
200 steps,
201 self.wrap,
202 |value| value,
203 ),
204 RangeAction::Minimum => self.min,
205 RangeAction::Maximum => self.max,
206 _ => return None,
207 };
208 let next = match action {
209 RangeAction::Increase if self.wrap && next > self.max => self.min,
210 RangeAction::Decrease if self.wrap && next < self.min => self.max,
211 _ => next.clamp(self.min, self.max),
212 };
213 (next != self.value).then_some(next)
214 }
215}
216
217pub fn progress_value(node: &Node) -> f64 {
218 node.number("progress").unwrap_or(0.0).clamp(0.0, 1.0)
219}
220
221#[derive(Clone, Copy, Debug, PartialEq)]
222pub struct ScrollBarRange {
223 pub position: f64,
224 pub size: f64,
225 pub step: f64,
226}
227
228impl ScrollBarRange {
229 pub const DEFAULT_SIZE: f64 = 0.0;
230 pub const DEFAULT_STEP: f64 = 0.1;
231
232 pub fn from_node(node: &Node) -> Self {
233 Self::new(
234 node.number("position").unwrap_or_default(),
235 node.number("size").unwrap_or(Self::DEFAULT_SIZE),
236 node.number("step-size").unwrap_or(Self::DEFAULT_STEP),
237 )
238 }
239
240 pub fn new(position: f64, size: f64, step: f64) -> Self {
241 let unit = |value: f64, default| {
242 if value.is_finite() {
243 value.clamp(0.0, 1.0)
244 } else {
245 default
246 }
247 };
248 let size = unit(size, Self::DEFAULT_SIZE);
249 Self {
250 position: unit(position, 0.0).min(1.0 - size),
251 size,
252 step: unit(step, Self::DEFAULT_STEP),
253 }
254 }
255
256 pub fn maximum(self) -> f64 {
257 1.0 - self.size
258 }
259
260 pub fn apply(self, action: RangeAction) -> Option<f64> {
261 let next = match action {
262 RangeAction::SetFraction(fraction) if fraction.is_finite() => fraction * self.maximum(),
263 RangeAction::Decrease => self.position - self.step,
264 RangeAction::Increase => self.position + self.step,
265 RangeAction::Minimum => 0.0,
266 RangeAction::Maximum => self.maximum(),
267 _ => return None,
268 }
269 .clamp(0.0, self.maximum());
270 (next != self.position).then_some(next)
271 }
272}
273
274#[derive(Clone, Copy, Debug, PartialEq)]
275pub enum IndicatorState {
276 Hidden,
277 Determinate(f64),
278 Indeterminate,
279}
280
281pub fn indicator_state(node: &Node) -> Option<IndicatorState> {
282 Some(match node.kind {
283 "BusyIndicator" if node.boolean("running", true) => IndicatorState::Indeterminate,
284 "BusyIndicator" => IndicatorState::Hidden,
285 "Spinner" | "ProgressIndicator" if node.boolean("indeterminate", false) => {
286 IndicatorState::Indeterminate
287 }
288 "Spinner" | "ProgressIndicator" => IndicatorState::Determinate(progress_value(node)),
289 _ => return None,
290 })
291}
292
293#[derive(Clone, Copy, Debug)]
294pub struct SliderInterval {
295 axis: SliderRange,
296 values: [f64; 2],
297}
298
299impl SliderInterval {
300 pub fn from_node(node: &Node) -> Self {
301 let axis = SliderRange::from_node(node);
302 Self::from_values(
303 node,
304 node.number("lower-value").unwrap_or(axis.min),
305 node.number("upper-value").unwrap_or(axis.max),
306 )
307 }
308
309 pub fn from_values(node: &Node, lower: f64, upper: f64) -> Self {
310 let axis = SliderRange::from_node(node);
311 let upper = if upper.is_finite() {
312 upper.clamp(axis.min, axis.max)
313 } else {
314 axis.max
315 };
316 let lower = if lower.is_finite() {
317 lower.clamp(axis.min, upper)
318 } else {
319 axis.min
320 };
321 Self {
322 axis,
323 values: [lower, upper],
324 }
325 }
326
327 pub fn values(self) -> [f64; 2] {
328 self.values
329 }
330
331 pub fn fractions(self) -> [f64; 2] {
332 self.values
333 .map(|value| SliderRange { value, ..self.axis }.fraction())
334 }
335
336 pub fn nearest_handle(self, fraction: f64) -> usize {
337 let [lower, upper] = self.fractions();
338 usize::from(if lower == upper {
339 fraction >= lower
340 } else {
341 (fraction - upper).abs() < (fraction - lower).abs()
342 })
343 }
344
345 pub fn preview_fractions(self, handle: usize, fraction: f64) -> [f64; 2] {
346 let values = self
347 .apply(handle, RangeAction::SetFraction(fraction))
348 .unwrap_or(self.values);
349 Self { values, ..self }.fractions()
350 }
351
352 pub fn apply(self, handle: usize, action: RangeAction) -> Option<[f64; 2]> {
353 let value = *self.values.get(handle)?;
354 let mut values = self.values;
355 let next = SliderRange { value, ..self.axis }.apply(action)?;
356 values[handle] = if handle == 0 {
357 next.min(values[1])
358 } else {
359 next.max(values[0])
360 };
361 (values != self.values).then_some(values)
362 }
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368
369 #[test]
370 fn batched_steps_keep_remaining_detents_after_wrap() {
371 let mut dial = Node::new("Dial", None);
372 dial.properties.insert("minimum", (-2.0_f64).into());
373 dial.properties.insert("maximum", 3.0_f64.into());
374 dial.properties.insert("value", 2.0_f64.into());
375 dial.properties.insert("wrap", true.into());
376 let range = SliderRange::from_node(&dial);
377 assert_eq!(range.apply(RangeAction::Step(3)), Some(-1.0));
378 assert_eq!(range.apply(RangeAction::Step(-6)), None);
379 assert_eq!(
380 step_float(
381 -f64::MAX,
382 (-f64::MAX, f64::MAX),
383 f64::MAX,
384 10,
385 true,
386 |value| value
387 ),
388 0.0,
389 );
390 }
391
392 #[test]
393 fn slider_snap_uses_the_minimum_and_keeps_a_partial_final_step_reachable() {
394 let mut node = Node::new("Slider", None);
395 node.properties.insert("minimum", 3.0_f64.into());
396 node.properties.insert("maximum", 17.0_f64.into());
397 node.properties.insert("step", 5.0_f64.into());
398 node.properties
399 .insert("snap-mode", ScrollSnapMode::OnRelease.into());
400 let range = SliderRange::from_node(&node);
401 assert_eq!(range.apply(RangeAction::SetFraction(0.5)), Some(10.0));
402 assert_eq!(range.apply(RangeAction::CommitFraction(0.5)), Some(8.0));
403 assert_eq!(range.apply(RangeAction::CommitFraction(0.96)), Some(17.0));
404 assert_eq!(range.apply(RangeAction::SetValue(15.0)), Some(13.0));
405 assert_eq!(range.apply(RangeAction::SetValue(f64::INFINITY)), None);
406 }
407}