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
//! A recipe: how the parts of a component look, case by case.
//!
//! A recipe is a list of rules. A rule says "in this case, this part has this
//! style": always, for a variant, for a size, in a window at least so wide,
//! while the component is in a state, under the pointer, or any of these
//! together ("a primary button under the pointer"). For a component as it is being built, the rules whose
//! case holds are laid one over another, the more specific over the less, and
//! what comes out is the style of each part.
//!
//! Variants, sizes, states and parts are names. A component gives its own as
//! enums, which read as names, and an app adds any others it wants: a
//! `"brand"` variant, a `"pinned"` state.

use std::{collections::HashMap, sync::Arc};

use super::{
  part_ids::{Lent, Owner},
  part_style::PartStyle,
};
use crate::{
  app::theme::{Breakpoint, Density, RoleName, Theme},
  components::Text,
  node::{Node, NodeUpdate},
};

/// The name of a variant, a size, a state or a part.
pub type Name = RoleName;

/// What a row moves by at each density but the default, from its height at the default: a row of 36 is 28 in a
/// compact theme, 44 in a comfortable one and 48 under a finger. A control keeps its size at every density.
pub const ROW_STEPS: [(Density, f32); 3] = [
  (Density::Compact, -8.0),
  (Density::Comfortable, 8.0),
  (Density::Touch, 12.0),
];

/// What the pointer or the keyboard does to a part, which the part shows by
/// itself: a rule for one of these is no reason to render the component.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Interaction {
  /// Under the pointer.
  Hovered,
  /// Held down.
  Pressed,
  /// Focused from the keyboard.
  FocusVisible,
}

impl Interaction {
  pub const ALL: [Interaction; 3] = [Self::Hovered, Self::Pressed, Self::FocusVisible];
}

/// The case a rule is for. An empty one holds always.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Selector {
  variant: Option<Name>,
  size: Option<Name>,
  /// The density of the theme the rule is for.
  density: Option<Name>,
  /// The narrowest window the rule is for: it holds at this breakpoint and at every wider one.
  breakpoint: Option<Breakpoint>,
  /// States of the component that all have to hold: checked, disabled, loading.
  states: Vec<Name>,
  interaction: Option<Interaction>,
  /// While the interaction group the part is in is under the pointer or holds the focus.
  within: bool,
}

impl Selector {
  /// The case that always holds.
  pub fn new() -> Self {
    Self::default()
  }

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

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

  /// While the theme is at `density` ([`Theme::density`]).
  pub fn density(mut self, density: impl Into<Density>) -> Self {
    self.density = Some(Name::new(density.into().as_str()));
    self
  }

  /// In a window at `breakpoint` or wider. A rule with no breakpoint is for
  /// every width, the narrowest included, and wider windows are styled over
  /// it: as [`Responsive`](crate::responsive::Responsive) values are.
  pub fn breakpoint(mut self, breakpoint: Breakpoint) -> Self {
    self.breakpoint = Some(breakpoint);
    self
  }

  /// While the component is in `state` too.
  pub fn state(mut self, state: impl Into<Name>) -> Self {
    let state = state.into();
    if !self.states.contains(&state) {
      self.states.push(state);
    }
    self
  }

  /// The states the case needs, every one of them: what [`state`](Self::state) added.
  pub fn held_states(&self) -> &[Name] {
    &self.states
  }

  /// What the pointer or the keyboard must be doing to the part for the case to hold, if anything.
  pub fn interaction(&self) -> Option<Interaction> {
    self.interaction
  }

  pub fn hovered(mut self) -> Self {
    self.interaction = Some(Interaction::Hovered);
    self
  }

  pub fn pressed(mut self) -> Self {
    self.interaction = Some(Interaction::Pressed);
    self
  }

  pub fn focus_visible(mut self) -> Self {
    self.interaction = Some(Interaction::FocusVisible);
    self
  }

  /// While the pointer is on the element the part is in that is an interaction group, or the focus is on it or in
  /// it (`.interaction_group(true)`, which a component puts on what is pressed: a row, an item); a part in no group
  /// answers to the innermost button it is in, as to a group (the label of a button). What it sets is painted only,
  /// never sized. With [`hovered`](Self::hovered) or [`pressed`](Self::pressed), while the group
  /// is under the pointer or held down, and not while it only holds the focus: the veil of a row on a cell of it
  /// that covers the row's. With another interaction, as without one.
  pub fn within(mut self) -> Self {
    self.within = true;
    self
  }

