lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
//! A slider: a value picked along a track, between a least and a greatest; and a range slider, two values
//! picked on one track.

use std::{any::Any, sync::Arc};

use super::{
  names,
  part_style::{Length, PartStyle},
  recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
  shared::Orientation,
  theme::{Themed, current_theme},
};
use crate::{
  app::theme::{OpacityLevel, PaletteColor, RadiusSize, Theme},
  components,
  core::{Signal, SignalValue},
  node::{self, CursorIcon, Element, SliderPartStyle, border, dimension::Dimension},
};

/// Which way a slider's track runs: across, or up with the least value at the bottom.
pub type SliderOrientation = Orientation;

/// The parts of a slider a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SliderPart {
  /// The slider: what is dragged along, pressed and focused.
  Root,
  /// The rail across the slider, from the least value to the greatest.
  Track,
  /// The part of the track from its start to the thumb: how much of the range the value is. Of a range
  /// slider, the part between its thumbs.
  Fill,
  /// What is dragged: at the value, along the track. A range slider has two.
  Thumb,
}

names!(SliderPart {
  Root => "root",
  Track => "track",
  Fill => "fill",
  Thumb => "thumb",
});

/// The states of a slider a recipe styles, besides what the pointer and the
/// keyboard do to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SliderState {
  /// It takes no input.
  Disabled,
  /// Its track runs across, the least value at the start. One of this and [`SliderState::Vertical`] is on.
  Horizontal,
  /// Its track runs up, the least value at the bottom.
  Vertical,
  /// It is a [`RangeSlider`]: two thumbs, and the range between them.
  Range,
}

names!(SliderState {
  Disabled => "disabled",
  Horizontal => "horizontal",
  Vertical => "vertical",
  Range => "range",
});

/// What builds a slider's nodes: a theme's in place of the default one.
pub type SliderRenderer = Arc<dyn Fn(SliderView) -> Element + Send + Sync>;

/// What hears a slider's value change: its low value and its high one (of a slider of one value, that twice).
type ChangeHandler = Arc<dyn Fn(f64, f64) + Send + Sync>;

mod sealed {
  pub trait Sealed {}
  impl Sealed for i32 {}
  impl Sealed for f32 {}
}

/// A number a slider holds: whole numbers (`i32`), from 0 to 100 in steps of 1 where the slider is given no range
/// and no step, or fractions (`f32`), from 0 to 1 in steps of a hundredth. A slider is bound to a `Signal<i32>` or
/// a `Signal<f32>`, a range slider to a signal of a pair of either.
pub trait SliderNumber: sealed::Sealed + SignalValue + Copy + Send + Sync + 'static {}

impl SliderNumber for i32 {}
impl SliderNumber for f32 {}

/// The value a slider is bound to: whole numbers, or fractions; of a range slider, a low one and a high one.
#[derive(Clone)]
enum Bound {
  Int(Signal<i32>),
  Float(Signal<f32>),
  IntRange(Signal<(i32, i32)>),
  FloatRange(Signal<(f32, f32)>),
}

impl Bound {
  /// The bound of a slider of one value, of whole numbers or of fractions.
  fn one<T: SliderNumber>(value: Signal<T>) -> Self {
    let value: Box<dyn Any> = Box::new(value);
    match value.downcast::<Signal<i32>>() {
      Ok(value) => Self::Int(*value),
      Err(value) => Self::Float(
        *value
          .downcast::<Signal<f32>>()
          .expect("a slider's number is an i32 or an f32"),
      ),
    }
  }

  /// The bound of a range slider, of whole numbers or of fractions.
  fn pair<T: SliderNumber>(values: Signal<(T, T)>) -> Self
  where
    (T, T): SignalValue,
  {
    let values: Box<dyn Any> = Box::new(values);
    match values.downcast::<Signal<(i32, i32)>>() {
      Ok(values) => Self::IntRange(*values),
      Err(values) => Self::FloatRange(
        *values
          .downcast::<Signal<(f32, f32)>>()
          .expect("a range slider's numbers are i32 or f32"),
      ),
    }
  }

  /// Whether it holds whole numbers.
  fn whole(&self) -> bool {
    matches!(self, Self::Int(_) | Self::IntRange(_))
  }

  /// The greatest value where the slider is given none: 100 for whole numbers, 1 for fractions.
  fn greatest(&self) -> f32 {
    if self.whole() { 100.0 } else { 1.0 }
  }

