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
//! A checkbox: a choice that is made or not, among others a form takes at once.

use std::sync::Arc;

use super::{
  icons, names,
  recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
  shared::{Choice, Orientation, beside_first_line, control_label, fading, glyph, label_top, pressable},
  switch::own_press,
  theme::{Themed, current_theme},
};
use crate::{
  app::theme::{BorderSize, IconSize, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
  components::{self, Column, Row},
  core::{ElementRef, Signal, SignalValue},
  layout::{Alignment, layout_kind::Justify},
  node::{CursorIcon, Element, border::Border, dimension::Dimension},
};

/// The parts of a checkbox a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CheckboxPart {
  /// The box and its label, side by side.
  Root,
  /// What is pressed: the square that holds the mark.
  Box,
  /// The mark in the box: a check while it is checked, a dash while it is indeterminate.
  Indicator,
  /// Its text, beside the box.
  Label,
}

names!(CheckboxPart {
  Root => "root",
  Box => "box",
  Indicator => "indicator",
  Label => "label",
});

/// The states of a checkbox a recipe styles, besides what the pointer and
/// the keyboard do to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CheckboxState {
  /// It is checked, and not indeterminate.
  Checked,
  /// Some of what it stands for is checked and some is not: a box over a list.
  Indeterminate,
  /// What it holds is wrong: a form says so.
  Invalid,
  /// It takes no input.
  Disabled,
  /// It is pressed as a whole: its root is what is pressed and focused, with the box and the label in it.
  Whole,
}

names!(CheckboxState {
  Checked => "checked",
  Indeterminate => "indeterminate",
  Invalid => "invalid",
  Disabled => "disabled",
  Whole => "whole",
});

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

/// A checkbox: a choice that is made or not, among others a form takes at
/// once. Send crash reports, keep me signed in, a row of a list picked.
///
/// ```
/// use lurq::ui::Checkbox;
///
/// let reports = Checkbox::new("Send crash reports").checked(true).on_change(|checked| println!("{checked}"));
/// // Bound to the app's signal, which a press turns.
/// # let signed_in = lurq::core::Signal::new(false);
/// let keep = Checkbox::new("Keep me signed in").bind(signed_in);
/// // The box over a list of which some are picked: a press of it picks them all.
/// let all = Checkbox::new("Select all").indeterminate(true);
/// // The box alone, in a row of a table: its label is still what it is called.
/// let row = Checkbox::new("Select blur.rs").label_hidden(true);
/// ```
///
/// A checkbox does not keep whether it is checked: the app says so with
/// [`Checkbox::checked`], and is told of a press with
/// [`Checkbox::on_change`], or binds it to a signal with [`Checkbox::bind`].
/// A press of its label is a press of the checkbox, and a press of either is
/// the checkbox's alone: a row around it that is pressed is not.
/// [`Checkbox::whole`] makes the box and its label one control, its id on the
/// whole. [`Checkbox::mark_only`] draws the box alone, for a row that is
/// pressed as a whole and says it is checked.
pub struct Checkbox {
  label: Arc<str>,
  label_hidden: bool,
  label_wraps: bool,
  whole: bool,
  mark_only: bool,
  checked: bool,
  indeterminate: bool,
  invalid: bool,
  disabled: bool,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  on_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
  /// Called as the focus leaves the box: for a form's checkbox, 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>>,
  element: Option<ElementRef>,
}

impl Checkbox {
  /// A checkbox called `label`, with the label beside it.
  pub fn new(label: &str) -> Self {
    Self {
      label: Arc::from(label),
      label_hidden: false,
      label_wraps: false,
      whole: false,
      mark_only: false,
      checked: false,
      indeterminate: false,
      invalid: false,
      disabled: false,
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      on_change: Vec::new(),
      on_leave: Vec::new(),
      name: None,
      id: None,
      key: None,
      element: None,
    }
  }

  /// Whether the checkbox is its box alone. Its label stays what it is called.
  pub fn label_hidden(mut self, hidden: bool) -> Self {
    self.label_hidden = hidden;
    self
  }

  /// Whether the label goes on to more lines within the width the checkbox is given, the box beside its first
  /// line and centered on it: a label that may be long, such as one that names a folder. The checkbox is then no
  /// wider than what holds it. Not unless told: the label is on one line.
  pub fn label_wraps(mut self, wraps: bool) -> Self {
    self.label_wraps = wraps;
    self
  }