  /// How specific the case is: the rules of a more specific case are laid
  /// over those of a less specific one. Always, then a variant, then a size,
  /// then a density, then a breakpoint, a wider one over a narrower, then
  /// states, more of them over fewer.
  fn rank(&self) -> usize {
    if !self.states.is_empty() {
      10 + self.states.len()
    } else if let Some(breakpoint) = self.breakpoint {
      4 + breakpoint as usize
    } else if self.density.is_some() {
      3
    } else if self.size.is_some() {
      2
    } else if self.variant.is_some() {
      1
    } else {
      0
    }
  }

  /// Whether the case holds for a component in `case`, the interaction apart.
  fn holds(&self, case: &Case) -> bool {
    self.variant.is_none_or(|variant| case.variant == Some(variant))
      && self.size.is_none_or(|size| case.size == Some(size))
      && self.density.is_none_or(|density| case.density == Some(density))
      && self
        .breakpoint
        .is_none_or(|from| case.breakpoint.is_some_and(|window| window >= from))
      && self.states.iter().all(|state| case.states.contains(state))
  }
}

/// A rule of a recipe: in a case, a part has a style.
#[derive(Clone, Debug)]
pub struct Rule {
  pub selector: Selector,
  pub part: Name,
  pub style: PartStyle,
}

/// What a component is as it is being built: its variant, its size, the
/// density of its theme, the breakpoint of the window it is in and the
/// states it is in.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Case {
  pub variant: Option<Name>,
  pub size: Option<Name>,
  /// The density of the theme. A case that names none takes the density
  /// of the theme it is resolved in.
  pub density: Option<Name>,
  /// The breakpoint of the window: `None` below the smallest one.
  pub breakpoint: Option<Breakpoint>,
  pub states: Vec<Name>,
}

impl Case {
  pub fn new() -> Self {
    Self::default()
  }

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

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

  /// The density the component is at, whatever its theme is at.
  pub fn density(mut self, density: impl Into<Density>) -> Self {
    self.density = Some(Name::new(density.into().as_str()));
    self
  }

  /// The case with the density of `theme`, unless it names one.
  pub(crate) fn in_theme(&self, theme: &Theme) -> Self {
    let mut case = self.clone();
    if case.density.is_none() {
      case.density = Some(Name::new(theme.density().as_str()));
    }
    case
  }

  /// The breakpoint of the window the component is in.
  pub fn breakpoint(mut self, breakpoint: Option<Breakpoint>) -> Self {
    self.breakpoint = breakpoint;
    self
  }

  /// Adds `state` if `on`.
  pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
    let state = state.into();
    if on && !self.states.contains(&state) {
      self.states.push(state);
    }
    self
  }
}

/// How the parts of a component look, case by case.
///
/// ```
/// use lurq::{
///   app::theme::{ControlSize, PaletteColor, RadiusSize},
///   ui::{Recipe, Selector},
/// };
///
/// let recipe = Recipe::new()
///   .base("root", |s| s.height(ControlSize::Md).radius(RadiusSize::Md))
///   .variant("primary", "root", |s| s.background(PaletteColor::Primary).foreground(PaletteColor::PrimaryForeground))
///   .when(Selector::new().variant("primary").hovered(), "root", |s| s.background(PaletteColor::PrimaryHover));
/// assert_eq!(recipe.rules().len(), 3);
/// ```
#[derive(Clone, Debug, Default)]
pub struct Recipe {
  rules: Vec<Rule>,
  /// The part of another component this recipe was lent from, which names a component given no id of its own.
  lent: Option<Lent>,
  /// What the component's root says of itself to tooling that reads the tree: see [`Recipe::describe`].
  descriptions: Vec<Description>,
}

/// What a node says of itself to tooling under a name: `("tone", "warning")`.
type Description = (Arc<str>, Arc<str>);

impl Recipe {
  pub fn new() -> Self {
    Self::default()
  }

  /// A rule for the case `selector` describes.
  pub fn when(mut self, selector: Selector, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.rules.push(Rule {
      selector,
      part: part.into(),
      style: style(PartStyle::new()),
    });
    self
  }

  /// A rule that always holds.
  pub fn base(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.when(Selector::new(), part, style)
  }

  /// A rule for a variant.
  pub fn variant(
    self,
    variant: impl Into<Name>,
    part: impl Into<Name>,
    style: impl FnOnce(PartStyle) -> PartStyle,
  ) -> Self {
    self.when(Selector::new().variant(variant), part, style)
  }

  /// A rule for a size.
  pub fn size(self, size: impl Into<Name>, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.when(Selector::new().size(size), part, style)
  }

  /// A rule for a density of the theme: a row that is lower in a compact
  /// tool and higher under a finger.
  pub fn density(
    self,
    density: impl Into<Density>,
    part: impl Into<Name>,
    style: impl FnOnce(PartStyle) -> PartStyle,
  ) -> Self {
    self.when(Selector::new().density(density), part, style)
  }