  /// Sets the signal to `low` and `high` (a slider of one value to `low`), where it holds something else.
  fn put(&self, low: f32, high: f32) {
    match self {
      Self::Int(signal) => {
        let next = low.round() as i32;
        if signal.get_untracked() != next {
          signal.set(next);
        }
      }
      Self::Float(signal) => {
        if signal.get_untracked() != low {
          signal.set(low);
        }
      }
      Self::IntRange(signal) => {
        let next = (low.round() as i32, high.round() as i32);
        if signal.get_untracked() != next {
          signal.set(next);
        }
      }
      Self::FloatRange(signal) => {
        if signal.get_untracked() != (low, high) {
          signal.set((low, high));
        }
      }
    }
  }
}

/// A value the engine's slider holds as an `f32`, as the app is told it: a whole number exactly, a fraction as it
/// is written (0.05, not 0.05000000074505806).
fn told(value: f32, whole: bool) -> f64 {
  if whole {
    f64::from(value.round())
  } else {
    value.to_string().parse().unwrap_or(f64::from(value))
  }
}

/// The engine's slider's way: its own enum, which the design system's is not.
fn engine_orientation(orientation: Orientation) -> node::SliderOrientation {
  match orientation {
    Orientation::Horizontal => node::SliderOrientation::Horizontal,
    Orientation::Vertical => node::SliderOrientation::Vertical,
  }
}