  /// Whether the checkbox is checked.
  pub fn checked(mut self, checked: bool) -> Self {
    self.checked = checked;
    self
  }

  /// Checked while `checked` is true, which a press turns. Handlers of [`Checkbox::on_change`] are told of a press
  /// after the signal is set, and not when the app sets it.
  pub fn bind(self, checked: Signal<bool>) -> Self {
    let set = checked.clone();
    let mut bound = self.checked(checked.get());
    bound.on_change.insert(0, Arc::new(move |next| set.set(next)));
    bound
  }

  /// Whether the checkbox is neither checked nor not: some of what it
  /// stands for is checked. It is drawn with a dash, whatever
  /// [`Checkbox::checked`] says, and a press of it asks for checked.
  pub fn indeterminate(mut self, indeterminate: bool) -> Self {
    self.indeterminate = indeterminate;
    self
  }

  /// Whether what the checkbox holds is wrong: its edge is the destructive color.
  pub fn invalid(mut self, invalid: bool) -> Self {
    self.invalid = invalid;
    self
  }

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

  /// Puts the checkbox 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
  }

  /// Called on a press, with what the checkbox is to be: checked if it was
  /// not, or if it was indeterminate. A second handler is called after the first.
  pub fn on_change(mut self, handler: impl Fn(bool) + Send + Sync + 'static) -> Self {
    self.on_change.push(Arc::new(handler));
    self
  }

  /// Styles one part of this checkbox 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 checkbox: what the
  /// component it is in says of the checkbox in this place.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// Draws the checkbox as it is under the pointer, held down 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 checkbox has in the form it is in: a checked one gives the form `on` under it, as a checkbox of
  /// the engine's does, and one that is not checked gives nothing.
  #[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 box: a form's checkbox 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
  }

  /// Whether the box and its label are one control: what is pressed,
  /// focused and ringed is the whole of them, one stop of Tab, and its id is
  /// on the whole, the box, its mark and the label named after it (`x-box`,
  /// `x-indicator`, `x-label`). Not unless told: the box is what is pressed,
  /// and has the id.
  pub fn whole(mut self, whole: bool) -> Self {
    self.whole = whole;
    self
  }

  /// Whether the checkbox is its mark alone: the box with its check or its
  /// dash, in the recipe's parts and states, for a row that is pressed as a
  /// whole (a filter's option). It takes no press, no focus and no stop of
  /// Tab, has no label, and is hidden from what reads the tree: the row around
  /// it is the control, and says that it is checked. Its id is on the box, its
  /// check `x-indicator`. Not unless told.
  pub fn mark_only(mut self, mark_only: bool) -> Self {
    self.mark_only = mark_only;
    self
  }

  /// Refers to what is pressed and focused once it is laid out: the box, or
  /// the whole where it is [`whole`](Self::whole). What a screen moves the
  /// focus to, or a popup hangs from. The box where it is
  /// [`mark_only`](Self::mark_only).
  pub fn element_ref(mut self, element: ElementRef) -> Self {
    self.element = Some(element);
    self
  }

  /// The id of the box: what is pressed. The id of the whole where it is
  /// [`whole`](Self::whole).
  pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
    self.id = Some(id.into());
    self
  }

  /// What tells the checkbox apart from those beside it, where two have one label.
  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.key = Some(key.into());
    self
  }

  /// Builds the checkbox in `theme`. Converting a checkbox 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(CheckboxState::Checked, self.checked && !self.indeterminate)
    .state(CheckboxState::Indeterminate, self.indeterminate)
    .state(CheckboxState::Invalid, self.invalid)
    .state(CheckboxState::Disabled, self.disabled)
    .state(CheckboxState::Whole, self.whole);
    // Its mark alone, the id is on the box, and the mark in it is a part named after it.
    let recipe = theme.resolve::<Checkbox>(&case, Some(&self.rules));
    let recipe = if self.mark_only {
      recipe.rooted_at(CheckboxPart::Box)
    } else {
      recipe
    };
    let view = CheckboxView {
      label: self.label,
      label_hidden: self.label_hidden,
      label_wraps: self.label_wraps,
      whole: self.whole,
      mark_only: self.mark_only,
      checked: self.checked,
      indeterminate: self.indeterminate,
      invalid: self.invalid,
      disabled: self.disabled,
      recipe: recipe.owned_by(self.id.as_ref()),
      forced: self.forced,
      on_change: self.on_change,
      on_leave: self.on_leave,
      name: self.name,
      id: self.id,
      key: self.key,
      element: self.element,
    };
    match theme.renderer::<Checkbox>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

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