  /// A rule for each density but the default, in the case of `selector`, with the step a row moves by at it
  /// ([`ROW_STEPS`]): `style` is given the part's style and the step.
  pub fn by_density(
    self,
    selector: Selector,
    part: impl Into<Name>,
    style: impl Fn(PartStyle, f32) -> PartStyle,
  ) -> Self {
    let part = part.into();
    ROW_STEPS.iter().fold(self, |recipe, (density, step)| {
      recipe.when(selector.clone().density(*density), part, |s| style(s, *step))
    })
  }

  /// The rules that move a row of `part`, `height` high at the default density, by the steps of the others in the
  /// case of `selector`: 8 lower in a compact theme, 8 higher in a comfortable one and 12 higher under a finger, as a
  /// row of 36 is 28, 44 and 48 ([`ROW_STEPS`]).
  pub fn row_density(self, selector: Selector, part: impl Into<Name>, height: f32) -> Self {
    self.by_density(selector, part, move |s, step| s.height(height + step))
  }

  /// A rule for a window at `breakpoint` or wider: a part that is one size
  /// on a phone and another on a desktop.
  pub fn at(self, breakpoint: Breakpoint, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.when(Selector::new().breakpoint(breakpoint), part, style)
  }

  /// A rule for a state of the component: checked, disabled, loading, or a
  /// state an app names.
  pub fn state(
    self,
    state: impl Into<Name>,
    part: impl Into<Name>,
    style: impl FnOnce(PartStyle) -> PartStyle,
  ) -> Self {
    self.when(Selector::new().state(state), part, style)
  }

  /// A rule for a part under the pointer, whatever the variant.
  pub fn hovered(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.when(Selector::new().hovered(), part, style)
  }

  /// A rule for a part held down.
  pub fn pressed(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.when(Selector::new().pressed(), part, style)
  }

  /// A rule for a part focused from the keyboard.
  pub fn focus_visible(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.when(Selector::new().focus_visible(), part, style)
  }

  /// A rule for a part while the interaction group it is in is under the pointer or holds the focus: an action at
  /// the end of a row that shows only then. See [`Selector::within`].
  pub fn within(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.when(Selector::new().within(), part, style)
  }

  /// A rule for a part while the interaction group it is in is under the pointer: laid over [`within`](Self::within).
  pub fn within_hovered(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.when(Selector::new().within().hovered(), part, style)
  }

  /// A rule for a part while the interaction group it is in is held down: laid over
  /// [`within_hovered`](Self::within_hovered).
  pub fn within_pressed(self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.when(Selector::new().within().pressed(), part, style)
  }

  /// Adds the rules of `other` after this recipe's: where both style a case,
  /// `other` wins.
  pub fn extend(mut self, other: &Recipe) -> Self {
    self.rules.extend(other.rules.iter().cloned());
    self.lent = Lent::over(self.lent, other.lent.as_ref());
    self.descriptions.extend(other.descriptions.iter().cloned());
    self
  }

  /// Says `value` of the component's root under `name` to tooling that reads the tree, the DevTools and the MCP
  /// tree, as an element's own `describe` does: the state an app's tests and an agent read, `("tone", "warning")`.
  /// It is said on the node of the root part ([`Themed::ROOT`](super::Themed::ROOT)) when the renderer gives it the
  /// part's style, before what the component says of itself, so a reader that takes the first value of a name takes
  /// this one. What [`Styled::describe`](super::Styled::describe) lays over an instance. Like an element's
  /// `describe`, it says nothing unless a tooling feature (`devtools`, `mcp`) is on.
  pub fn describe(mut self, name: impl Into<Arc<str>>, value: impl Into<Arc<str>>) -> Self {
    self.descriptions.push((name.into(), value.into()));
    self
  }

  /// What the recipe says of the component's root to tooling, in the order it was said.
  pub fn descriptions(&self) -> &[(Arc<str>, Arc<str>)] {
    &self.descriptions
  }

  pub fn rules(&self) -> &[Rule] {
    &self.rules
  }

  pub fn is_empty(&self) -> bool {
    self.rules.is_empty()
  }

  pub(crate) fn lent(&self) -> Option<&Lent> {
    self.lent.as_ref()
  }

  /// The style of every part for a component in `case`, in `theme`.
  pub fn resolve(&self, case: &Case, theme: &Theme) -> ResolvedRecipe {
    resolve(&[self], case, theme)
  }
}

/// The styles of every part of a component in one case: the rules of
/// `recipes` that hold, each recipe's over the one before it.
pub(crate) fn resolve(recipes: &[&Recipe], case: &Case, theme: &Theme) -> ResolvedRecipe {
  let lent = recipes.iter().rev().find_map(|recipe| recipe.lent.clone());
  ResolvedRecipe::new(
    theme,
    Arc::new(resolve_styles(recipes, &case.in_theme(theme))),
    ROOT,
    lent,
  )
  .described(recipes)
}

