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
//! A card: a surface that holds one thing, with a header, its content and a
//! footer where it has them.

use std::sync::Arc;

use super::{
  names,
  node_edits::NodeEdits,
  part_style::Length,
  recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
  shared::{fading, pressable},
  theme::{Themed, current_theme},
};
use crate::{
  app::{
    events::MouseEvent,
    theme::{BorderSize, OpacityLevel, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle},
  },
  components::{self, Column, Row},
  layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
  node::{
    CursorIcon, Element, EventHandler, IntoMouseEventHandler, NodeUpdate, SpacingValue, border::Border as Edge,
    dimension::Dimension, padding::Padding,
  },
};

/// The parts of a card a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CardPart {
  /// The surface: its fill, its edge, its corners, its shadow. What is
  /// pressed, where the card is.
  Root,
  /// The padded column of the header and the body, over the footer.
  Content,
  /// The title and the description, and the action at its end.
  Header,
  /// The title and the description, one over the other.
  Text,
  /// What the card is about, in a word or a line.
  Title,
  /// More of it, under the title, in the muted color.
  Description,
  /// What the app puts at the end of the header: a button, a menu, a badge.
  Action,
  /// What the app puts in the card (its `child`), under the header.
  Body,
  /// The row of buttons at the bottom, at its end, set off by a line.
  Footer,
}

names!(CardPart {
  Root => "root",
  Content => "content",
  Header => "header",
  Text => "text",
  Title => "title",
  Description => "description",
  Action => "action",
  Body => "body",
  Footer => "footer",
});

/// The states of a card a recipe styles, besides what the pointer and the
/// keyboard do to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CardState {
  /// The card is pressed as a whole: it answers the pointer and the keyboard.
  Pressable,
  /// It takes no input.
  Disabled,
  /// It has a footer under its content, which a line sets off.
  Footer,
}

names!(CardState {
  Pressable => "pressable",
  Disabled => "disabled",
  Footer => "footer",
});

/// How a card stands off the page.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CardVariant {
  /// A hairline edge and the faintest shadow: the card of most places.
  #[default]
  Outline,
  /// A soft shadow and no edge: a card over a busy page.
  Elevated,
  /// A muted fill and no edge: cards that group what is in them, side by side.
  Filled,
}

names!(CardVariant {
  Outline => "outline",
  Elevated => "elevated",
  Filled => "filled",
});

/// How roomy a card is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum CardSize {
  /// Padded 16, a title of 14 and a description of 13: a card of a grid, a
  /// choice, a tile.
  Sm,
  /// Padded 24, a title of 16 and a description of 14.
  #[default]
  Md,
}

names!(CardSize {
  Sm => "sm",
  Md => "md",
});

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

