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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//! A progress bar: how far a piece of work is, along a rail; and a ring progress, the same value around a circle.

use std::{sync::Arc, time::Duration};

use super::{
  meter::number,
  names,
  part_style::{Length, PartTransition},
  recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe},
  theme::{Themed, current_theme},
};
use crate::{
  animation::{AnimatableProperty, AnimatableValue, Animation, Easing, Keyframes, KeyframesId, Transition},
  app::theme::{MotionDuration, PaletteColor, RadiusSize, Theme, TypographyStyle},
  components::{Row, Stack},
  layout::{Alignment, StackAlignment, layout_kind::Justify, text_style::FontWeight},
  node::{BackgroundColor, Element, border::Border, color::Color, dimension::Dimension, node_kind::TextOverflow},
};

/// The keyframes of the room before the moving segment of a progress that does not know how far it is: it grows
/// from nothing to the whole rail, pushing the segment across and out at the end.
pub const PROGRESS_LEAD: KeyframesId = KeyframesId::new(0xFF21);

/// The keyframes of the moving segment of a progress that does not know how far it is: it grows out of the start
/// of the rail to its width, and keeps it as it is pushed across.
pub const PROGRESS_SEGMENT: KeyframesId = KeyframesId::new(0xFF22);

/// How long the segment of a progress that does not know how far it is takes to cross the rail once.
pub const PROGRESS_PERIOD: Duration = Duration::from_millis(1600);

/// The share of the rail the segment of a progress that does not know how far it is fills, in percent: 90 of 240
/// (`pencil/lurq-design-system.pen`, Loader/Linear).
const SEGMENT: f32 = 37.5;

/// Where the segment stands while motion is reduced: 70 of 240 from the start, as the board draws it.
const STILL_LEAD: f32 = 70.0 / 240.0 * 100.0;

/// How far through a crossing the segment has grown to its width.
const GROWN: f32 = SEGMENT / 100.0;

/// The keyframes of a progress that does not know how far it is: [`PROGRESS_LEAD`] and [`PROGRESS_SEGMENT`],
/// which every window has. Both play in phase, so the room and the segment of one bar move together, and every
/// such bar of a window moves as the others do.
pub(crate) fn keyframes() -> [Keyframes; 2] {
  let share = |frame: &mut crate::animation::KeyframeBuilder, percent: f32| {
    frame.set(AnimatableProperty::Width, AnimatableValue::Percent(percent));
  };
  [
    Keyframes::new(PROGRESS_LEAD)
      .frame(0.0, |frame| share(frame, 0.0))
      .frame(1.0, |frame| share(frame, 100.0)),
    Keyframes::new(PROGRESS_SEGMENT)
      .frame(0.0, |frame| share(frame, 0.0))
      .frame(GROWN, |frame| share(frame, SEGMENT))
      .frame(1.0, |frame| share(frame, SEGMENT)),
  ]
}

/// The parts of a progress bar a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ProgressPart {
  /// The bar with its label and its value above it.
  Root,
  /// The row of the label and the value, over the rail.
  Header,
  /// What the work is: "Uploading theme.json".
  Label,
  /// How far it is, at the end of the header: "62%".
  Value,
  /// The rail: as long as the whole of the work.
  Track,
  /// What is filled of the rail: as long as what is done. Of a progress that does not know how far it is, the
  /// segment that crosses the rail.
  Fill,
  /// The line under the rail: "2 minutes left".
  Description,
}

names!(ProgressPart {
  Root => "root",
  Header => "header",
  Label => "label",
  Value => "value",
  Track => "track",
  Fill => "fill",
  Description => "description",
});

/// The states of a progress bar a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ProgressState {
  /// It does not know how far the work is: a segment crosses the rail again and again.
  Indeterminate,
  /// It is the thin bar across the top of a window or a surface: no rail, square at the start.
  TopBar,
}

names!(ProgressState {
  Indeterminate => "indeterminate",
  TopBar => "top_bar",
});

/// What a progress says of the work: the color of what is filled.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ProgressVariant {
  /// Work under way: the primary color.
  #[default]
  Neutral,
  /// Work to know of: the info color.
  Info,
  /// Work that went well, or a share that is good to have: the success color.
  Success,
  /// A share that wants a look: the warning color.
  Warning,
  /// Work that failed, or a share that is too much: the destructive color.
  Destructive,
}