/// A slider: a value picked along a track, between a least and a greatest.
/// Volume, the size of a brush, a price no higher than.
///
/// ```
/// use lurq::{core::Signal, ui::Slider};
///
/// let volume = Signal::new(40);
/// let slider = Slider::new(volume).label("Volume");
/// // A fraction, in steps of a twentieth.
/// let opacity = Signal::new(0.5_f32);
/// let fine = Slider::new(opacity).max(1.0).step(0.05).label("Opacity");
/// // The app holds the value, and is told what a person makes it.
/// let held = Slider::controlled(40, |value| println!("{value}")).label("Volume");
/// ```
///
/// The slider is bound to the app's signal: a drag, a press on the track
/// and the keys set it, snapped to the step and kept between the least and
/// the greatest value. [`Slider::on_change`] hears each change a person makes
/// as it is made, [`Slider::on_change_end`] the value when the drag is let go
/// or the key's step is made. The arrow keys move it a step (right and up toward the
/// greatest), Page Up and Page Down a tenth of the range in whole steps and at
/// least one, and Home and End to the least and the greatest. It is the engine's
/// [`Slider`](crate::components::Slider) dressed by the theme's recipe.
pub struct Slider {
  value: Bound,
  /// Of a controlled slider, the app's value: what the slider shows until the app answers a change.
  controlled: Option<(f32, f32)>,
  on_change: Vec<ChangeHandler>,
  on_change_end: Vec<ChangeHandler>,
  min: f32,
  max: f32,
  step: Option<f32>,
  orientation: SliderOrientation,
  length: Option<f32>,
  label: Option<Arc<str>>,
  disabled: bool,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  /// Called as the focus leaves the slider (a thumb of a range slider): for a form's slider, which judges its field
  /// then.
  on_leave: Vec<Arc<dyn Fn() + Send + Sync>>,
  // Read only where the engine has forms.
  #[cfg_attr(not(feature = "form"), allow(dead_code))]
  name: Option<Arc<str>>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl Slider {
  /// A slider bound to `value`: of whole numbers (`Signal<i32>`), from 0 to 100 in steps of 1, or of fractions
  /// (`Signal<f32>`), from 0 to 1 in steps of a hundredth. What a person does sets the signal.
  pub fn new<T: SliderNumber>(value: Signal<T>) -> Self {
    Self::bound(Bound::one(value), None)
  }

  /// A slider that shows `value`, held by the app, and tells `on_change` what a person makes it: the app sets
  /// what it shows. Of whole numbers or fractions as [`Slider::new`] is.
  /// Two built at the one place in the app's code, in a loop, are told apart by their `id` or `key`.
  pub fn controlled<T: SliderNumber>(value: T, on_change: impl Fn(f64) + Send + Sync + 'static) -> Self {
    let signal = Signal::new(value);
    let bound = Bound::one(signal);
    let held = Self::held(&bound);
    Self::bound(bound, Some(held)).on_change(on_change)
  }

  /// What `bound` holds now, as the engine holds it: the low value and the high one.
  fn held(bound: &Bound) -> (f32, f32) {
    match bound {
      Bound::Int(value) => {
        let value = value.get_untracked() as f32;
        (value, value)
      }
      Bound::Float(value) => {
        let value = value.get_untracked();
        (value, value)
      }
      Bound::IntRange(values) => {
        let (low, high) = values.get_untracked();
        (low as f32, high as f32)
      }
      Bound::FloatRange(values) => values.get_untracked(),
    }
  }

  fn bound(value: Bound, controlled: Option<(f32, f32)>) -> Self {
    Self {
      max: value.greatest(),
      value,
      controlled,
      on_change: Vec::new(),
      on_change_end: Vec::new(),
      min: 0.0,
      step: None,
      orientation: SliderOrientation::Horizontal,
      length: None,
      label: None,
      disabled: false,
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      on_leave: Vec::new(),
      name: None,
      id: None,
      key: None,
    }
  }

  /// The least value: the start of the track.
  pub fn min(mut self, min: impl Into<f64>) -> Self {
    self.min = min.into() as f32;
    self
  }

  /// The greatest value: the end of the track.
  pub fn max(mut self, max: impl Into<f64>) -> Self {
    self.max = max.into() as f32;
    self
  }

  /// How far apart the values it can take are, from the least: what an arrow
  /// key moves it by, and what a drag snaps to.
  pub fn step(mut self, step: impl Into<f64>) -> Self {
    self.step = Some(step.into() as f32);
    self
  }

  /// Which way the track runs. A vertical slider is 16 wide and 140 high,
  /// its least value at the bottom; the up and down arrows move it as the
  /// right and left ones do.
  pub fn orientation(mut self, orientation: SliderOrientation) -> Self {
    self.orientation = orientation;
    self
  }

  /// Called each time a person changes the value, with the new value: as a drag moves it, a press on the track,
  /// an arrow, Page or Home/End key. Not called when the app sets the signal, nor for a press that leaves the
  /// value as it is. Each call adds a handler.
  pub fn on_change(mut self, handler: impl Fn(f64) + Send + Sync + 'static) -> Self {
    self.on_change.push(Arc::new(move |value, _| handler(value)));
    self
  }

  /// Called when an interaction is over, with the value as it then is, where it is another than it was as the
  /// interaction began: the drag let go, the press on the track or the key's step made. A drag taken back to where
  /// it began tells nothing. Each call adds a handler.
  pub fn on_change_end(mut self, handler: impl Fn(f64) + Send + Sync + 'static) -> Self {
    self.on_change_end.push(Arc::new(move |value, _| handler(value)));
    self
  }

  /// How long the slider is along its track, in pixels: its width across, its
  /// height up. 240 across and 140 up when not given.
  pub fn length(mut self, length: f32) -> Self {
    self.length = Some(length);
    self
  }

  /// What the slider is called, to what reads the tree. The board draws no
  /// text beside a slider: the field it is in shows its label.
  pub fn label(mut self, label: &str) -> Self {
    self.label = Some(Arc::from(label));
    self
  }

  /// Whether the slider takes no input.
  pub fn disabled(mut self, disabled: bool) -> Self {
    self.disabled = disabled;
    self
  }

  /// Puts the slider in a state the theme's recipe names, or takes it out.
  pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
    let state = state.into();
    self.states.retain(|held| *held != state);
    if on {
      self.states.push(state);
    }
    self
  }