/// The part a component puts its id on, unless it says another ([`Themed::ROOT`](super::Themed::ROOT)).
pub(crate) const ROOT: &str = "root";

/// The styles of [`resolve`], apart from a theme: they are the same in every
/// theme with the same recipes, so a theme keeps them.
pub(crate) fn resolve_styles(recipes: &[&Recipe], case: &Case) -> ResolvedStyles {
  let mut holding: Vec<(usize, usize, &Rule)> = recipes
    .iter()
    .enumerate()
    .flat_map(|(layer, recipe)| recipe.rules.iter().map(move |rule| (layer, rule)))
    .filter(|(_, rule)| rule.selector.holds(case))
    .map(|(layer, rule)| (layer, rule.selector.rank(), rule))
    .collect();
  // A later recipe over an earlier one, the more specific case over the less; rules of one rank in the order
  // they were written.
  holding.sort_by_key(|(layer, rank, _)| (*layer, *rank));

  let mut parts: HashMap<Name, PartStyles> = HashMap::new();
  for (_, _, rule) in holding {
    let part = parts.entry(rule.part).or_default();
    match rule.selector.interaction {
      None | Some(Interaction::FocusVisible) if rule.selector.within => part.within.merge(&rule.style),
      Some(Interaction::Hovered) if rule.selector.within => part.within_hovered.merge(&rule.style),
      Some(Interaction::Pressed) if rule.selector.within => part.within_pressed.merge(&rule.style),
      None => part.rest.merge(&rule.style),
      Some(Interaction::Hovered) => part.hovered.merge(&rule.style),
      Some(Interaction::Pressed) => part.pressed.merge(&rule.style),
      Some(Interaction::FocusVisible) => part.focus_visible.merge(&rule.style),
    }
  }
  ResolvedStyles {
    parts,
    nothing: PartStyles::default(),
  }
}

/// The styles of one part: at rest, and what each interaction lays over that.
#[derive(Clone, Debug, Default)]
pub struct PartStyles {
  pub rest: PartStyle,
  pub hovered: PartStyle,
  pub pressed: PartStyle,
  pub focus_visible: PartStyle,
  /// What the part shows while the interaction group it is in is under the pointer or holds the focus.
  pub within: PartStyle,
  /// What the part shows over `within` while the interaction group it is in is under the pointer.
  pub within_hovered: PartStyle,
  /// What the part shows over `within_hovered` while the interaction group it is in is held down.
  pub within_pressed: PartStyle,
}

impl PartStyles {
  /// What an interaction lays over the style at rest.
  pub fn interaction(&self, interaction: Interaction) -> &PartStyle {
    match interaction {
      Interaction::Hovered => &self.hovered,
      Interaction::Pressed => &self.pressed,
      Interaction::FocusVisible => &self.focus_visible,
    }
  }
}

/// The styles of every part of a component in one case.
pub(crate) struct ResolvedStyles {
  parts: HashMap<Name, PartStyles>,
  nothing: PartStyles,
}

/// The style of every part of a component as it is being built: what a
/// renderer builds the component's nodes from.
///
/// Once [`owned_by`](Self::owned_by) the id of the component, it names the
/// nodes it styles after it: `x-label` for the node of the part `label`, as
/// [`ResolvedPart::apply`] gives it.
#[derive(Clone)]
pub struct ResolvedRecipe {
  theme: Theme,
  styles: Arc<ResolvedStyles>,
  /// The part the component's id is on.
  root: Name,
  /// The id its parts are named after.
  owner: Option<Owner>,
  /// The part of the component it is built in that it stands for, if it was lent one.
  lent: Option<Lent>,
  /// What the root's node says of itself to tooling: what the recipes said with [`Recipe::describe`].
  descriptions: Option<Arc<[Description]>>,
}

impl ResolvedRecipe {
  pub(crate) fn new(theme: &Theme, styles: Arc<ResolvedStyles>, root: impl Into<Name>, lent: Option<Lent>) -> Self {
    Self {
      theme: theme.clone(),
      styles,
      root: root.into(),
      owner: None,
      lent,
      descriptions: None,
    }
  }

  /// This recipe saying on its root's node what `recipes` said with [`Recipe::describe`], the earlier first.
  pub(crate) fn described(mut self, recipes: &[&Recipe]) -> Self {
    let said: Vec<Description> = recipes
      .iter()
      .flat_map(|recipe| recipe.descriptions.iter().cloned())
      .collect();
    self.descriptions = (!said.is_empty()).then(|| Arc::from(said));
    self
  }