/// A checkbox as a renderer sees it: what it was given, the style of its
/// parts, and its behavior ready to be dressed.
pub struct CheckboxView {
  pub label: Arc<str>,
  pub label_hidden: bool,
  /// Whether the label goes on to more lines, the box beside its first line.
  pub label_wraps: bool,
  /// Whether the box and its label are one control, its id on the whole.
  pub whole: bool,
  /// Whether the checkbox is its mark alone, with no press, focus or label.
  pub mark_only: bool,
  pub checked: bool,
  pub indeterminate: bool,
  pub invalid: bool,
  pub disabled: bool,
  /// The style of each part of this checkbox.
  pub recipe: ResolvedRecipe,
  forced: Option<Interaction>,
  on_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
  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>>,
  element: Option<ElementRef>,
}

impl CheckboxView {
  /// The style of a part, as this checkbox 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()
  }

  /// What a press does: every handler is told what the checkbox is to be.
  fn press(&self) -> Option<impl Fn() + Send + Sync + Clone + 'static> {
    let (handlers, next) = (self.on_change.clone(), self.indeterminate || !self.checked);
    (!handlers.is_empty() && !self.disabled).then(|| {
      move || {
        for handler in &handlers {
          handler(next);
        }
      }
    })
  }

  /// The checkbox's behavior with the style of its box: the element that is
  /// pressed, focused and disabled, with nothing in it yet. It is a checkbox
  /// to what reads the tree, called by its label, and says whether it is
  /// checked: `mixed` while it is indeterminate.
  pub fn control(&self) -> components::Button {
    self.pressed(CheckboxPart::Box)
  }

  /// The behavior of a checkbox pressed as a whole, with the style of its
  /// root: what is pressed, focused and ringed, with nothing in it yet, the
  /// box and the label to go in it. What [`control`](Self::control) is
  /// otherwise.
  pub fn whole_root(&self) -> components::Button {
    self
      .pressed(CheckboxPart::Root)
      .justify(Justify::Start)
      .align_items(Alignment::Center)
  }

  /// The checkbox's behavior with the style of `part`. A press of it is its own: it does not reach what is around it.
  fn pressed(&self, part: CheckboxPart) -> components::Button {
    let checked = match (self.indeterminate, self.checked) {
      (true, _) => "mixed",
      (false, true) => "true",
      (false, false) => "false",
    };
    let mut control = pressable(&self.part(part), self.disabled)
      .describe("a11y_role", "checkbox")
      .describe("a11y_name", self.label.clone())
      .describe("a11y_checked", checked)
      .on_click(own_press(self.press()));
    // The box is no checkbox of the engine's: it says itself what it gives the form.
    #[cfg(feature = "form")]
    if let Some(name) = &self.name {
      control = control
        .name(name.clone())
        .form_value(self.checked.then(|| Arc::from("on")));
    }
    if !self.on_leave.is_empty() {
      let leave = self.on_leave.clone();
      control = control.on_blur(move || {
        for handler in &leave {
          handler();
        }
      });
    }
    if let Some(id) = &self.id {
      control = control.id(id.clone());
    }
    if let Some(key) = &self.key {
      control = control.key(key.clone());
    }
    if let Some(element) = &self.element {
      control = control.ref_element(element.clone());
    }
    control
  }

  /// The box alone with its mark, in the style of its part: nothing pressed,
  /// focused or read by tooling, its id, its key and its element ref on it.
  /// What [`render`](Self::render) draws where the checkbox is
  /// [`mark_only`](CheckboxView::mark_only).
  pub fn mark_alone(&self) -> Row {
    let mut square = Row::new()
      .align_items(Alignment::Center)
      .justify(Justify::Center)
      .flex_shrink(0.0)
      .part(&self.part(CheckboxPart::Box))
      .describe("a11y_hidden", "true")
      .with_children(self.indicator());
    if let Some(id) = &self.id {
      square = square.id(id.clone());
    }
    if let Some(key) = &self.key {
      square = square.key(key.clone());
    }
    if let Some(element) = &self.element {
      square = square.ref_element(element.clone());
    }
    square
  }

  /// The mark in the box in the style of its part: the theme's dash while
  /// the checkbox is indeterminate, its check while it is checked, and
  /// nothing while it is neither.
  pub fn indicator(&self) -> Option<Element> {
    let name = match (self.indeterminate, self.checked) {
      (true, _) => icons::MINUS,
      (false, true) => icons::CHECK,
      (false, false) => return None,
    };
    Some(glyph(&self.part(CheckboxPart::Indicator), Name::new(name), false))
  }

  /// The label in the style of its part: `None` where it is hidden.
  fn label(&self) -> Option<Row> {
    if self.label_hidden {
      return None;
    }
    let part = self.part(CheckboxPart::Label);
    let wraps = self
      .label_wraps
      .then(|| label_top(&part, &self.part(CheckboxPart::Box)));
    Some(control_label(&part, &self.label, wraps))
  }

  /// Whether the label is shown and goes on to more lines.
  fn wraps(&self) -> bool {
    self.label_wraps && !self.label_hidden
  }

  /// The box as it stands beside the label: held at the label's first line where the label wraps.
  fn beside_label(&self, square: impl Into<Element>) -> Element {
    if self.wraps() {
      beside_first_line(&self.part(CheckboxPart::Label), square).into()
    } else {
      square.into()
    }
  }

  /// How the default renderer builds a checkbox: the box with its mark, and the label beside it; pressed as a whole,
  /// both in what is pressed.
  pub fn render(self) -> Element {
    if self.mark_only {
      return self.mark_alone().into();
    }
    if self.whole {
      let square = Row::new()
        .align_items(Alignment::Center)
        .justify(Justify::Center)
        .part(&self.part(CheckboxPart::Box))
        .with_children(self.indicator());
      let root = self
        .whole_root()
        .child(self.beside_label(square))
        .with_children(self.label());
      return if self.wraps() {
        root
          .align_items(Alignment::Start)
          .max_width(Dimension::Pct(100.0))
          .into()
      } else {
        root.into()
      };
    }
    let mut control = self.control();
    if let Some(indicator) = self.indicator() {
      control = control.child(indicator);
    }
    let mut root = Row::new()
      .align_items(if self.wraps() {
        Alignment::Start
      } else {
        Alignment::Center
      })
      .part(&self.part(CheckboxPart::Root))
      .child(self.beside_label(control));
    if self.wraps() {
      root = root.max_width(Dimension::Pct(100.0));
    }
    if let Some(label) = self.label() {
      root = root.child(label.on_click(own_press(self.press())));
    }
    root.into()
  }
}