  /// Styles one part of this slider over what the theme gives it.
  pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.rules = self.rules.base(part, style);
    self
  }

  /// Lays rules over the theme's recipe for this slider: what the component
  /// it is in says of the slider in this place.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// Draws the slider as it is under the pointer or focused from the
  /// keyboard, with nothing pointing at it: for a gallery or a test.
  pub fn force(mut self, interaction: Option<Interaction>) -> Self {
    self.forced = interaction;
    self
  }

  /// The name the slider's value has in the form it is in. A range slider gives its low value and its high one
  /// under it.
  #[cfg(feature = "form")]
  pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
    self.name = Some(name.into());
    self
  }

  /// Called as the focus leaves the slider: a form's slider judges its field then.
  #[cfg_attr(not(feature = "form"), allow(dead_code))]
  pub(crate) fn on_leave(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
    self.on_leave.push(Arc::new(handler));
    self
  }

  /// The id of the slider's node: what is dragged and focused.
  pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
    self.id = Some(id.into());
    self
  }

  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.key = Some(key.into());
    self
  }

  /// Builds the slider in `theme`. Converting a slider into an element does
  /// this in the theme of what is being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    let case = Case {
      variant: None,
      size: None,
      density: None,
      breakpoint: super::current_breakpoint(),
      states: self.states.clone(),
    }
    .state(SliderState::Disabled, self.disabled)
    .state(
      SliderState::Horizontal,
      self.orientation == SliderOrientation::Horizontal,
    )
    .state(SliderState::Vertical, self.orientation == SliderOrientation::Vertical)
    .state(
      SliderState::Range,
      matches!(self.value, Bound::IntRange(_) | Bound::FloatRange(_)),
    );
    let view = SliderView {
      min: self.min,
      max: self.max.max(self.min),
      step: self.step,
      orientation: self.orientation,
      length: self.length,
      label: self.label,
      disabled: self.disabled,
      recipe: theme
        .resolve::<Slider>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      value: self.value,
      controlled: self.controlled,
      on_change: self.on_change,
      on_change_end: self.on_change_end,
      forced: self.forced,
      on_leave: self.on_leave,
      name: self.name,
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<Slider>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

impl From<Slider> for Element {
  fn from(slider: Slider) -> Self {
    slider.build(&current_theme())
  }
}

/// A slider as a renderer sees it: what it was given, the style of its
/// parts, and its behavior ready to be dressed.
pub struct SliderView {
  pub min: f32,
  pub max: f32,
  /// The step it was given; `None` for the engine's: 1 for whole numbers, a hundredth for fractions.
  pub step: Option<f32>,
  pub orientation: SliderOrientation,
  /// The length along the track it was given; `None` for the recipe's.
  pub length: Option<f32>,
  pub label: Option<Arc<str>>,
  pub disabled: bool,
  /// The style of each part of this slider.
  pub recipe: ResolvedRecipe,
  value: Bound,
  controlled: Option<(f32, f32)>,
  on_change: Vec<ChangeHandler>,
  on_change_end: Vec<ChangeHandler>,
  forced: Option<Interaction>,
  on_leave: Vec<Arc<dyn Fn() + Send + Sync>>,
  #[cfg_attr(not(feature = "form"), allow(dead_code))]
  name: Option<Arc<str>>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl SliderView {
  /// The style of a part, as this slider is to be drawn.
  pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
    self.recipe.part(part).forced(self.forced)
  }

  pub fn theme(&self) -> &Theme {
    self.recipe.theme()
  }

  /// The value, as a fraction or a whole number; of a range slider, its low
  /// value. What reads it is rendered again when it changes: a renderer that
  /// shows the value beside the track.
  pub fn value(&self) -> f32 {
    self.values().0
  }

  /// The low value and the high one of a range slider; of a slider of one
  /// value, that value twice. Read as [`SliderView::value`] is.
  pub fn values(&self) -> (f32, f32) {
    match &self.value {
      Bound::Int(value) => {
        let value = value.get() as f32;
        (value, value)
      }
      Bound::Float(value) => {
        let value = value.get();
        (value, value)
      }
      Bound::IntRange(values) => {
        let (low, high) = values.get();
        (low as f32, high as f32)
      }
      Bound::FloatRange(values) => values.get(),
    }
  }

  /// Whether this is a [`RangeSlider`]: two thumbs bound to a low value and
  /// a high one.
  pub fn is_range(&self) -> bool {
    matches!(self.value, Bound::IntRange(_) | Bound::FloatRange(_))
  }

  /// The engine's slider bound to the value (or a range slider's two), with
  /// its range, step and orientation, in the style of the root and of the
  /// length it was given: what is dragged, pressed, moved by the arrow keys,
  /// focused and disabled, and that tells the slider's handlers of what a
  /// person does. Its track, fill and thumbs are not styled yet:
  /// [`SliderView::dressed`] gives them the recipe's.
  pub fn slider(&self) -> components::Slider {
    let mut slider = match &self.value {
      Bound::Int(value) => components::Slider::new(value.clone()),
      Bound::Float(value) => components::Slider::new_f32(value.clone()),
      Bound::IntRange(values) => components::Slider::new_range(values.clone()),
      Bound::FloatRange(values) => components::Slider::new_range_f32(values.clone()),
    }
    .orientation(engine_orientation(self.orientation))
    // The range first: it keeps the value in it, snapped to the step it has, and the step then snaps it to its own.
    .range_f32(self.min, self.max);
    if let Some(step) = self.step {
      slider = slider.step(step);
    }
    let whole = self.value.whole();
    // A controlled slider shows the app's value: what a person did is told, and the slider goes back to what the
    // app holds until the app answers with the value it takes.
    let (handlers, back) = (
      self.on_change.clone(),
      self.controlled.map(|held| (self.value.clone(), held)),
    );
    if !handlers.is_empty() || back.is_some() {
      slider = slider.on_change(move |low, high| {
        let (low_told, high_told) = (told(low, whole), told(high, whole));
        for handler in &handlers {
          handler(low_told, high_told);
        }
        if let Some((bound, (low, high))) = &back {
          bound.put(*low, *high);
        }
      });
    }
    if !self.on_change_end.is_empty() {
      let handlers = self.on_change_end.clone();
      slider = slider.on_change_end(move |low, high| {
        let (low, high) = (told(low, whole), told(high, whole));
        for handler in &handlers {
          handler(low, high);
        }
      });
    }
    // A slider is a stop of Tab only in a form or with an index of its own. A control of the design system is one
    // wherever it is, in the order of the tree.
    let mut slider = slider
      .tab_index(0)
      .disabled(self.disabled)
      .part(&self.part(SliderPart::Root))
      .describe("a11y_role", "slider");
    if let Some(length) = self.length {
      slider = match self.orientation {
        SliderOrientation::Horizontal => slider.width(length),
        SliderOrientation::Vertical => slider.height(length),
      };
    }
    if let Some(label) = &self.label {
      slider = slider.describe("a11y_name", label.clone());
    }
    #[cfg(feature = "form")]
    if let Some(name) = &self.name {
      slider = slider.name(name.clone());
    }
    if !self.on_leave.is_empty() {
      let leave = self.on_leave.clone();
      slider = slider.on_blur(move || {
        for handler in &leave {
          handler();
        }
      });
    }
    if let Some(id) = &self.id {
      slider = slider.id(id.clone());
    }
    if let Some(key) = &self.key {
      slider = slider.key(key.clone());
    }
    slider
  }

  /// `slider` with its track, fill and thumb in the style the recipe gives
  /// them, at rest and under the pointer; the thumb also as it is while the
  /// slider is focused from the keyboard. The engine paints the parts: of a
  /// part's style it takes the size, the fill, the corners, the border and
  /// the ring.
  pub fn dressed(&self, slider: components::Slider) -> components::Slider {
    let theme = self.theme();
    let (track, fill, thumb) = (
      self.part(SliderPart::Track),
      self.part(SliderPart::Fill),
      self.part(SliderPart::Thumb),
    );
    let mut slider = slider
      .track_style(engine_part(&track.rest(), theme))
      .fill_style(engine_part(&fill.rest(), theme))
      .thumb_style(engine_part(&thumb.rest(), theme));
    if !track.styles().hovered.is_empty() {
      slider = slider.track_hovered_style(engine_part(&track.styles().hovered, theme));
    }
    if !fill.styles().hovered.is_empty() {
      slider = slider.fill_hovered_style(engine_part(&fill.styles().hovered, theme));
    }
    if !thumb.styles().hovered.is_empty() {
      slider = slider.thumb_hovered_style(engine_part(&thumb.styles().hovered, theme));
    }
    if !thumb.styles().focus_visible.is_empty() {
      slider = slider.thumb_focused_style(engine_part(&thumb.styles().focus_visible, theme));
    }
    slider
  }

  /// How the default renderer builds a slider: the engine's, dressed.
  pub fn render(self) -> Element {
    self.dressed(self.slider()).into()
  }
}

/// A part's style as the engine's slider paints a part: its size in pixels,
/// its fill in the theme's palette, its corners, its border and its ring.
pub(super) fn engine_part(style: &PartStyle, theme: &Theme) -> SliderPartStyle {
  let px = |length: Option<Length>| match length?.resolve(theme)? {
    Dimension::Px(px) => Some(px),
    _ => None,
  };
  let mut part = SliderPartStyle::new();
  if let Some(width) = px(style.width) {
    part = part.width(width);
  }
  if let Some(height) = px(style.height) {
    part = part.height(height);
  }
  if let Some(color) = style
    .background
    .as_ref()
    .and_then(|color| color.resolve(&theme.palette()))
  {
    part = part.background(color);
  }
  if let Some(radius) = style.radius {
    part.border_radius = Some(radius);
  }
  if let Some(border) = &style.border {
    part = part.border(border.clone());
  }
  let ring = match (&style.outline, style.focus_ring) {
    (Some(outline), _) => Some(outline.clone()),
    (None, Some(true)) => Some(theme.focus_ring().outline()),
    _ => None,
  };
  if let Some(ring) = ring {
    part = part.outline(ring);
  }
  part
}

impl crate::ui::Styled for Slider {
  type Component = Self;

  fn rules(self, rules: &crate::ui::Recipe) -> Self {
    Self::rules(self, rules)
  }

  fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
    Self::state(self, state, on)
  }
}