names!(ProgressVariant {
  Neutral => "neutral",
  Info => "info",
  Success => "success",
  Warning => "warning",
  Destructive => "destructive",
});

/// How large a progress is: how thick a bar's rail is, and how wide a ring is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ProgressSize {
  /// A rail of 4, in a row of a list (a file being uploaded); a ring of 40.
  Sm,
  /// A rail of 6, under a label or in a dialog; a ring of 56.
  Md,
  /// A rail of 8, the board's progress; a ring of 72, the board's ring.
  #[default]
  Lg,
}

names!(ProgressSize {
  Sm => "sm",
  Md => "md",
  Lg => "lg",
});

/// What a [`ProgressDialog`](super::ProgressDialog) says its value with: given the value and the greatest value.
pub type ProgressFormat = Arc<dyn Fn(f32, f32) -> String + Send + Sync>;

/// What writes a value as the app does, given the value.
type ValueText = Arc<dyn Fn(f64) -> String + Send + Sync>;

/// How far the work is: a value in a range, or not known.
#[derive(Clone)]
struct Amount {
  /// `None` while it is not known.
  value: Option<f64>,
  min: f64,
  max: f64,
  value_text: Option<ValueText>,
}

impl Amount {
  fn new(value: Option<f64>) -> Self {
    Self {
      value,
      min: 0.0,
      max: 1.0,
      value_text: None,
    }
  }

  /// The value as it was given; `None` while it is not known.
  fn value(&self) -> Option<f64> {
    self.value
  }

  /// How much of the range the value fills, from 0 to 1: a value under the least fills nothing and one over the
  /// greatest all of it. A range of nothing or less has no room: nothing is done.
  fn fraction(&self) -> Option<f32> {
    let value = self.value?;
    let span = self.max - self.min;
    Some(if span > 0.0 {
      ((value - self.min) / span).clamp(0.0, 1.0) as f32
    } else {
      0.0
    })
  }

  /// The value as it is written: by the app's `value_text`, given the value as it is, or as a percentage of the
  /// range.
  fn text(&self) -> Option<String> {
    let value = self.value?;
    Some(match &self.value_text {
      Some(text) => text(value),
      None => percent(self.fraction()?),
    })
  }
}

/// A fraction as a whole percentage: "62%".
fn percent(fraction: f32) -> String {
  format!("{}%", (fraction * 100.0).round() as i32)
}

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