/// The inner edge of 1 the box has, in `color`.
fn edge(color: PaletteColor) -> Border {
  Border::inside(BorderSize::Sm, color)
}

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

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

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

  /// The design's checkbox (`pencil/lurq-design-system.pen`, Checkbox): a
  /// box of 16 with the small radius and an inner edge of 1 in the color of
  /// an input's edge, on the background. Checked or indeterminate it is
  /// filled and edged in the primary color, with a check or a dash of 12 in
  /// the color on it. An invalid one is edged in the destructive color; a
  /// disabled one is dimmed with its label, its box muted while it is empty.
  /// Its label is 8 beside it, in the body's type.
  fn recipe() -> Recipe {
    use CheckboxState::{Checked, Disabled, Indeterminate, Invalid};
    use PaletteColor::*;
    let (root, square, indicator, label) = (
      CheckboxPart::Root,
      CheckboxPart::Box,
      CheckboxPart::Indicator,
      CheckboxPart::Label,
    );
    let marked = |s: super::PartStyle| s.background(Primary).border(edge(Primary));
    Recipe::new()
      .base(root, |s| s.gap(8.0).foreground(Foreground))
      .base(square, |s| {
        fading(
          s.square(16.0)
            .radius(RadiusSize::Sm)
            .background(Background)
            .border(edge(Input))
            .cursor(CursorIcon::Pointer),
        )
      })
      .base(indicator, |s| s.square(IconSize::Xs).foreground(PrimaryForeground))
      .base(label, |s| {
        s.typography(TypographyStyle::Body).cursor(CursorIcon::Pointer)
      })
      .focus_visible(square, |s| s.focus_ring())
      .state(Checked, square, marked)
      .state(Indeterminate, square, marked)
      // After the marked box, so that an invalid one that is checked keeps the edge that says so.
      .state(Invalid, square, |s| s.border(edge(Destructive)))
      .state(Disabled, root, |s| s.opacity(OpacityLevel::Disabled))
      .state(Disabled, square, |s| s.background(Muted).cursor(CursorIcon::Default))
      .state(Disabled, label, |s| s.cursor(CursorIcon::Default))
      // A recipe has no case for a state that does not hold: a disabled box that is marked is filled again.
      .when(Selector::new().state(Checked).state(Disabled), square, |s| {
        s.background(Primary)
      })
      .when(Selector::new().state(Indeterminate).state(Disabled), square, |s| {
        s.background(Primary)
      })
      // Pressed as a whole: the root is what the pointer presses and the ring goes round, the box only drawn.
      .state(CheckboxState::Whole, root, |s| s.radius(RadiusSize::Sm).cursor(CursorIcon::Pointer))
      .when(Selector::new().state(CheckboxState::Whole).focus_visible(), root, |s| s.focus_ring())
      .when(Selector::new().state(CheckboxState::Whole).state(Disabled), root, |s| {
        s.cursor(CursorIcon::Default)
      })
  }
}