  /// This recipe with its root at `part` in place of the one the component declares: for a component that is laid
  /// out with its id on another part in one of its forms (a switch pressed as a whole, its id on the whole and not on
  /// its track). Called before [`owned_by`](Self::owned_by).
  pub(crate) fn rooted_at(mut self, part: impl Into<Name>) -> Self {
    self.root = part.into();
    self
  }

  /// The recipe of a component whose id is `id`, which names the nodes of its parts after it: `x-label`, `x-dot`,
  /// and `x-label-2` for a second node of a part. The root's node is not named: the component puts `id` on it.
  /// Given no id, the component takes the id of the part of the component it is built in that it stands for (as
  /// [`rules_for`](Self::rules_for) or [`lend`](Self::lend) gave it), and puts it on its root; with neither, its
  /// parts have no ids. What a component calls once, where it resolves its recipe.
  pub fn owned_by(mut self, id: Option<&Arc<str>>) -> Self {
    self.owner = match id {
      Some(id) => Some(Owner::new(id.clone(), self.root, true)),
      None => self.lent.take().and_then(|lent| lent.owner(self.root)),
    };
    self
  }

  /// This recipe naming its parts after the id `other` names them after, counted with `other`'s: a second recipe of
  /// the same component in another case (an item while it is current, a row while it is disabled), resolved in the
  /// same build.
  pub fn owned_like(mut self, other: &ResolvedRecipe) -> Self {
    self.owner = other.owner.as_ref().map(|owner| owner.rooted(self.root));
    self.lent = None;
    self
  }

  /// The recipe an item of the component is built with, its node the part `root`: given an id `y`, it names the
  /// item's parts after it (`y-term`, `y-value`), whether the component has an id or not; given none, after the
  /// component's id, as the rest of it.
  pub fn item(&self, id: Option<&Arc<str>>, root: impl Into<Name>) -> Self {
    let mut item = self.clone();
    if let Some(id) = id {
      item.owner = Some(Owner::new(id.clone(), root.into(), true));
    }
    item
  }

  /// The recipe an item of the component is built with that has no id of its own and a key that tells it from the
  /// others (its value, a date): where the component has an id `x`, the item's node of the part `root` is
  /// `x-<root>-<key>`, and its parts are named after that. Where the component has none, as the rest of it.
  pub fn keyed_item(&self, key: &str, root: impl Into<Name>) -> Self {
    let mut item = self.clone();
    item.owner = self.owner.as_ref().map(|owner| owner.item(root.into(), key));
    item
  }

  /// The id of the next node of `part`, for an element the renderer builds without the part's style, or a
  /// component it gives the id to itself: `x-<part>`, numbered as [`ResolvedPart::apply`] numbers. `None` where the
  /// component has no id, and for its root.
  pub fn part_id(&self, part: impl Into<Name>) -> Option<Arc<str>> {
    self.owner.as_ref()?.next(part.into())
  }

  /// The id of the node of `part` told apart by `key` (`x-nav-previous`), for an element the renderer builds without
  /// the part's style, or a component it gives the id to itself: what [`ResolvedPart::keyed`] names. `None` where the
  /// component has no id, and for its root.
  pub fn keyed_id(&self, part: impl Into<Name>, key: impl std::fmt::Display) -> Option<Arc<str>> {
    self.owner.as_ref()?.keyed(part.into(), &key.to_string())
  }

  /// Rules that lend `part` to a component built inside this one, given to it by its `rules`: the component, given
  /// no id of its own, takes `part`'s id (`x-close`) and names its parts after it. [`rules_for`](Self::rules_for)
  /// lends its part too. `part` may be a name that is no part of this recipe's: the inner component's own short
  /// name (`calendar`), where it is the only one of its kind in this one, so that it is `x-calendar` and not named
  /// after the panel it stands in.
  pub fn lend(&self, part: impl Into<Name>) -> Recipe {
    Recipe {
      rules: Vec::new(),
      lent: self.lent_part(part.into(), true),
      descriptions: Vec::new(),
    }
  }

  fn lent_part(&self, part: Name, to_root: bool) -> Option<Lent> {
    self.owner.clone().map(|owner| Lent::new(owner, part, to_root))
  }