/// A progress bar: how far a piece of work is. A file uploading, items being
/// copied, the steps of an install.
///
/// ```
/// use lurq::ui::{Progress, ProgressSize, ProgressVariant};
///
/// // A fraction of one.
/// let upload = Progress::new(0.62).label("Uploading theme.json").show_value(true).size(ProgressSize::Md);
/// // 42 of 128 items, said as the app says it.
/// let copy = Progress::new(42.0).max(128.0).show_value(true).value_text(|done| format!("{done} of 128"));
/// let full = Progress::new(0.92).variant(ProgressVariant::Warning);
/// // Work whose end is not known.
/// let loading = Progress::indeterminate().label("Connecting");
/// ```
///
/// What is filled moves to a new value over the theme's slow duration. A
/// progress that does not know how far it is runs a segment across its rail
/// again and again; while motion is reduced the segment stands still, apart
/// from the start of the rail, where no value would be. A progress is read
/// and not operated: it takes no focus and no press. To tooling that reads
/// the tree it is a `progressbar`, called by its label and described by its
/// description, with its value, its least and its greatest and the value's
/// text, as a [`Meter`](super::Meter) says them, and no value while it does
/// not know it.
pub struct Progress {
  amount: Amount,
  variant: Name,
  size: Name,
  label: Option<Arc<str>>,
  label_hidden: bool,
  description: Option<Arc<str>>,
  show_value: bool,
  top_bar: bool,
  width: Option<Length>,
  states: Vec<Name>,
  rules: Recipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl Progress {
  /// A progress at `value`, a fraction of one unless [`min`](Self::min) and
  /// [`max`](Self::max) say another range. A value under the least fills
  /// nothing, and one over the greatest all of the rail; its text says what
  /// it is.
  pub fn new(value: impl Into<f64>) -> Self {
    Self::with(Amount::new(Some(value.into())))
  }

  /// A progress of work whose end is not known.
  pub fn indeterminate() -> Self {
    Self::with(Amount::new(None))
  }

  fn with(amount: Amount) -> Self {
    Self {
      amount,
      variant: ProgressVariant::default().into(),
      size: ProgressSize::default().into(),
      label: None,
      label_hidden: false,
      description: None,
      show_value: false,
      top_bar: false,
      width: None,
      states: Vec::new(),
      rules: Recipe::new(),
      id: None,
      key: None,
    }
  }

  /// How far the work is, in its range: it then knows.
  pub fn value(mut self, value: impl Into<f64>) -> Self {
    self.amount.value = Some(value.into());
    self
  }

  /// The least value: none of the work done. 0 when not given.
  pub fn min(mut self, min: impl Into<f64>) -> Self {
    self.amount.min = min.into();
    self
  }

  /// The greatest value: the whole of the work. 1 when not given: the value is then a fraction of one.
  pub fn max(mut self, max: impl Into<f64>) -> Self {
    self.amount.max = max.into();
    self
  }

  /// A [`ProgressVariant`], or a variant the theme's recipe names.
  pub fn variant(mut self, variant: impl Into<Name>) -> Self {
    self.variant = variant.into();
    self
  }

  /// A [`ProgressSize`], or a size the theme's recipe names.
  pub fn size(mut self, size: impl Into<Name>) -> Self {
    self.size = size.into();
    self
  }

  /// What the work is, over the start of the rail, and what the progress is called.
  pub fn label(mut self, label: &str) -> Self {
    self.label = Some(Arc::from(label));
    self
  }

  /// Whether the label is said to tooling and not drawn: a bar whose work the text beside it already says.
  pub fn label_hidden(mut self, hidden: bool) -> Self {
    self.label_hidden = hidden;
    self
  }

  /// The line under the rail: what is left, or what the work is doing, "2 minutes left". It describes the bar to
  /// tooling.
  pub fn description(mut self, description: &str) -> Self {
    self.description = Some(Arc::from(description));
    self
  }

  /// Whether the value is said over the end of the rail: as a percentage, or
  /// as [`Progress::value_text`] writes it. A progress that does not know how far it
  /// is says none. Off unless told, as the design's bar draws none; a
  /// [`RingProgress`] says its value unless told, as the design's ring does.
  pub fn show_value(mut self, show: bool) -> Self {
    self.show_value = show;
    self
  }

  /// Writes the value as the app does, given the value as it is: `|done| format!("{done} of 128")`. Not given, its
  /// share of the range as a percentage, "62%". It is what tooling reads of the value too.
  pub fn value_text(mut self, text: impl Fn(f64) -> String + Send + Sync + 'static) -> Self {
    self.amount.value_text = Some(Arc::new(text));
    self
  }

  /// Whether it is the thin bar across the top of a window or of a surface:
  /// 3 high, with no rail under what is filled, as wide as what holds it.
  /// Put it first in what it is the top of.
  pub fn top_bar(mut self, top_bar: bool) -> Self {
    self.top_bar = top_bar;
    self
  }

  /// How wide the progress is: 240 when not given, and all the room there is for a top bar.
  pub fn width(mut self, width: impl Into<Length>) -> Self {
    self.width = Some(width.into());
    self
  }

  /// Puts the progress 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 progress over what the theme gives it.
  pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
    self.rules = self.rules.base(part, style);
    self
  }

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