/// A card: a surface that holds one thing. A group of settings, a summary
/// of a project, a form of a few fields.
///
/// ```
/// use lurq::{
///   components::Text,
///   layout::Alignment,
///   node::padding::Padding,
///   ui::{Button, ButtonVariant, Card, CardVariant},
/// };
///
/// let appearance = Card::new()
///   .title("Appearance")
///   .description("How lurq looks on this device.")
///   .child(Button::new("Reset to defaults").variant(ButtonVariant::Outline))
///   .footer(Button::new("Cancel").variant(ButtonVariant::Outline))
///   .footer(Button::new("Save"));
/// // A card that is pressed as a whole: one stop of Tab.
/// let project = Card::new()
///   .title("lurq")
///   .description("A Rust UI toolkit with GPU-backed rendering.")
///   .variant(CardVariant::Elevated)
///   .on_click(|_| println!("open the project"));
/// // Laid out as a column is: its padding, the room between its children, their alignment, its share of a row.
/// let figure = Card::new()
///   .padding(Padding::symmetric(16.0, 12.0))
///   .gap(4.0)
///   .align_items(Alignment::Center)
///   .flex(1.0)
///   .child(Text::new("1,284"))
///   .child(Text::new("Runs this week"));
/// ```
///
/// Every part is optional: a card with children alone is a padded surface.
/// A card is as wide as the room it is given unless it is given a width of
/// its own, and its title and description wrap in the width it has. Cards
/// side by side in a row are each given their share: a column with
/// `flex(1.0)` around each, or a grid. A card given
/// [`Card::on_click`] is pressed as a whole, from the pointer and the
/// keyboard; a press of a control in its action or its footer is that
/// control's and not the card's. A card that is not pressed is read, and
/// the controls in it are each a stop of Tab of their own.
///
/// A card is laid out as a column is, from its own builder: what lays out
/// what is in it ([`padding`](Card::padding), [`gap`](Card::gap),
/// [`align_items`](Card::align_items)) goes to its content and its body, and
/// what places it in what holds it ([`width`](Card::width),
/// [`height`](Card::height) and their least and most, [`flex`](Card::flex),
/// [`flex_shrink`](Card::flex_shrink), [`absolute`](Card::absolute)) to its
/// surface. A card given a height of its own ([`height`](Card::height), or
/// its recipe's) gives what its header leaves to its body, so its children
/// with `flex` fill it, and its footer stays at the bottom.
/// What is in a card is clipped to its rounded corners, as what is in any
/// element is to its own: a table or a picture that reaches its edge does not
/// paint over them.
pub struct Card {
  title: Option<Arc<str>>,
  label: Option<Arc<str>>,
  description: Option<Arc<str>>,
  action: Option<Element>,
  body: Vec<Element>,
  footer: Vec<Element>,
  variant: Name,
  size: Name,
  disabled: bool,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  on_click: Vec<EventHandler<MouseEvent>>,
  /// What the app laid on the surface and on the body besides their style.
  root_edits: NodeEdits,
  body_edits: NodeEdits,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl Default for Card {
  fn default() -> Self {
    Self::new()
  }
}

impl Card {
  /// A card with nothing in it yet.
  pub fn new() -> Self {
    Self {
      title: None,
      label: None,
      description: None,
      action: None,
      body: Vec::new(),
      footer: Vec::new(),
      variant: CardVariant::default().into(),
      size: CardSize::default().into(),
      disabled: false,
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      on_click: Vec::new(),
      root_edits: NodeEdits::default(),
      body_edits: NodeEdits::default(),
      id: None,
      key: None,
    }
  }

  /// What the card is about: "Appearance". It is also what the card is
  /// called to tooling that reads the tree, unless it has a label.
  pub fn title(mut self, title: &str) -> Self {
    self.title = Some(Arc::from(title));
    self
  }

  /// What the card is called to tooling that reads the tree, in place of
  /// its title: the name of a card that has none.
  pub fn label(mut self, label: &str) -> Self {
    self.label = Some(Arc::from(label));
    self
  }

  /// More of it, under the title, in the muted color.
  pub fn description(mut self, description: &str) -> Self {
    self.description = Some(Arc::from(description));
    self
  }

  /// What stands at the end of the header, beside the title: a button, a
  /// menu, a badge. A card has one: a second call takes the place of the
  /// first.
  pub fn action(mut self, action: impl Into<Element>) -> Self {
    self.action = Some(action.into());
    self
  }

  /// Adds an element to the body, under the header.
  pub fn child(mut self, child: impl Into<Element>) -> Self {
    self.body.push(child.into());
    self
  }

  /// Adds elements to the body.
  pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Element>>) -> Self {
    self.body.extend(children.into_iter().map(Into::into));
    self
  }

  /// Adds an element to the footer, after those already there: the footer is
  /// a row at the end of the card under a line, its least action first and
  /// its main one last.
  pub fn footer(mut self, element: impl Into<Element>) -> Self {
    self.footer.push(element.into());
    self
  }

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

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

  /// A width of its own in place of all the room it is given: a number of
  /// logical pixels, or another [`Length`].
  pub fn width(mut self, width: impl Into<Length>) -> Self {
    let width = width.into();
    self.rules = self.rules.base(CardPart::Root, |s| s.width(width));
    self
  }

  /// A height of its own in place of its content's: a number of logical
  /// pixels, or another [`Length`].
  pub fn height(mut self, height: impl Into<Length>) -> Self {
    let height = height.into();
    self.rules = self.rules.base(CardPart::Root, |s| s.height(height));
    self
  }