  /// The style of a part. A part no rule styles has an empty one.
  pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
    ResolvedPart {
      recipe: self.clone(),
      part: part.into(),
      forced: None,
      named: true,
      key: None,
    }
  }

  /// The theme the recipe was resolved in.
  pub fn theme(&self) -> &Theme {
    &self.theme
  }

  /// Whether a rule styles `part`: a part of a name no rule gives anything is no part of this recipe's.
  pub fn has(&self, part: impl Into<Name>) -> bool {
    self.styles.parts.contains_key(&part.into())
  }

  fn styles(&self, part: Name) -> &PartStyles {
    self.styles.parts.get(&part).unwrap_or(&self.styles.nothing)
  }

  /// Rules that give the part `inner` of another component what this recipe
  /// has for `part`, at rest and in each interaction: how a component that
  /// holds another hands it its place. A group's recipe has a part for its
  /// items, and gives each button in it these rules over the theme's for a
  /// button (`Button::rules`).
  pub fn rules_for(&self, part: impl Into<Name>, inner: impl Into<Name>) -> Recipe {
    let part = part.into();
    let styles = self.styles(part).clone();
    let inner = inner.into();
    let mut recipe = Recipe::new();
    recipe.lent = self.lent_part(part, inner.as_str() == ROOT);
    recipe
      .base(inner, |_| styles.rest.clone())
      .hovered(inner, |_| styles.hovered.clone())
      .pressed(inner, |_| styles.pressed.clone())
      .focus_visible(inner, |_| styles.focus_visible.clone())
      .within(inner, |_| styles.within.clone())
      .within_hovered(inner, |_| styles.within_hovered.clone())
      .within_pressed(inner, |_| styles.within_pressed.clone())
  }
}

/// The style of one part of a component as it is being built.
///
/// A renderer gives it to the node that is the part,
/// `Row::new().part(&recipe.part(ButtonPart::Root))`, and makes the part's
/// text with [`ResolvedPart::text`].
#[derive(Clone)]
pub struct ResolvedPart {
  recipe: ResolvedRecipe,
  part: Name,
  forced: Option<Interaction>,
  /// Whether the node it is given is named after the part ([`ResolvedRecipe::owned_by`]).
  named: bool,
  /// What tells its node from the others of the part, in place of their order.
  key: Option<Arc<str>>,
}

impl ResolvedPart {
  /// The part drawn as it is in an interaction, with nothing pointing at it:
  /// for a gallery, a screenshot, a test. `None` leaves it to the pointer.
  pub fn forced(mut self, interaction: Option<Interaction>) -> Self {
    self.forced = interaction;
    self
  }

  /// The part, its node told apart from the others of the part by `key` (`x-day-2026-11-20`, `x-nav-previous`) in
  /// place of its place among them (`x-day-20`): a day of a calendar, a button of each side. The key is an
  /// identifier, the same in every language.
  pub fn keyed(mut self, key: impl std::fmt::Display) -> Self {
    self.key = Some(Arc::from(key.to_string()));
    self
  }

  /// The part, its node given no id: a node that holds the component the part was lent to
  /// ([`ResolvedRecipe::lend`]), which has the part's id on its own root.
  pub fn unnamed(mut self) -> Self {
    self.named = false;
    self
  }

  /// The id the node of the part is given: by its key, or the next of the part.
  fn id(&self) -> Option<Arc<str>> {
    let owner = self.recipe.owner.as_ref()?;
    match &self.key {
      Some(key) => owner.keyed(self.part, key),
      None => owner.next(self.part),
    }
  }

  /// The styles the rules gave the part.
  pub fn styles(&self) -> &PartStyles {
    self.recipe.styles(self.part)
  }

  /// The style of the part at rest, with a forced interaction laid over it.
  pub fn rest(&self) -> PartStyle {
    let styles = self.styles();
    // A part drawn as pointed at or focused is in a group that is: what shows only then shows.
    match self.forced {
      // A part held down is under the pointer too.
      Some(Interaction::Pressed) => styles
        .rest
        .clone()
        .merged(&styles.within)
        .merged(&styles.within_hovered)
        .merged(&styles.within_pressed)
        .merged(&styles.hovered)
        .merged(&styles.pressed),
      Some(Interaction::Hovered) => styles
        .rest
        .clone()
        .merged(&styles.within)
        .merged(&styles.within_hovered)
        .merged(&styles.hovered),
      Some(interaction) => styles
        .rest
        .clone()
        .merged(&styles.within)
        .merged(styles.interaction(interaction)),
      None => styles.rest.clone(),
    }
  }

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

  /// A text in the part's typography, in the color of the part it is in.
  ///
  /// A part that sets a `foreground`, at rest or in any of its states, colors
  /// its own text: the color of its typography role is dropped, so the text
  /// takes the foreground. Where the part sets one only in a state, the role's
  /// color is the text's at rest. A part that sets none leaves the text in its
  /// role's color, or, where the role names none, in the foreground of what it
  /// is in.
  pub fn text(&self, content: &str) -> Text {
    let rest = self.rest();
    let mut style = rest.text.resolve(self.theme());
    if !self.sets_foreground(&rest) {
      return Text::styled(content, style);
    }
    let role = std::mem::replace(&mut style.color, crate::layout::text_style::DEFAULT_TEXT_COLOR);
    let text = Text::styled(content, style);
    if rest.foreground.is_none() && role != crate::layout::text_style::DEFAULT_TEXT_COLOR {
      text.foreground(role)
    } else {
      text
    }
  }