/// The parts of a group of checkboxes a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CheckboxGroupPart {
  /// The group: the checkboxes one under the other, or side by side.
  Root,
  /// What the group says of each checkbox in it: laid over the theme's recipe for a checkbox's root.
  Item,
}

names!(CheckboxGroupPart {
  Root => "root",
  Item => "item",
});

/// The states of a group of checkboxes a recipe styles. One of `Horizontal` and `Vertical` is on.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CheckboxGroupState {
  /// Its checkboxes stand side by side.
  Horizontal,
  /// Its checkboxes stand one under the other.
  Vertical,
}

names!(CheckboxGroupState {
  Horizontal => "horizontal",
  Vertical => "vertical",
});

/// The set `checked` with `value` taken out where it is in it, and put at its end where it is not.
pub(crate) fn toggled<T: PartialEq>(mut checked: Vec<T>, value: T) -> Vec<T> {
  match checked.iter().position(|held| *held == value) {
    Some(index) => {
      checked.remove(index);
    }
    None => checked.push(value),
  }
  checked
}

/// What turns a value in the signal a group of any number is bound to, and gives the new set.
pub(crate) type Turn<T> = Arc<dyn Fn(T) -> Vec<T> + Send + Sync>;

/// What turns a value in `signal`: takes it out where the signal has it, puts it at the end where it does not.
pub(crate) fn turning<T: Clone + PartialEq + Send + Sync + 'static>(signal: Signal<Vec<T>>) -> Turn<T>
where
  Vec<T>: SignalValue,
{
  Arc::new(move |value| {
    signal.update(|held| *held = toggled(std::mem::take(held), value));
    signal.get_untracked()
  })
}

/// What a press of a choice of a group of any number does: the signal the group is bound to is set to the new set,
/// and then every handler is told the whole new set. A group the app holds tells the set it would be.
pub(crate) fn toggling<T: Clone + PartialEq + Send + Sync + 'static>(
  value: T,
  checked: &[T],
  bound: Option<Turn<T>>,
  handlers: Vec<Arc<dyn Fn(&[T]) + Send + Sync>>,
) -> impl Fn() + Send + Sync + 'static {
  let checked = checked.to_vec();
  move || {
    let next = match &bound {
      Some(turn) => turn(value.clone()),
      None => toggled(checked.clone(), value.clone()),
    };
    for handler in &handlers {
      handler(&next);
    }
  }
}

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