  /// The id of the root: the progress with its label.
  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 progress in `theme`. Converting a progress into an element
  /// does this in the theme of what is being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    let mut rules = self.rules;
    if let Some(width) = self.width {
      rules = rules.base(ProgressPart::Root, |s| s.width(width));
    }
    let case = Case {
      variant: Some(self.variant),
      size: Some(self.size),
      density: None,
      breakpoint: super::current_breakpoint(),
      states: self.states,
    }
    .state(ProgressState::Indeterminate, self.amount.value.is_none())
    .state(ProgressState::TopBar, self.top_bar);
    let view = ProgressView {
      label: self.label,
      label_hidden: self.label_hidden,
      description: self.description,
      show_value: self.show_value,
      variant: self.variant,
      size: self.size,
      top_bar: self.top_bar,
      reduced_motion: theme.reduced_motion(),
      recipe: theme
        .resolve::<Progress>(&case, Some(&rules))
        .owned_by(self.id.as_ref()),
      amount: self.amount,
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<Progress>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

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

/// A progress bar as a renderer sees it: what it was given, the style of its
/// parts, and its parts ready to be put together.
pub struct ProgressView {
  pub label: Option<Arc<str>>,
  /// Whether the label is said to tooling and not drawn.
  pub label_hidden: bool,
  /// The line under the rail.
  pub description: Option<Arc<str>>,
  pub show_value: bool,
  pub variant: Name,
  pub size: Name,
  pub top_bar: bool,
  /// Whether motion is reduced: a progress that does not know how far it is then stands still.
  pub reduced_motion: bool,
  /// The style of each part of this progress.
  pub recipe: ResolvedRecipe,
  amount: Amount,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

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

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

  /// The value as it was given; `None` while it is not known.
  pub fn value(&self) -> Option<f64> {
    self.amount.value()
  }

  /// The least value.
  pub fn min(&self) -> f64 {
    self.amount.min
  }

  /// The greatest value.
  pub fn max(&self) -> f64 {
    self.amount.max
  }

  /// How much of the work is done, from 0 to 1; `None` while it is not known.
  pub fn fraction(&self) -> Option<f32> {
    self.amount.fraction()
  }

  /// The value as it is written: a percentage, or what the app's `value_text` writes. `None` while it is not known.
  pub fn value_text(&self) -> Option<String> {
    self.amount.text()
  }

  /// The root in the style of its part, saying what it is to tooling that reads the tree, with nothing in it yet.
  pub fn root(&self) -> crate::components::Column {
    let mut root = crate::components::Column::new().part(&self.part(ProgressPart::Root));
    root = describe(root, self.label.as_deref(), self.description.as_deref(), &self.amount);
    if let Some(id) = &self.id {
      root = root.id(id.clone());
    }
    if let Some(key) = &self.key {
      root = root.key(key.clone());
    }
    root
  }

  /// The label and the value over the rail, each where it is given: the label at the start, the value at the end.
  /// `None` where there is neither.
  pub fn header(&self) -> Option<Row> {
    let value = self.show_value.then(|| self.value_text()).flatten();
    let shown = self.label.as_ref().filter(|_| !self.label_hidden);
    if shown.is_none() && value.is_none() {
      return None;
    }
    let label = self.part(ProgressPart::Label);
    // What holds the label takes the room there is, so that the value stands at the end with no label too. A
    // label longer than the room is cut with an ellipsis before the value.
    let mut start = Row::new()
      .flex_full(1.0, 1.0, Some(0.0))
      .min_width(Dimension::Px(0.0))
      .part(&label);
    if let Some(text) = shown {
      start = start.child(label.text(text).nowrap().text_overflow(TextOverflow::Elipsis));
    }
    let mut header = Row::new()
      .align_items(Alignment::Center)
      .part(&self.part(ProgressPart::Header))
      .child(start);
    if let Some(text) = value {
      let part = self.part(ProgressPart::Value);
      header = header.child(Row::new().part(&part).child(part.text(&text).nowrap()));
    }
    Some(header)
  }

  /// The rail with what is filled of it: as long as what is done, its width a share of the rail's, which a
  /// transition the recipe gives it moves. Of a progress that does not know how far it is, the room before the
  /// segment and the segment, crossing the rail in [`PROGRESS_PERIOD`] or standing still while motion is reduced.
  pub fn track(&self) -> Row {
    let track = Row::new().part(&self.part(ProgressPart::Track));
    let fill = Row::new().part(&self.part(ProgressPart::Fill));
    match self.fraction() {
      // Keyed, so that a bar that comes to know its value grows from nothing rather than from the segment.
      Some(fraction) => track.child(fill.key("fill").width(Dimension::Pct(fraction * 100.0))),
      None => {
        let mut lead = Row::new().key("lead").flex_shrink(0.0);
        let mut segment = fill.key("segment").flex_shrink(0.0);
        if self.reduced_motion {
          lead = lead.width(Dimension::Pct(STILL_LEAD));
          segment = segment.width(Dimension::Pct(SEGMENT));
        } else {
          let crossing = |keyframes| {
            Animation::new(keyframes)
              .duration(PROGRESS_PERIOD)
              .easing(Easing::Linear)
              .infinite()
          };
          lead = lead.width(Dimension::Pct(0.0)).animation(crossing(PROGRESS_LEAD));
          segment = segment
            .width(Dimension::Pct(SEGMENT))
            .animation(crossing(PROGRESS_SEGMENT));
        }
        track.child(lead).child(segment)
      }
    }
  }

  /// The line under the rail, where it has one.
  pub fn description(&self) -> Option<Row> {
    let description = self.description.as_ref()?;
    let part = self.part(ProgressPart::Description);
    Some(
      Row::new()
        .width(Dimension::Pct(100.0))
        .part(&part)
        .child(part.text(description).width(Dimension::Pct(100.0))),
    )
  }

  /// How the default renderer builds a progress: the header, where there is one, over the rail, and the
  /// description under it.
  pub fn render(self) -> Element {
    let mut root = self.root();
    if let Some(header) = self.header() {
      root = root.child(header);
    }
    root = root.child(self.track());
    if let Some(description) = self.description() {
      root = root.child(description);
    }
    root.into()
  }
}

/// `node` said to be a progress bar to tooling that reads the tree: called `label` and described by `description`,
/// with its value, its least, its greatest and the value's text written as a [`Meter`](super::Meter) writes them,
/// and no value while it does not know it.
fn describe<N: Describe>(node: N, label: Option<&str>, description: Option<&str>, amount: &Amount) -> N {
  let mut node = node.describe_as("a11y_role", "progressbar");
  if let Some(label) = label {
    node = node.describe_as("a11y_name", label);
  }
  if let Some(description) = description {
    node = node.describe_as("a11y_description", description);
  }
  if let Some(value) = amount.value() {
    node = node
      .describe_as("a11y_valuenow", &number(value))
      .describe_as("a11y_valuemin", &number(amount.min))
      .describe_as("a11y_valuemax", &number(amount.max));
    if let Some(text) = amount.text() {
      node = node.describe_as("a11y_valuetext", &text);
    }
  }
  node
}

/// What [`describe`] annotates: a column or a stack.
trait Describe: Sized {
  fn describe_as(self, name: &str, value: &str) -> Self;
}

impl Describe for crate::components::Column {
  fn describe_as(self, name: &str, value: &str) -> Self {
    self.describe(name, value)
  }
}

impl Describe for Stack {
  fn describe_as(self, name: &str, value: &str) -> Self {
    self.describe(name, value)
  }
}

impl crate::ui::Styled for Progress {
  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 Progress {
  const NAME: &'static str = "progress";
  type Renderer = ProgressRenderer;

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

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

  /// The design's progress (`pencil/lurq-design-system.pen`, Progress,
  /// Loader/Progress Labeled, Loader/Linear, Loader/Top Bar): a rail of 240
  /// by 8, round, in the secondary color, filled in the primary color, or in
  /// the success, warning or destructive one. The rail is 6 under a label
  /// and in a dialog, 4 in a row of a list. Over it, 8 above, the label in
  /// the label's type at the start and the value at the end in the mono type
  /// of 11 in the muted foreground. The top bar is 3 high with no rail, its
  /// fill square where it starts and round 2 where it ends.
  fn recipe() -> Recipe {
    use PaletteColor::*;
    use ProgressPart::{Description, Fill, Header, Label, Root, Track, Value};
    Recipe::new()
      .base(Root, |s| {
        s.width(240.0)
          .max_width(Length::Fill)
          .gap(8.0)
          .foreground(Foreground)
      })
      // The line under the rail, as a meter's: 12 in the muted color, 8 under the rail.
      .base(Description, |s| {
        s.typography(TypographyStyle::Body)
          .font_size(12.0)
          .foreground(MutedForeground)
      })
      .base(Header, |s| s.width(Length::Fill).gap(8.0))
      .base(Label, |s| s.typography(TypographyStyle::Label))
      .base(Value, |s| {
        s.typography(TypographyStyle::Mono)
          .font_size(11.0)
          .foreground(MutedForeground)
      })
      .base(Track, |s| {
        s.width(Length::Fill)
          .height(8.0)
          .radius(RadiusSize::Full)
          .background(Secondary)
      })
      .base(Fill, |s| {
        s.height(Length::Fill)
          .radius(RadiusSize::Full)
          .background(Primary)
          .transition(PartTransition::new(Transition::width(), MotionDuration::Slow))
      })
      .variant(ProgressVariant::Info, Fill, |s| s.background(Info))
      .variant(ProgressVariant::Success, Fill, |s| s.background(Success))
      .variant(ProgressVariant::Warning, Fill, |s| s.background(Warning))
      .variant(ProgressVariant::Destructive, Fill, |s| s.background(Destructive))
      .size(ProgressSize::Sm, Track, |s| s.height(4.0))
      .size(ProgressSize::Md, Track, |s| s.height(6.0))
      .size(ProgressSize::Lg, Track, |s| s.height(8.0))
      .state(ProgressState::TopBar, Root, |s| s.width(Length::Fill))
      .state(ProgressState::TopBar, Track, |s| {
        s.height(3.0).radius(0.0).background(Color::new(0, 0, 0, 0))
      })
      // Square where it starts, at the window's edge, and round where it ends.
      .state(ProgressState::TopBar, Fill, |s| s.corners(0.0, 2.0, 2.0, 0.0))
  }
}

/// The parts of a ring progress a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RingProgressPart {
  /// The ring with its value in the middle: a square.
  Root,
  /// The ring under the arc: a round box over the whole of the root, its inside border the ring, as wide as the
  /// ring is and in the color of what is not done.
  Track,
  /// The arc of what is done, over the track: a round box with an inside border of one dash, from the top and
  /// clockwise. Its border's color is the arc's; its width is the track's.
  Fill,
  /// The middle, which holds the value and paints nothing: as large as the ring is not wide.
  Middle,
  /// How far it is, in the middle.
  Value,
}

names!(RingProgressPart {
  Root => "root",
  Track => "track",
  Fill => "fill",
  Middle => "middle",
  Value => "value",
});

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

/// A ring progress: how far a piece of work is, around a circle, with the
/// value in the middle. A storage quota, the share of a goal, an export in a
/// card.
///
/// ```
/// use lurq::ui::{ProgressVariant, RingProgress};
///
/// let export = RingProgress::new(0.7).label("Export");
/// let quota = RingProgress::new(96.0)
///   .max(128.0)
///   .variant(ProgressVariant::Warning)
///   .value_text(|used| format!("{used} GB"));
/// ```
///
/// It takes the [`ProgressVariant`]s and the [`ProgressSize`]s of a
/// [`Progress`]. The ring always knows how far the work is: what does not
/// is a spinner's. To tooling it is a `progressbar`, as a progress is.
///
/// The ring is two round borders one over the other, with nothing painted
/// in the middle: the track's, and over it the fill's, cut to one dash as
/// long as the arc. The arc moves round to a new value over the theme's slow
/// duration, at once while motion is reduced.
pub struct RingProgress {
  amount: Amount,
  variant: Name,
  size: Name,
  label: Option<Arc<str>>,
  show_value: bool,
  states: Vec<Name>,
  rules: Recipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl RingProgress {
  /// A ring at `value`, a fraction of one unless [`min`](Self::min) and [`max`](Self::max) say another range.
  pub fn new(value: impl Into<f64>) -> Self {
    Self {
      amount: Amount::new(Some(value.into())),
      variant: ProgressVariant::default().into(),
      size: ProgressSize::default().into(),
      label: None,
      show_value: true,
      states: Vec::new(),
      rules: Recipe::new(),
      id: None,
      key: None,
    }
  }

  /// How far the work is, in its range.
  pub fn value(mut self, value: impl Into<f64>) -> Self {
    self.amount.value = Some(value.into());
    self
  }

  /// The least value: none of the work done. 0 when not given.
  pub fn min(mut self, min: impl Into<f64>) -> Self {
    self.amount.min = min.into();
    self
  }

  /// The greatest value: the whole of the work. 1 when not given.
  pub fn max(mut self, max: impl Into<f64>) -> Self {
    self.amount.max = max.into();
    self
  }

  /// A [`ProgressVariant`], or a variant the theme's recipe names.
  pub fn variant(mut self, variant: impl Into<Name>) -> Self {
    self.variant = variant.into();
    self
  }

  /// A [`ProgressSize`], or a size the theme's recipe names.
  pub fn size(mut self, size: impl Into<Name>) -> Self {
    self.size = size.into();
    self
  }

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

  /// Whether the value is said in the middle: as a percentage, or as [`RingProgress::value_text`] writes it. It is
  /// unless told otherwise, as the design's ring says it; a [`Progress`] bar says none unless told.
  pub fn show_value(mut self, show: bool) -> Self {
    self.show_value = show;
    self
  }

  /// Writes the value as the app does, given the value as it is. Not given, its share of the range as a
  /// percentage.
  pub fn value_text(mut self, text: impl Fn(f64) -> String + Send + Sync + 'static) -> Self {
    self.amount.value_text = Some(Arc::new(text));
    self
  }

  /// Puts the ring 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 ring over what the theme gives it.
  pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
    self.rules = self.rules.base(part, style);
    self
  }

  /// Lays rules over the theme's recipe for this ring.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// The id of the root.
  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 ring in `theme`. Converting a ring into an element does this
  /// in the theme of what is being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    let case = Case {
      variant: Some(self.variant),
      size: Some(self.size),
      density: None,
      breakpoint: super::current_breakpoint(),
      states: self.states,
    };
    let view = RingProgressView {
      label: self.label,
      show_value: self.show_value,
      variant: self.variant,
      size: self.size,
      recipe: theme
        .resolve::<RingProgress>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      amount: self.amount,
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<RingProgress>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

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

/// A ring progress as a renderer sees it.
pub struct RingProgressView {
  pub label: Option<Arc<str>>,
  pub show_value: bool,
  pub variant: Name,
  pub size: Name,
  /// The style of each part of this ring.
  pub recipe: ResolvedRecipe,
  amount: Amount,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

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

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

  /// The value, kept between nothing and the greatest.
  pub fn value(&self) -> f64 {
    self.amount.value().unwrap_or(0.0)
  }

  /// The least value.
  pub fn min(&self) -> f64 {
    self.amount.min
  }

  /// The greatest value.
  pub fn max(&self) -> f64 {
    self.amount.max
  }

  /// How much of the work is done, from 0 to 1.
  pub fn fraction(&self) -> f32 {
    self.amount.fraction().unwrap_or(0.0)
  }

  /// The value as it is said: a percentage, or what the app's format says.
  pub fn value_text(&self) -> String {
    self.amount.text().unwrap_or_default()
  }

  /// The root in the style of its part, saying what it is to tooling that reads the tree, with nothing in it yet.
  /// What is in it is laid over one another, in the middle.
  pub fn root(&self) -> Stack {
    let mut root = Stack::new()
      .stack_align(StackAlignment::Center)
      .part(&self.part(RingProgressPart::Root));
    root = describe(root, self.label.as_deref(), None, &self.amount);
    if let Some(id) = &self.id {
      root = root.id(id.clone());
    }
    if let Some(key) = &self.key {
      root = root.key(key.clone());
    }
    root
  }

  /// The side of the ring in pixels: the width the recipe gives its root. `None` where it gives none in pixels.
  pub fn side(&self) -> Option<f32> {
    match self.part(RingProgressPart::Root).rest().width?.resolve(self.theme())? {
      Dimension::Px(side) => Some(side),
      _ => None,
    }
  }

  /// How wide the ring is: the width of the track's border, 0 where it has none.
  pub fn thickness(&self) -> f32 {
    self
      .part(RingProgressPart::Track)
      .rest()
      .border
      .map_or(0.0, |border| border.width.resolve(&self.theme().border_sizes()))
  }

  /// The ring under the arc, in the style of the track.
  pub fn track(&self) -> Row {
    Row::new().part(&self.part(RingProgressPart::Track))
  }

  /// The arc of what is done, in the style of the fill, with an inside border as wide as the track's in the fill's
  /// border color, of one dash: as long as the arc, from the top and clockwise, with a gap of the rest of the
  /// circle. A border's dashes run along its outline from the start of its top edge, which on a circle is the top,
  /// and the period is fitted to the outline: a dash and a gap that make the circle are one dash of it. With
  /// nothing done the dash is too short to see and has no color, so that a transition to a value grows the arc
  /// from the top as it fades in.
  pub fn arc(&self) -> Row {
    let part = self.part(RingProgressPart::Fill);
    let arc = Row::new().part(&part);
    let (Some(side), Some(border)) = (self.side(), part.rest().border) else {
      return arc;
    };
    let circle = std::f32::consts::PI * side;
    let fraction = self.fraction();
    let (color, length) = if fraction > 0.0 {
      (border.color, circle * fraction)
    } else {
      (BackgroundColor::Color(Color::new(0, 0, 0, 0)), NO_ARC)
    };
    // A whole circle is a dash with no gap: a solid line.
    arc.border(Border::inside(self.thickness(), color).dash(length, circle - length))
  }

  /// The middle, in the style of its part, with the value in it where it is shown.
  pub fn middle(&self) -> Row {
    let mut middle = Row::new()
      .align_items(Alignment::Center)
      .justify(Justify::Center)
      .part(&self.part(RingProgressPart::Middle));
    if self.show_value {
      let part = self.part(RingProgressPart::Value);
      middle = middle.child(Row::new().part(&part).child(part.text(&self.value_text()).nowrap()));
    }
    middle
  }

  /// How the default renderer builds a ring: the track, the arc over it, and the middle with the value.
  pub fn render(self) -> Element {
    self
      .root()
      .child(self.track())
      .child(self.arc())
      .child(self.middle())
      .into()
  }
}

/// How long the arc of a ring with nothing done is, in pixels: a dash, so that the border stays dashed and a
/// transition to a value grows it from the top. It has no color.
const NO_ARC: f32 = 0.01;

impl crate::ui::Styled for RingProgress {
  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 RingProgress {
  const NAME: &'static str = "ring_progress";
  type Renderer = RingProgressRenderer;

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

  /// The design's ring progress (`pencil/lurq-design-system.pen`, Ring
  /// Progress): a ring of 72 whose width is a tenth of its side, in the
  /// secondary color, with what is done over it in the primary color from the
  /// top and clockwise, and the value in the middle in the label's type of 13
  /// at a weight of 600. The variants color the arc as they color a bar; the
  /// smaller rings are 56 and 40, their value 12 and 11. The arc moves round,
  /// and fades in from nothing, over the theme's slow duration.
  fn recipe() -> Recipe {
    use PaletteColor::*;
    use RingProgressPart::{Fill, Middle, Root, Track, Value};

    // A border; `Border` is a color of the palette here.
    use crate::node::border::Border as Stroke;
    let middle = |side: f32| move |s: super::PartStyle| s.square(side * 0.8);
    let ring = |side: f32| move |s: super::PartStyle| s.border(Stroke::inside(side / 10.0, Secondary));
    let round = |s: super::PartStyle| s.width(Length::Fill).height(Length::Fill).radius(RadiusSize::Full);
    Recipe::new()
      .base(Root, |s| s.square(72.0).foreground(Foreground))
      .base(Track, |s| round(s).border(Stroke::inside(7.2, Secondary)))
      .base(Fill, |s| {
        round(s)
          .border(Stroke::inside(7.2, Primary))
          .transition(PartTransition::new(Transition::border_dash(), MotionDuration::Slow))
          .transition(PartTransition::new(Transition::border_color(), MotionDuration::Slow))
      })
      .base(Middle, |s| s.square(57.6))
      .base(Value, |s| {
        s.typography(TypographyStyle::Label)
          .font_size(13.0)
          .weight(FontWeight::SemiBold)
      })
      .variant(ProgressVariant::Info, Fill, |s| s.border(Stroke::inside(7.2, Info)))
      .variant(ProgressVariant::Success, Fill, |s| {
        s.border(Stroke::inside(7.2, Success))
      })
      .variant(ProgressVariant::Warning, Fill, |s| {
        s.border(Stroke::inside(7.2, Warning))
      })
      .variant(ProgressVariant::Destructive, Fill, |s| {
        s.border(Stroke::inside(7.2, Destructive))
      })
      .size(ProgressSize::Sm, Root, |s| s.square(40.0))
      .size(ProgressSize::Sm, Track, ring(40.0))
      .size(ProgressSize::Sm, Middle, middle(40.0))
      .size(ProgressSize::Sm, Value, |s| s.font_size(11.0))
      .size(ProgressSize::Md, Root, |s| s.square(56.0))
      .size(ProgressSize::Md, Track, ring(56.0))
      .size(ProgressSize::Md, Middle, middle(56.0))
      .size(ProgressSize::Md, Value, |s| s.font_size(12.0))
  }
}