  /// Whether the part sets a foreground, at rest (`rest`, as [`rest`](Self::rest) gives it) or in a state.
  fn sets_foreground(&self, rest: &PartStyle) -> bool {
    let styles = self.styles();
    rest.foreground.is_some()
      || [
        &styles.hovered,
        &styles.pressed,
        &styles.focus_visible,
        &styles.within,
        &styles.within_hovered,
        &styles.within_pressed,
      ]
      .iter()
      .any(|style| style.foreground.is_some())
  }

  /// Gives a node the part's style: what it shows at rest, and what it shows
  /// under the pointer, held down and focused from the keyboard.
  ///
  /// A node with no id is given the part's id, where the component has one: see
  /// [`ResolvedRecipe::owned_by`]. The node of the root part says what the recipe describes
  /// ([`Recipe::describe`]).
  pub(crate) fn apply(&self, node: &mut Node) {
    if self.named
      && node.element_id.is_none()
      && let Some(id) = self.id()
    {
      NodeUpdate::id(node, id);
    }
    if self.part == self.recipe.root
      && let Some(descriptions) = &self.recipe.descriptions
    {
      for (name, value) in descriptions.iter() {
        NodeUpdate::describe(node, name.clone(), value.clone());
      }
    }
    let theme = self.theme();
    let styles = self.styles();
    self.rest().apply(node, theme);
    if let Some(style) = styles.hovered.state_style(theme) {
      NodeUpdate::hovered_style(node, style);
    }
    if let Some(style) = styles.pressed.state_style(theme) {
      NodeUpdate::active_style(node, style);
    }
    if let Some(style) = styles.focus_visible.state_style(theme) {
      NodeUpdate::focus_visible_style(node, style);
    }
    if let Some(style) = styles.within.state_style(theme) {
      NodeUpdate::within_style(node, style);
    }
    if let Some(style) = styles.within_hovered.state_style(theme) {
      NodeUpdate::within_hovered_style(node, style);
    }
    if let Some(style) = styles.within_pressed.state_style(theme) {
      NodeUpdate::within_pressed_style(node, style);
    }
  }
}

#[cfg(test)]
mod tests {
  use super::{Case, Interaction, Recipe, Selector};
  use crate::{
    app::theme::{ControlSize, PaletteColor, RadiusSize, Theme},
    node::BackgroundColor,
    ui::Length,
  };

  fn recipe() -> Recipe {
    Recipe::new()
      .base("root", |s| {
        s.height(ControlSize::Md)
          .radius(RadiusSize::Md)
          .background(PaletteColor::Muted)
      })
      .variant("primary", "root", |s| s.background(PaletteColor::Primary))
      .size("lg", "root", |s| s.height(ControlSize::Lg))
      .state("disabled", "root", |s| s.opacity(0.5))
      .when(Selector::new().variant("primary").hovered(), "root", |s| {
        s.background(PaletteColor::PrimaryHover)
      })
      .hovered("root", |s| s.background(PaletteColor::StateHover))
  }

  fn background(color: PaletteColor) -> Option<BackgroundColor> {
    Some(BackgroundColor::Palette(color))
  }

  #[test]
  fn the_rules_that_hold_are_laid_the_more_specific_over_the_less() {
    let theme = Theme::new();
    let resolved = recipe().resolve(&Case::new().variant("primary").size("lg"), &theme);
    let root = resolved.part("root").rest();
    assert_eq!(
      root.background,
      background(PaletteColor::Primary),
      "the variant over the base"
    );
    assert_eq!(
      root.height,
      Some(Length::Control(ControlSize::Lg)),
      "the size over the base"
    );
    assert_eq!(
      root.radius,
      Some(crate::node::border::ThemedBorderRadius::all(RadiusSize::Md)),
      "what nothing replaced"
    );
    assert_eq!(root.opacity, None, "a state it is not in");
  }

  #[test]
  fn a_rule_for_a_state_holds_while_the_component_is_in_it() {
    let theme = Theme::new();
    let case = Case::new().state("disabled", true).state("loading", false);
    assert!(recipe().resolve(&case, &theme).part("root").rest().opacity.is_some());
  }