/// Checkboxes over one list: those whose values the app holds are checked,
/// and a press of one adds its value or takes it out.
///
/// ```
/// use lurq::{core::Signal, ui::{CheckboxGroup, Choice, Orientation}};
///
/// # fn groups(days: Signal<Vec<u8>>) {
/// let days = CheckboxGroup::new(days, [(1, "Monday"), (2, "Tuesday"), (3, "Wednesday")])
///   .orientation(Orientation::Horizontal)
///   .on_change(|days| println!("{days:?}"));
/// // The app holds it, and is told the whole new set. A choice that cannot be made is drawn, dimmed, and takes
/// // nothing.
/// let scopes = CheckboxGroup::controlled(["read"], [
///   Choice::new("read", "Read"),
///   Choice::new("write", "Write"),
///   Choice::new("admin", "Admin").disabled(true),
/// ], |scopes| println!("{scopes:?}"));
/// # }
/// ```
///
/// Each checkbox is its own stop of Tab, and Space or Enter presses the one
/// the focus is on. A choice's icon is not drawn.
pub struct CheckboxGroup<T = ()> {
  choices: Vec<Choice<T>>,
  checked: Vec<T>,
  bound: Option<Turn<T>>,
  on_change: Vec<Arc<dyn Fn(&[T]) + Send + Sync>>,
  label: Option<Arc<str>>,
  orientation: Orientation,
  invalid: bool,
  disabled: bool,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl<T: Clone + PartialEq + Send + Sync + 'static> CheckboxGroup<T> {
  fn of(checked: Vec<T>, bound: Option<Turn<T>>, choices: impl IntoIterator<Item = impl Into<Choice<T>>>) -> Self {
    Self {
      choices: choices.into_iter().map(Into::into).collect(),
      checked,
      bound,
      on_change: Vec::new(),
      label: None,
      orientation: Orientation::Vertical,
      invalid: false,
      disabled: false,
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      id: None,
      key: None,
    }
  }

  /// A group of which the checkboxes whose values the signal has are
  /// checked. A press adds a value to the signal, or takes it out.
  pub fn new(checked: Signal<Vec<T>>, choices: impl IntoIterator<Item = impl Into<Choice<T>>>) -> Self
  where
    Vec<T>: SignalValue,
  {
    Self::of(checked.get(), Some(turning(checked)), choices)
  }

  /// A group whose state the app holds: the checkboxes of `checked` are
  /// checked, and `on_change` is told the whole new set a press asks for: `checked` with the value pressed added,
  /// or taken out. What is drawn is what the app says next.
  pub fn controlled(
    checked: impl IntoIterator<Item = T>,
    choices: impl IntoIterator<Item = impl Into<Choice<T>>>,
    on_change: impl Fn(&[T]) + Send + Sync + 'static,
  ) -> Self {
    Self::of(checked.into_iter().collect(), None, choices).on_change(on_change)
  }

  /// Called on a press, with the whole new set of values checked, after the signal the group is bound to is set.
  /// That the app sets the signal calls nothing. A second handler is called after the first.
  pub fn on_change(mut self, handler: impl Fn(&[T]) + Send + Sync + 'static) -> Self {
    self.on_change.push(Arc::new(handler));
    self
  }

  /// Which way the checkboxes stand: one under the other, unless told. Side by side they go on to the next line
  /// where there is no room.
  pub fn orientation(mut self, orientation: Orientation) -> Self {
    self.orientation = orientation;
    self
  }

  /// What the group is called, to what reads the tree. It draws nothing: a field gives it its own label.
  pub fn label(mut self, label: &str) -> Self {
    self.label = Some(Arc::from(label));
    self
  }

  /// Whether what is checked is not accepted: every box's edge says so.
  pub fn invalid(mut self, invalid: bool) -> Self {
    self.invalid = invalid;
    self
  }

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

  /// Puts the group 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 group 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 group: what the component it is in says of it in this place.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// Draws the first checkbox that is not disabled as it is under the pointer, held down or focused from the
  /// keyboard, with nothing pointing at it: for a gallery or a test. The other checkboxes are drawn as they are.
  pub fn force(mut self, interaction: Option<Interaction>) -> Self {
    self.forced = interaction;
    self
  }