impl Themed for Slider {
  const NAME: &'static str = "slider";
  type Renderer = SliderRenderer;

  fn parts() -> crate::ui::Declared {
    SliderPart::declared()
  }

  fn states() -> crate::ui::Declared {
    SliderState::declared()
  }

  /// The design's slider (`pencil/lurq-design-system.pen`, Slider): 240 by
  /// 16, a track of 4 in the secondary color, filled in the primary color up
  /// to the thumb, and a round thumb of 16 in the background's color with an
  /// edge of 1.5 in the primary color inside it. The ring of the focus is
  /// the thumb's. The vertical one (Slider/Vertical) is 16 by 140, its track
  /// 4 wide and as high as it; the range slider (Range Slider) is the slider
  /// with two thumbs, the range between them.
  fn recipe() -> Recipe {
    use PaletteColor::*;
    use SliderPart::{Fill, Root, Thumb, Track};
    Recipe::new()
      // 240 long where there is the room, and no longer than the room it is given: in a narrower row its track
      // is shorter, and its thumb stays on it, inside the slider.
      .base(Root, |s| {
        s.width(240.0)
          .max_width(Length::Fill)
          .height(16.0)
          .cursor(CursorIcon::Pointer)
      })
      .base(Track, |s| s.height(4.0).radius(RadiusSize::Full).background(Secondary))
      .base(Fill, |s| s.radius(RadiusSize::Full).background(Primary))
      .base(Thumb, |s| {
        s.square(16.0)
          .radius(RadiusSize::Full)
          .background(Background)
          .border(border::Border::inside(1.5, Primary))
      })
      .focus_visible(Thumb, |s| s.focus_ring())
      .state(SliderState::Vertical, Root, |s| s.width(16.0).height(140.0))
      // The track's height is undone: it is as high as the slider.
      .state(SliderState::Vertical, Track, |s| s.width(4.0).height(Length::Auto))
      .state(SliderState::Disabled, Root, |s| {
        s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
      })
  }
}