  /// The least it is wide: `0.0` lets a card that shares a row with others
  /// be narrower than its content, which then wraps.
  pub fn min_width(mut self, width: impl Into<Length>) -> Self {
    let width = width.into();
    self.rules = self.rules.base(CardPart::Root, |s| s.min_width(width));
    self
  }

  /// The most it is wide, however much room it is given.
  pub fn max_width(mut self, width: impl Into<Length>) -> Self {
    let width = width.into();
    self.rules = self.rules.base(CardPart::Root, |s| s.max_width(width));
    self
  }

  /// The least it is high.
  pub fn min_height(mut self, height: impl Into<Length>) -> Self {
    let height = height.into();
    self.rules = self.rules.base(CardPart::Root, |s| s.min_height(height));
    self
  }

  /// The most it is high.
  pub fn max_height(mut self, height: impl Into<Length>) -> Self {
    let height = height.into();
    self.rules = self.rules.base(CardPart::Root, |s| s.max_height(height));
    self
  }

  /// The room inside it around its header and its body, in place of its
  /// size's: a [`Padding`], one number for every side, or a step of the
  /// theme's spacing. Its footer keeps its own.
  pub fn padding(mut self, padding: impl Into<Padding>) -> Self {
    let padding = padding.into();
    self.rules = self.rules.base(CardPart::Content, |s| {
      s.padding_top(*padding.get_top())
        .padding_end(*padding.get_right())
        .padding_bottom(*padding.get_bottom())
        .padding_start(*padding.get_left())
    });
    self
  }

  /// The room between its children, and between its header and its body, in
  /// place of its size's: a number of logical pixels or a step of the theme's
  /// spacing.
  pub fn gap(mut self, gap: impl Into<SpacingValue>) -> Self {
    let gap = gap.into();
    self.rules = self
      .rules
      .base(CardPart::Content, |s| s.gap(gap))
      .base(CardPart::Body, |s| s.gap(gap));
    self
  }

  /// How its children are aligned across its width, as a column aligns
  /// them: at the start unless told.
  pub fn align_items(mut self, align: Alignment) -> Self {
    self.body_edits.push(move |node| NodeUpdate::align_items(node, align));
    self
  }

  /// Its share of the room a row or a column it is in has left, as an
  /// element's `flex` is.
  pub fn flex(mut self, factor: f32) -> Self {
    self.root_edits.push(move |node| NodeUpdate::flex(node, factor));
    self
  }

  /// How much of its size it gives up where a row or a column it is in has
  /// too little room: `0.0` keeps it whole.
  pub fn flex_shrink(mut self, factor: f32) -> Self {
    self.root_edits.push(move |node| NodeUpdate::flex_shrink(node, factor));
    self
  }

  /// Stands it at `x` and `y` in the [`Stack`](crate::components::Stack)
  /// that holds it, `width` by `height`, as an element's `absolute` does.
  pub fn absolute(mut self, x: f32, y: f32, width: impl Into<Dimension>, height: impl Into<Dimension>) -> Self {
    let (width, height) = (width.into(), height.into());
    self
      .root_edits
      .push(move |node| NodeUpdate::absolute(node, x, y, width, height));
    self
  }

  /// Says `value` as `name` to tooling that reads the tree, on its surface:
  /// the state of what it shows, for a test or an agent.
  pub fn describe(mut self, name: impl Into<Arc<str>>, value: impl Into<Arc<str>>) -> Self {
    let (name, value) = (name.into(), value.into());
    self
      .root_edits
      .push(move |node| NodeUpdate::describe(node, name.clone(), value.clone()));
    self
  }

  /// Whether the card takes no input: a card that is pressed is dimmed and
  /// is not pressed.
  pub fn disabled(mut self, disabled: bool) -> Self {
    self.disabled = disabled;
    self
  }

  /// Puts the card 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 of the card: a click, or Enter or Space while it has
  /// the focus. A card given one is pressed as a whole.
  pub fn on_click(mut self, handler: impl IntoMouseEventHandler) -> Self {
    self.on_click.push(handler.into_event_handler());
    self
  }

  /// Styles one part of this card 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 card.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