  #[test]
  fn an_interaction_is_kept_apart_from_the_style_at_rest() {
    let theme = Theme::new();
    let primary = recipe().resolve(&Case::new().variant("primary"), &theme);
    let root = primary.part("root");
    assert_eq!(root.rest().background, background(PaletteColor::Primary));
    assert_eq!(
      root.styles().hovered.background,
      background(PaletteColor::PrimaryHover),
      "the rule for a primary button under the pointer over the one for any"
    );
    let plain = recipe().resolve(&Case::new(), &theme);
    assert_eq!(
      plain.part("root").styles().hovered.background,
      background(PaletteColor::StateHover)
    );
  }

  #[test]
  fn a_forced_interaction_is_drawn_as_the_style_at_rest() {
    let theme = Theme::new();
    let resolved = recipe().resolve(&Case::new().variant("primary"), &theme);
    let hovered = resolved.part("root").forced(Some(Interaction::Hovered)).rest();
    assert_eq!(hovered.background, background(PaletteColor::PrimaryHover));
    assert_eq!(
      hovered.radius,
      Some(crate::node::border::ThemedBorderRadius::all(RadiusSize::Md))
    );
  }

  #[test]
  fn a_later_recipe_is_laid_over_an_earlier_one_whatever_the_case() {
    let theme = Theme::new();
    let instance = Recipe::new().base("root", |s| s.background(PaletteColor::Destructive));
    let resolved = super::resolve(&[&recipe(), &instance], &Case::new().variant("primary"), &theme);
    assert_eq!(
      resolved.part("root").rest().background,
      background(PaletteColor::Destructive),
      "the instance's rule for any case over the theme's rule for the variant"
    );
  }

  #[test]
  fn a_rule_for_a_density_holds_while_the_theme_is_at_it() {
    use crate::app::theme::Density;
    let theme = Theme::new();
    let recipe = Recipe::new()
      .base("root", |s| s.height(36.0))
      .size("lg", "root", |s| s.height(40.0))
      .density(Density::Compact, "root", |s| s.height(28.0))
      .density(Density::Touch, "root", |s| s.height(48.0));
    let height = |case: Case| recipe.resolve(&case, &theme).part("root").rest().height;
    assert_eq!(height(Case::new()), Some(Length::Px(36.0)), "the default density");
    theme.set_density(Density::Compact);
    assert_eq!(height(Case::new()), Some(Length::Px(28.0)), "the theme at compact");
    assert_eq!(
      height(Case::new().size("lg")),
      Some(Length::Px(28.0)),
      "the rule for the density over the rule for the size"
    );
    assert_eq!(
      height(Case::new().density(Density::Touch)),
      Some(Length::Px(48.0)),
      "a case that names a density keeps it"
    );
  }

  #[test]
  fn a_rule_for_a_breakpoint_holds_from_that_width_up() {
    use crate::app::theme::Breakpoint;
    let theme = Theme::new();
    let recipe = Recipe::new()
      .base("root", |s| s.height(48.0))
      .at(Breakpoint::Md, "root", |s| s.height(36.0))
      .at(Breakpoint::Xl, "root", |s| s.height(40.0));
    let height = |breakpoint| {
      recipe
        .resolve(&Case::new().breakpoint(breakpoint), &theme)
        .part("root")
        .rest()
        .height
    };
    assert_eq!(
      height(None),
      Some(Length::Px(48.0)),
      "a phone: the rule for every width"
    );
    assert_eq!(
      height(Some(Breakpoint::Sm)),
      Some(Length::Px(48.0)),
      "narrower than the rule's"
    );
    assert_eq!(height(Some(Breakpoint::Md)), Some(Length::Px(36.0)));
    assert_eq!(
      height(Some(Breakpoint::Lg)),
      Some(Length::Px(36.0)),
      "and at every wider one"
    );
    assert_eq!(
      height(Some(Breakpoint::Xl)),
      Some(Length::Px(40.0)),
      "the widest that holds wins"
    );
  }

  #[test]
  fn a_part_no_rule_styles_is_unstyled() {
    let theme = Theme::new();
    let resolved = recipe().resolve(&Case::new(), &theme);
    assert!(resolved.part("icon").rest().is_empty());
    assert!(
      Recipe::new()
        .resolve(&Case::new(), &theme)
        .part("root")
        .rest()
        .is_empty()
    );
  }

  #[test]
  fn an_app_names_variants_and_states_of_its_own() {
    let theme = Theme::new();
    let recipe = recipe()
      .variant("brand", "root", |s| s.background(PaletteColor::extra("brand")))
      .state("pinned", "root", |s| s.radius(RadiusSize::Full));
    let resolved = recipe.resolve(&Case::new().variant("brand").state("pinned", true), &theme);
    let root = resolved.part("root").rest();
    assert_eq!(root.background, background(PaletteColor::extra("brand")));
    assert_eq!(
      root.radius,
      Some(crate::node::border::ThemedBorderRadius::all(RadiusSize::Full))
    );
  }
}