  /// The id of the group.
  pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
    self.id = Some(id.into());
    self
  }

  /// What tells the group apart from those beside it.
  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.key = Some(key.into());
    self
  }

  /// Builds the group in `theme`. Converting a group 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(CheckboxGroupState::Horizontal, !self.orientation.is_vertical())
    .state(CheckboxGroupState::Vertical, self.orientation.is_vertical());
    let recipe = theme
      .resolve::<Self>(&case, Some(&self.rules))
      .owned_by(self.id.as_ref());
    let item = recipe.rules_for(CheckboxGroupPart::Item, CheckboxPart::Root);
    let entry = self
      .choices
      .iter()
      .position(|choice| !self.disabled && !choice.disabled);
    let checkboxes = self
      .choices
      .iter()
      .enumerate()
      .map(|(index, choice)| {
        let press = toggling(
          choice.value.clone(),
          &self.checked,
          self.bound.clone(),
          self.on_change.clone(),
        );
        let mut checkbox = Checkbox::new(&choice.label)
          .checked(self.checked.contains(&choice.value))
          .invalid(self.invalid)
          .disabled(self.disabled || choice.disabled)
          .rules(&item)
          .on_change(move |_| press());
        if Some(index) == entry {
          checkbox = checkbox.force(self.forced);
        }
        checkbox.build(theme)
      })
      .collect();
    let view = CheckboxGroupView {
      label: self.label,
      orientation: self.orientation,
      invalid: self.invalid,
      disabled: self.disabled,
      recipe,
      checkboxes,
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<Self>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

impl<T: Clone + PartialEq + Send + Sync + 'static> From<CheckboxGroup<T>> for Element {
  fn from(group: CheckboxGroup<T>) -> Self {
    group.build(&current_theme())
  }
}

/// A group of checkboxes as a renderer sees it: what it was given, the style of its parts, and its checkboxes,
/// built with what the group says of each and what a press of each does.
pub struct CheckboxGroupView {
  pub label: Option<Arc<str>>,
  pub orientation: Orientation,
  pub invalid: bool,
  pub disabled: bool,
  /// The style of each part of this group.
  pub recipe: ResolvedRecipe,
  /// Its checkboxes, in order.
  pub checkboxes: Vec<Element>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl CheckboxGroupView {
  /// The style of a part, as this group 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()
  }

  /// How the default renderer builds a group: its checkboxes one under the other, or side by side and going on to
  /// the next line. It is a group to what reads the tree, called by its label.
  pub fn render(self) -> Element {
    let root = self.part(CheckboxGroupPart::Root);
    let (id, key, label, checkboxes) = (self.id, self.key, self.label, self.checkboxes);
    macro_rules! group {
      ($holder:expr) => {{
        let mut holder = $holder.part(&root).describe("a11y_role", "group");
        if let Some(label) = label {
          holder = holder.describe("a11y_name", label);
        }
        for checkbox in checkboxes {
          holder = holder.child(checkbox);
        }
        if let Some(id) = id {
          holder = holder.id(id);
        }
        if let Some(key) = key {
          holder = holder.key(key);
        }
        holder.into()
      }};
    }
    if self.orientation.is_vertical() {
      group!(Column::new())
    } else {
      group!(Row::new().wrap().align_items(Alignment::Center))
    }
  }
}

impl<T: Clone + PartialEq + Send + Sync + 'static> crate::ui::Styled for CheckboxGroup<T> {
  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<T: Send + Sync + 'static> Themed for CheckboxGroup<T> {
  const NAME: &'static str = "checkbox_group";
  type Renderer = CheckboxGroupRenderer;

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

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

  /// The design's checkboxes (`pencil/lurq-design-system.pen`, Toggles): one
  /// under the other, 12 apart, as its radios are.
  fn recipe() -> Recipe {
    Recipe::new().base(CheckboxGroupPart::Root, |s| s.gap(12.0)).state(
      CheckboxGroupState::Horizontal,
      CheckboxGroupPart::Root,
      |s| s.gap(24.0),
    )
  }
}

impl super::FieldControl for Checkbox {
  /// Called by the field's label where its own is hidden, since the label a person reads is then the field's;
  /// invalid where the field is, and disabled where the field is.
  fn in_field(mut self, field: &super::InField) -> Element {
    if self.label_hidden && !field.label.is_empty() {
      self.label = field.label.clone();
    }
    self.invalid |= field.judgment == Some(super::Judgment::Invalid);
    self.disabled |= field.disabled;
    self.into()
  }
}

impl<T: Clone + PartialEq + Send + Sync + 'static> super::FieldControl for CheckboxGroup<T> {
  /// Called by the field's label unless it has a name of its own, every box invalid where the field is, and
  /// disabled where the field is.
  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.invalid |= field.judgment == Some(super::Judgment::Invalid);
    self.disabled |= field.disabled;
    self.into()
  }
}