  /// Draws the card 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 id of the surface: what is pressed, where the card is.
  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 card in `theme`. Converting a card into an element does
  /// this in the theme of what is being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    let pressable = !self.on_click.is_empty();
    let has_content =
      self.title.is_some() || self.description.is_some() || self.action.is_some() || !self.body.is_empty();
    let case = Case {
      variant: Some(self.variant),
      size: Some(self.size),
      density: None,
      breakpoint: super::current_breakpoint(),
      states: self.states.clone(),
    }
    // A disabled card is not pressed, so it does not answer the pointer either.
    .state(CardState::Pressable, pressable && !self.disabled)
    .state(CardState::Disabled, self.disabled)
    .state(CardState::Footer, has_content && !self.footer.is_empty());
    let view = CardView {
      title: self.title,
      label: self.label,
      description: self.description,
      action: self.action,
      body: self.body,
      footer: self.footer,
      pressable,
      disabled: self.disabled,
      recipe: theme
        .resolve::<Card>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      forced: self.forced,
      on_click: self.on_click,
      root_edits: self.root_edits,
      body_edits: self.body_edits,
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<Card>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

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

/// A card as a renderer sees it: what it was given, the style of its parts,
/// and its behavior ready to be dressed.
pub struct CardView {
  pub title: Option<Arc<str>>,
  /// What the card is called to tooling, where the app gave other words than its title.
  pub label: Option<Arc<str>>,
  pub description: Option<Arc<str>>,
  /// What the app put at the end of the header.
  pub action: Option<Element>,
  /// What the app put in the body.
  pub body: Vec<Element>,
  /// What the app put in the footer.
  pub footer: Vec<Element>,
  /// Whether the card is pressed as a whole.
  pub pressable: bool,
  pub disabled: bool,
  /// The style of each part of this card.
  pub recipe: ResolvedRecipe,
  forced: Option<Interaction>,
  on_click: Vec<EventHandler<MouseEvent>>,
  root_edits: NodeEdits,
  body_edits: NodeEdits,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

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

  /// A row that keeps a press of what is in it from the card, where the card
  /// is pressed: a press of a button in the footer is the button's alone.
  fn own_presses(&self, row: Row) -> Row {
    if self.pressable {
      row.on_click(|event: MouseEvent| event.stop_propagation())
    } else {
      row
    }
  }

  /// The title and the description, one over the other, each as wide as the
  /// room the header leaves it: `None` for a card that has neither.
  pub fn text(&self) -> Option<Column> {
    if self.title.is_none() && self.description.is_none() {
      return None;
    }
    let mut text = Column::new()
      .flex(1.0)
      .min_width(Dimension::Px(0.0))
      .part(&self.part(CardPart::Text));
    if let Some(title) = &self.title {
      text = text.child(wrapping(&self.part(CardPart::Title), title));
    }
    if let Some(description) = &self.description {
      text = text.child(wrapping(&self.part(CardPart::Description), description));
    }
    Some(text)
  }

  /// Whether the card has a height of its own that its content and its body are to fill: a card as high as what is
  /// in it, or with only a least height, gives them none, since a column that grows takes all the room it may.
  pub fn has_height(&self) -> bool {
    self.part(CardPart::Root).rest().height.is_some()
  }

  /// What the card is called to tooling: its label, or its title.
  fn name(&self) -> Option<Arc<str>> {
    self.label.clone().or_else(|| self.title.clone())
  }

  /// The action, in the style of its part: `None` for a card without one.
  pub fn action(&mut self) -> Option<Row> {
    let action = self.action.take()?;
    let row = Row::new()
      .align_items(Alignment::Center)
      .part(&self.part(CardPart::Action))
      .child(action);
    Some(self.own_presses(row))
  }

  /// The header: the title and the description, and the action at its end.
  /// `None` for a card with neither.
  pub fn header(&mut self) -> Option<Row> {
    let text = self.text();
    let action = self.action();
    if text.is_none() && action.is_none() {
      return None;
    }
    let mut header = Row::new()
      .width(Dimension::Pct(100.0))
      .align_items(Alignment::Start)
      .part(&self.part(CardPart::Header));
    match text {
      Some(text) => header = header.child(text),
      // Without a title the action still stands at the end.
      None => header = header.justify(Justify::End),
    }
    if let Some(action) = action {
      header = header.child(action);
    }
    Some(header)
  }

  /// The body: a column with what the app put there, its children aligned
  /// as the app said. `None` for a card with nothing in it.
  pub fn body(&mut self) -> Option<Column> {
    if self.body.is_empty() {
      return None;
    }
    let mut body = Column::new()
      .width(Dimension::Pct(100.0))
      .part(&self.part(CardPart::Body))
      .with_children(std::mem::take(&mut self.body));
    // A card of a height of its own gives what its header leaves to what is in it: a child with `flex` fills it.
    if self.has_height() {
      body = body.flex(1.0);
    }
    body.update_node(|node| self.body_edits.apply(node));
    Some(body)
  }

  /// The content: the header over the body, padded. `None` for a card with
  /// neither.
  pub fn content(&mut self) -> Option<Column> {
    let header = self.header();
    let body = self.body();
    if header.is_none() && body.is_none() {
      return None;
    }
    let mut content = Column::new()
      .width(Dimension::Pct(100.0))
      .part(&self.part(CardPart::Content));
    // A card of a height of its own gives what its footer leaves to its content: the footer stays at the bottom.
    if self.has_height() {
      content = content.flex(1.0);
    }
    if let Some(header) = header {
      content = content.child(header);
    }
    if let Some(body) = body {
      content = content.child(body);
    }
    Some(content)
  }

  /// The footer: a row at the end of the card with what the app put there.
  /// `None` for a card with nothing in it.
  pub fn footer(&mut self) -> Option<Row> {
    if self.footer.is_empty() {
      return None;
    }
    let footer = Row::new()
      .width(Dimension::Pct(100.0))
      .align_items(Alignment::Center)
      .justify(Justify::End)
      .part(&self.part(CardPart::Footer))
      .with_children(std::mem::take(&mut self.footer));
    Some(self.own_presses(footer))
  }

  /// The surface of a card that is pressed as a whole, in the style of its
  /// root and where the app placed it, with nothing in it yet: a click, Enter and Space press it, Tab
  /// reaches it, and a disabled one takes nothing. It is a button to what
  /// reads the tree, called by the card's label or its title.
  pub fn pressed_root(&self) -> components::Button {
    let mut root = pressable(&self.part(CardPart::Root), self.disabled)
      .justify(Justify::Start)
      .align_items(Alignment::Stretch)
      // The controls in its action and its footer are stops of Tab of their own, after the card.
      .stops_inside(true)
      .describe("a11y_role", "button");
    if let Some(name) = self.name() {
      root = root.describe("a11y_name", name);
    }
    if !self.disabled {
      for handler in &self.on_click {
        root = root.on_click(handler.clone());
      }
    }
    if let Some(id) = &self.id {
      root = root.id(id.clone());
    }
    if let Some(key) = &self.key {
      root = root.key(key.clone());
    }
    root.update_node(|node| self.root_edits.apply(node));
    root
  }

  /// The surface of a card that is read, in the style of its root and where
  /// the app placed it, with nothing in it yet: a group to what reads the tree, called by the card's
  /// label or its title.
  pub fn read_root(&self) -> Column {
    let mut root = Column::new()
      .part(&self.part(CardPart::Root))
      .describe("a11y_role", "group");
    if let Some(name) = self.name() {
      root = root.describe("a11y_name", name);
    }
    if let Some(id) = &self.id {
      root = root.id(id.clone());
    }
    if let Some(key) = &self.key {
      root = root.key(key.clone());
    }
    root.update_node(|node| self.root_edits.apply(node));
    root
  }

  /// How the default renderer builds a card: the content over the footer,
  /// on the surface.
  pub fn render(mut self) -> Element {
    let parts: Vec<Element> = [self.content().map(Element::from), self.footer().map(Element::from)]
      .into_iter()
      .flatten()
      .collect();
    if self.pressable {
      // What is pressed is a row: the content and the footer are in a column as wide as it.
      let column = Column::new()
        .flex(1.0)
        .min_width(Dimension::Px(0.0))
        .with_children(parts);
      self.pressed_root().child(column).into()
    } else {
      self.read_root().with_children(parts).into()
    }
  }
}

/// A text of a card in the style of `part`, as wide as the room it has: a
/// longer one goes on to the next line. A row would lay it out as wide as it
/// is and cut it.
fn wrapping(part: &ResolvedPart, content: &str) -> Column {
  let fill = Dimension::Pct(100.0);
  Column::new()
    .width(fill)
    .part(part)
    .child(part.text(content).width(fill))
}

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

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

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

  /// The design's card (`pencil/lurq-design-system.pen`, Card and
  /// Card/Simple): a surface as wide as the room it is given, in the card's color with an edge of the
  /// border's color, corners of `radius-xl` and the small shadow. Its header
  /// and its body are padded 24 with 24 between them; the title is 16/600
  /// with the description 6 under it in 14 of the muted color, and what is in
  /// the body is 16 apart. The footer is set off by a line and padded 16
  /// and 24, its buttons 8 apart at its end. The elevated card has the
  /// medium shadow and no edge, the filled one the muted color and no edge.
  /// A small card is padded 16, with a title of 14 and a description of 13.
  /// A card that is pressed takes an edge of the ring's color and the
  /// medium shadow under the pointer.
  fn recipe() -> Recipe {
    use CardPart::{Action, Body, Content, Description, Footer, Header, Root, Text, Title};
    use CardSize::Sm;
    use CardState::{Disabled, Pressable};
    use CardVariant::{Elevated, Filled, Outline};
    use PaletteColor::*;
    let edge = |color: PaletteColor| Edge::inside(BorderSize::Sm, color);
    let when_pressable = || Selector::new().state(Pressable);
    Recipe::new()
      .base(Root, |s| {
        fading(
          s.width(Length::Fill)
            .background(Card)
            .foreground(CardForeground)
            .radius(RadiusSize::Xl),
        )
      })
      .variant(Outline, Root, |s| s.border(edge(PaletteColor::Border)).shadow(ShadowStyle::Sm))
      .variant(Elevated, Root, |s| s.shadow(ShadowStyle::Md))
      .variant(Filled, Root, |s| s.background(Muted))
      .base(Content, |s| s.padding_x(24.0).padding_y(24.0).gap(24.0))
      .base(Header, |s| s.gap(16.0))
      .base(Text, |s| s.gap(6.0))
      .base(Title, |s| {
        s.typography(TypographyStyle::Body)
          .font_size(16.0)
          .weight(FontWeight::SemiBold)
          .foreground(CardForeground)
      })
      .base(Description, |s| {
        s.typography(TypographyStyle::Description)
          .font_size(14.0)
          .foreground(MutedForeground)
      })
      .base(Action, |s| s.gap(8.0))
      .base(Body, |s| s.gap(16.0))
      .base(Footer, |s| s.gap(8.0).padding_x(24.0).padding_y(16.0))
      // The line over the footer is the content's: it is there only where the footer has content over it.
      .state(CardState::Footer, Content, |s| s.underline(edge(PaletteColor::Border)))
      .size(Sm, Content, |s| s.padding_x(16.0).padding_y(16.0).gap(16.0))
      .size(Sm, Header, |s| s.gap(12.0))
      .size(Sm, Title, |s| s.font_size(14.0))
      .size(Sm, Description, |s| s.font_size(13.0).line_height(1.4))
      .size(Sm, Body, |s| s.gap(12.0))
      .size(Sm, Footer, |s| s.padding_x(16.0).padding_y(12.0))
      .state(Pressable, Root, |s| s.cursor(CursorIcon::Pointer))
      .when(when_pressable().hovered(), Root, |s| s.border(edge(Ring)).shadow(ShadowStyle::Md))
      // Held down it sinks back to the page, and keeps the edge it has under the pointer.
      .when(when_pressable().pressed(), Root, |s| s.border(edge(Ring)).shadow(ShadowStyle::Sm))
      .when(when_pressable().focus_visible(), Root, |s| s.focus_ring())
      .state(Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
  }
}