/// A range slider: two values picked on one track, a low one and a high one.
/// A price between, the hours of a day a shop is open.
///
/// ```
/// use lurq::{core::Signal, ui::RangeSlider};
///
/// let price = Signal::new((20, 80));
/// let slider = RangeSlider::new(price).label("Price");
/// // The app holds the two values, and is told what a person makes them.
/// let held = RangeSlider::controlled((20, 80), |(low, high)| println!("{low} to {high}"));
/// ```
///
/// Bound to the app's signal of the two values, the low one first. A press on
/// the track moves the nearer thumb there, a drag moves the thumb it began on,
/// and neither thumb passes the other. Each thumb is a stop of Tab, the low
/// one first, and the keys move the one focused as they move a [`Slider`]:
/// Home and End take it no further than the other thumb. It is drawn by the
/// [`Slider`]'s recipe and renderer, in the state
/// [`SliderState::Range`]: a theme that restyles the slider restyles it too.
pub struct RangeSlider(Slider);

/// A method of [`RangeSlider`] that is [`Slider`]'s.
macro_rules! as_slider {
  ($($(#[$doc:meta])* fn $name:ident($($arg:ident: $ty:ty),*);)*) => {
    $(
      $(#[$doc])*
      pub fn $name(self, $($arg: $ty),*) -> Self {
        Self(self.0.$name($($arg),*))
      }
    )*
  };
}

impl RangeSlider {
  /// A range slider bound to `values`, the low one first: of whole numbers (`Signal<(i32, i32)>`), from 0 to 100
  /// in steps of 1, or of fractions (`Signal<(f32, f32)>`), from 0 to 1 in steps of a hundredth.
  pub fn new<T: SliderNumber>(values: Signal<(T, T)>) -> Self
  where
    (T, T): SignalValue,
  {
    Self(Slider::bound(Bound::pair(values), None))
  }

  /// A range slider that shows `values`, held by the app, the low one first, and tells `on_change` the two values
  /// a person makes them: the app sets what it shows.
  /// Two built at the one place in the app's code, in a loop, are told apart by their `id` or `key`.
  pub fn controlled<T: SliderNumber>(values: (T, T), on_change: impl Fn((f64, f64)) + Send + Sync + 'static) -> Self
  where
    (T, T): SignalValue,
  {
    let bound = Bound::pair(Signal::new(values));
    let held = Slider::held(&bound);
    Self(Slider::bound(bound, Some(held))).on_change(on_change)
  }

  /// Called each time a person changes either value, with the two, the low one first: as a drag moves a thumb,
  /// a press on the track, a key. Not called when the app sets the signal. Each call adds a handler.
  pub fn on_change(mut self, handler: impl Fn((f64, f64)) + Send + Sync + 'static) -> Self {
    self.0.on_change.push(Arc::new(move |low, high| handler((low, high))));
    self
  }

  /// Called when an interaction is over, with the two values as they then are, where they are others than they
  /// were as it began: the drag let go, the press on the track or the key's step made. Each call adds a handler.
  pub fn on_change_end(mut self, handler: impl Fn((f64, f64)) + Send + Sync + 'static) -> Self {
    self
      .0
      .on_change_end
      .push(Arc::new(move |low, high| handler((low, high))));
    self
  }

  as_slider! {
    /// The least value: the start of the track.
    fn min(min: impl Into<f64>);
    /// The greatest value: the end of the track.
    fn max(max: impl Into<f64>);
    /// How far apart the values it can take are, from the least: what an
    /// arrow key moves a thumb by, and what a drag snaps to.
    fn step(step: impl Into<f64>);
    /// Which way the track runs: see [`Slider::orientation`].
    fn orientation(orientation: SliderOrientation);
    /// How long the slider is along its track: see [`Slider::length`].
    fn length(length: f32);
    /// What the slider is called, to what reads the tree.
    fn label(label: &str);
    /// Whether the slider takes no input.
    fn disabled(disabled: bool);
    /// Puts the slider in a state the theme's recipe names, or takes it out.
    fn state(state: impl Into<Name>, on: bool);
    /// Styles one part of this slider over what the theme gives it.
    fn style(part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle);
    /// Lays rules over the theme's recipe for this slider.
    fn rules(rules: &Recipe);
    /// Draws the slider as it is under the pointer or focused from the
    /// keyboard, with nothing pointing at it: for a gallery or a test.
    fn force(interaction: Option<Interaction>);
    /// The id of the slider's node: what is dragged and focused.
    fn id(id: impl Into<Arc<str>>);
    fn key(key: impl Into<Arc<str>>);
    /// The name the two values have in the form the slider is in: it gives the low one and the high one under it.
    #[cfg(feature = "form")]
    fn name(name: impl Into<Arc<str>>);
  }

  /// Called as the focus leaves either thumb: a form's range slider judges its field then.
  #[cfg_attr(not(feature = "form"), allow(dead_code))]
  pub(crate) fn on_leave(self, handler: impl Fn() + Send + Sync + 'static) -> Self {
    Self(self.0.on_leave(handler))
  }

  /// Builds the range slider in `theme`. Converting it into an element does
  /// this in the theme of what is being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    self.0.build(theme)
  }
}

impl From<RangeSlider> for Element {
  fn from(slider: RangeSlider) -> Self {
    slider.build(&current_theme())
  }
}

impl super::FieldControl for Slider {
  /// Called by the field's label unless it has a name of its own, and disabled where the field is. A slider has no
  /// judgment.
  fn in_field(mut self, field: &super::InField) -> Element {
    if self.label.is_none() && !field.label.is_empty() {
      self.label = Some(field.label.clone());
    }
    self.disabled |= field.disabled;
    self.into()
  }
}

impl super::FieldControl for RangeSlider {
  /// As a [`Slider`] takes it.
  fn in_field(self, field: &super::InField) -> Element {
    self.0.in_field(field)
  }
}