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
//! A key of the keyboard, the keys of a shortcut pressed together, or steps pressed one after another, read and
//! not operated; and a short text of code in a run of text, which is the same kind of thing.

use std::sync::Arc;

use super::{
  code_tokens::{TokenStyles, code_tokens},
  names,
  part_style::PartStyle,
  recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe},
  theme::{Themed, current_theme},
};
use crate::{
  app::{
    Accelerator,
    theme::{BorderSize, PaletteColor, RadiusSize, Theme, TypographyStyle},
  },
  code::{CodeToken, CodeTokenizer},
  components::Row,
  core::KeyWords,
  layout::Alignment,
  node::{Element, Node, TextColor, border::Border as Line},
};

/// How a key is drawn.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum KbdVariant {
  /// Each key in a box of its own: on a muted fill, with an edge.
  #[default]
  Default,
  /// The keys of a step written as one text, with no box, in the muted color: "Ctrl+K", or "⌘K" on a Mac. What a
  /// menu writes at the end of an item.
  Plain,
}

names!(KbdVariant {
  Default => "default",
  Plain => "plain",
});

/// How tall a key is: 16, 20 or 24.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum KbdSize {
  /// 16 high, at 10: a key in a tooltip, or in a line of small text.
  Sm,
  /// 20 high, at 11.
  #[default]
  Md,
  /// 24 high, at 12: a list of the shortcuts of an app.
  Lg,
}

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

/// Whose names a key is written with.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum KeyPlatform {
  /// In words, as Windows and Linux write them: "Ctrl", "Alt", "Shift", "Enter". `Mod` is Ctrl.
  #[default]
  Standard,
  /// With a Mac's glyphs: ⌃ ⌥ ⇧ ⌘, ↩ ⌫ ⇥, the modifiers of a shortcut first and in that order, as a Mac's menus
  /// write them. `Mod` is ⌘.
  Mac,
}

impl KeyPlatform {
  /// The platform the app is built for: a Mac's glyphs on macOS and iOS, words elsewhere.
  pub fn current() -> Self {
    if cfg!(any(target_os = "macos", target_os = "ios")) {
      Self::Mac
    } else {
      Self::Standard
    }
  }
}

/// The parts of a key, a shortcut or a sequence a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KbdPart {
  /// What holds the keys, in a row.
  Root,
  /// One key: its box, its fill and its edge.
  Key,
  /// The text on a key; in [`KbdVariant::Plain`], the text of a step.
  Label,
  /// What stands between the steps of a sequence: "then".
  Separator,
}

names!(KbdPart {
  Root => "root",
  Key => "key",
  Label => "label",
  Separator => "separator",
});

/// The states of a key a recipe styles. It has nothing the pointer or the keyboard does to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KbdState {
  /// It is a sequence of steps pressed one after another.
  Sequence,
  /// It is written with a Mac's glyphs.
  Mac,
}

names!(KbdState {
  Sequence => "sequence",
  Mac => "mac",
});

/// One key as it is drawn: what is on it, and what it is called.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KbdKey {
  /// What is drawn on the key: "Ctrl", "⌘", "K".
  pub label: Arc<str>,
  /// What it is called in words: "Ctrl", "Cmd", "K".
  pub name: Arc<str>,
  /// Whether it is a modifier: Ctrl, Alt, Shift, Meta.
  pub modifier: bool,
}

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

/// A key of the keyboard, a shortcut, or a sequence of them: what a person presses to do something.
///
/// ```
/// use lurq::ui::{Kbd, KbdSize, KeyPlatform};
///
/// let escape = Kbd::new("Esc");
/// // A key each: "Ctrl" and "K". `Mod` is Ctrl, and ⌘ on a Mac.
/// let search = Kbd::shortcut("Mod+K").platform(KeyPlatform::current());
/// // ⇧ ⌘ P on a Mac: the modifiers first, in a Mac's order.
/// let palette = Kbd::shortcut("Ctrl+Shift+P").platform(KeyPlatform::Mac);
/// // Pressed one after another: G, then D.
/// let dashboard = Kbd::sequence(["G", "D"]);
/// let chord = Kbd::sequence(["Ctrl+K", "Ctrl+S"]).size(KbdSize::Lg);
/// ```
///
/// Keys are named as lurq names them in a [`KeyboardEvent`](crate::app::events::KeyboardEvent) (`ArrowUp`,
/// `Escape`, `Backspace`), or as a person writes them (`Up` is written as it is, `Esc`, `Del`), in any case. A
/// letter is drawn in capitals. In a shortcut the keys are parted by `+`, and a `+` after another, or alone, is the
/// key of that name: `Ctrl++`.
///
/// A key is read and not operated: it takes no press, no focus and no stop of Tab. To what reads the tree it is one
/// text, called by its keys in words: "Ctrl+K", "G then D".
pub struct Kbd {
  steps: Vec<Vec<Arc<str>>>,
  platform: KeyPlatform,
  variant: Name,
  size: Name,
  separator_text: Arc<str>,
  label: Option<Arc<str>>,
  states: Vec<Name>,
  rules: Recipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl Kbd {
  fn of(steps: Vec<Vec<Arc<str>>>) -> Self {
    Self {
      steps,
      platform: KeyPlatform::default(),
      variant: KbdVariant::default().into(),
      size: KbdSize::default().into(),
      separator_text: super::current_locale().keys.then.clone(),
      label: None,
      states: Vec::new(),
      rules: Recipe::new(),
      id: None,
      key: None,
    }
  }

  /// One key: "Ctrl", "Esc", "Page Up". A `+` in it is drawn as it is.
  pub fn new(key: &str) -> Self {
    Self::of(vec![vec![Arc::from(key)]])
  }

  /// The keys of a shortcut, pressed together: "Ctrl+K", a key each.
  pub fn shortcut(keys: &str) -> Self {
    Self::of(vec![split(keys)])
  }

  /// Steps pressed one after another, each a key or a shortcut: `["G", "D"]`, `["Ctrl+K", "Ctrl+S"]`.
  pub fn sequence<S: AsRef<str>>(steps: impl IntoIterator<Item = S>) -> Self {
    Self::of(steps.into_iter().map(|step| split(step.as_ref())).collect())
  }

  /// The keys of an [`Accelerator`] of the app's menu: its modifiers, then its key.
  pub fn accelerator(accelerator: &Accelerator) -> Self {
    let modifiers = accelerator.modifiers;
    let mut keys: Vec<Arc<str>> = [
      (modifiers.ctrl, "Ctrl"),
      (modifiers.alt, "Alt"),
      (modifiers.shift, "Shift"),
      (modifiers.meta, "Meta"),
    ]
    .into_iter()
    .filter(|(held, _)| *held)
    .map(|(_, name)| Arc::from(name))
    .collect();
    keys.push(accelerator.key.clone());
    Self::of(vec![keys])
  }

  /// Whose names the keys are written with: words unless told. [`KeyPlatform::current`] is the platform the app
  /// runs on.
  pub fn platform(mut self, platform: KeyPlatform) -> Self {
    self.platform = platform;
    self
  }

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

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

  /// The word that stands between the steps of a sequence, and that they are called by between them: "then"
  /// unless told.
  pub fn separator_text(mut self, text: &str) -> Self {
    self.separator_text = Arc::from(text);
    self
  }

  /// What the keys are called to what reads the tree, in place of their words: "Search" for `Ctrl+K`.
  pub fn label(mut self, label: &str) -> Self {
    self.label = Some(Arc::from(label));
    self
  }

  /// Puts the keys in a state the theme's recipe names, or takes them 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 over what the theme gives it.
  pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.rules = self.rules.base(part, style);
    self
  }

  /// Lays rules over the theme's recipe for these keys: what the component they are in says of them.
  pub fn rules(mut self, rules: &Recipe) -> Self {
    self.rules = self.rules.extend(rules);
    self
  }

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

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

  /// Builds the keys in `theme`. Converting them into an element does this in the theme of what is being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    let case = Case {
      variant: Some(self.variant),
      size: Some(self.size),
      density: None,
      breakpoint: super::current_breakpoint(),
      states: self.states.clone(),
    }
    .state(KbdState::Sequence, self.steps.len() > 1)
    .state(KbdState::Mac, self.platform == KeyPlatform::Mac);
    let platform = self.platform;
    let view = KbdView {
      steps: {
        let locale = super::current_locale();
        self
          .steps
          .iter()
          .map(|step| keys_of(step, platform, &locale.keys))
          .collect()
      },
      platform,
      variant: self.variant,
      size: self.size,
      separator_text: self.separator_text,
      label: self.label,
      recipe: theme
        .resolve::<Kbd>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<Kbd>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

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

/// The keys of a shortcut as written, parted by `+`: a `+` where a key is to start is the key of that name.
fn split(keys: &str) -> Vec<Arc<str>> {
  let mut parted = Vec::new();
  let mut key = String::new();
  for character in keys.chars() {
    if character == '+' && !key.trim().is_empty() {
      parted.push(Arc::from(key.trim()));
      key.clear();
    } else if character == '+' {
      key = "+".to_owned();
    } else {
      key.push(character);
    }
  }
  if !key.trim().is_empty() {
    parted.push(Arc::from(key.trim()));
  } else if key == " " {
    parted.push(Arc::from(" "));
  }
  parted
}

/// A modifier: where a Mac puts it among the others, its word, its word on a Mac, and its glyph, in the words of
/// `keys`.
fn modifier<'a>(folded: &str, platform: KeyPlatform, keys: &'a KeyWords) -> Option<(u8, &'a str, &'a str, &'a str)> {
  Some(match folded {
    "ctrl" | "control" => (0, &keys.ctrl, &keys.ctrl, "⌃"),
    "alt" | "option" | "opt" => (1, &keys.alt, &keys.option, "⌥"),
    "shift" => (2, &keys.shift, &keys.shift, "⇧"),
    "meta" => (3, &keys.meta, &keys.cmd, "⌘"),
    "cmd" | "command" => (3, &keys.cmd, &keys.cmd, "⌘"),
    "super" => (3, &keys.super_key, &keys.cmd, "⌘"),
    "win" | "windows" => (3, &keys.win, &keys.cmd, "⌘"),
    "mod" if platform == KeyPlatform::Mac => (3, &keys.ctrl, &keys.cmd, "⌘"),
    "mod" => (0, &keys.ctrl, &keys.cmd, "⌘"),
    _ => return None,
  })
}

/// A key that is not a modifier, by the name lurq gives it or a person writes: its label in words, its label on a
/// Mac, and its word, in the words of `keys`.
fn named<'a>(folded: &str, keys: &'a KeyWords) -> Option<(&'a str, &'a str, &'a str)> {
  Some(match folded {
    "enter" | "return" => (&keys.enter, "↩", &keys.enter),
    "escape" | "esc" => (&keys.esc, &keys.esc, &keys.esc),
    "backspace" => (&keys.backspace, "⌫", &keys.backspace),
    "delete" | "del" => (&keys.delete, "⌦", &keys.delete_name),
    "tab" => (&keys.tab, "⇥", &keys.tab),
    "space" | "spacebar" => (&keys.space, &keys.space, &keys.space),
    "arrowup" => ("↑", "↑", &keys.up),
    "arrowdown" => ("↓", "↓", &keys.down),
    "arrowleft" => ("←", "←", &keys.left),
    "arrowright" => ("→", "→", &keys.right),
    "pageup" => (&keys.page_up, "⇞", &keys.page_up),
    "pagedown" => (&keys.page_down, "⇟", &keys.page_down),
    "home" => (&keys.home, "↖", &keys.home),
    "end" => (&keys.end, "↘", &keys.end),
    "capslock" => (&keys.caps_lock, "⇪", &keys.caps_lock),
    _ => return None,
  })
}

/// The keys of one step as they are drawn on `platform`: on a Mac its modifiers first, in a Mac's order.
fn keys_of(step: &[Arc<str>], platform: KeyPlatform, words: &KeyWords) -> Vec<KbdKey> {
  let mac = platform == KeyPlatform::Mac;
  let mut keys: Vec<(u8, KbdKey)> = step
    .iter()
    .map(|written| {
      if written.as_ref() == " " {
        let space = words.space.clone();
        return (
          u8::MAX,
          KbdKey {
            label: space.clone(),
            name: space,
            modifier: false,
          },
        );
      }
      let folded: String = written
        .chars()
        .filter(|character| !character.is_whitespace())
        .flat_map(char::to_lowercase)
        .collect();
      if let Some((rank, word, mac_word, glyph)) = modifier(&folded, platform, words) {
        let (label, name) = if mac { (glyph, mac_word) } else { (word, word) };
        return (
          rank,
          KbdKey {
            label: Arc::from(label),
            name: Arc::from(name),
            modifier: true,
          },
        );
      }
      if let Some((word, mac_label, name)) = named(&folded, words) {
        let label = if mac { mac_label } else { word };
        let name = if mac && name == &*words.enter {
          &*words.return_key
        } else {
          name
        };
        return (
          u8::MAX,
          KbdKey {
            label: Arc::from(label),
            name: Arc::from(name),
            modifier: false,
          },
        );
      }
      // A letter is drawn in capitals; anything else as it is written.
      let label: Arc<str> = if written.chars().count() == 1 {
        Arc::from(written.to_uppercase())
      } else {
        written.clone()
      };
      (
        u8::MAX,
        KbdKey {
          label: label.clone(),
          name: label,
          modifier: false,
        },
      )
    })
    .collect();
  if mac {
    // Stable: what is not a modifier keeps its place after them.
    keys.sort_by_key(|(rank, _)| *rank);
  }
  keys.into_iter().map(|(_, key)| key).collect()
}

/// Keys as a renderer sees them: each step's keys, and the style of the parts.
pub struct KbdView {
  /// The steps pressed one after another, each the keys pressed together, as they are drawn.
  pub steps: Vec<Vec<KbdKey>>,
  pub platform: KeyPlatform,
  pub variant: Name,
  pub size: Name,
  /// The word that stands between steps.
  pub separator_text: Arc<str>,
  /// What the keys are called to what reads the tree, where the app gave other words than theirs.
  pub label: Option<Arc<str>>,
  /// The style of each part.
  pub recipe: ResolvedRecipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl KbdView {
  /// The style of a part, as these keys are to be drawn.
  pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
    self.recipe.part(part)
  }

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

  /// Whether the keys are drawn as text, with no box ([`KbdVariant::Plain`]).
  pub fn plain(&self) -> bool {
    self.variant == Name::from(KbdVariant::Plain)
  }

  /// The keys of one step written as one text: "Ctrl+K" in words, "⌘K" on a Mac.
  pub fn written(&self, step: &[KbdKey]) -> String {
    let join = if self.platform == KeyPlatform::Mac { "" } else { "+" };
    step.iter().map(|key| key.label.as_ref()).collect::<Vec<_>>().join(join)
  }

  /// What the keys are called to what reads the tree: the app's label, or their words, parted by `+` within a
  /// step and by the separator's word between steps. "Ctrl+K", "Cmd+Shift+P", "G then D".
  pub fn name(&self) -> String {
    if let Some(label) = &self.label {
      return label.to_string();
    }
    self
      .steps
      .iter()
      .map(|step| step.iter().map(|key| key.name.as_ref()).collect::<Vec<_>>().join("+"))
      .collect::<Vec<_>>()
      .join(&format!(" {} ", self.separator_text))
  }

  /// The root in its style, with nothing in it yet: one text to what reads the tree, called by [`name`](Self::name).
  pub fn root(&self) -> Row {
    let mut root = Row::new()
      .align_items(Alignment::Center)
      .part(&self.part(KbdPart::Root))
      .describe("a11y_role", "text")
      .describe("a11y_name", self.name());
    if let Some(id) = &self.id {
      root = root.id(id.clone());
    }
    if let Some(key) = &self.key {
      root = root.key(key.clone());
    }
    root
  }

  /// A text in the style of the label.
  pub fn label(&self, text: &str) -> Row {
    let part = self.part(KbdPart::Label);
    Row::new().part(&part).child(part.text(text).nowrap())
  }

  /// One key in its box.
  pub fn key_cap(&self, key: &KbdKey) -> Row {
    Row::new()
      .align_items(Alignment::Center)
      .part(&self.part(KbdPart::Key))
      .child(self.label(&key.label))
  }

  /// What stands between two steps.
  pub fn between(&self) -> Row {
    let part = self.part(KbdPart::Separator);
    Row::new().part(&part).child(part.text(&self.separator_text).nowrap())
  }

  /// How the default renderer builds keys: each key in its box, or each step as one text where they are plain, and
  /// the separator between steps.
  pub fn render(self) -> Element {
    let mut root = self.root();
    for (index, step) in self.steps.iter().enumerate() {
      if index > 0 {
        root = root.child(self.between());
      }
      if self.plain() {
        root = root.child(self.label(&self.written(step)));
      } else {
        for key in step {
          root = root.child(self.key_cap(key));
        }
      }
    }
    root.into()
  }
}

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

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

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

  /// The design's key (`pencil/lurq-design-system.pen`: Kbd, and the keys of the search field, the command
  /// palette, the shortcut recorder and the tablet's list of shortcuts): 20 high, padded 6, on `Muted` with an edge
  /// of `Border` and the radius `Sm`, its text 11 in the family of code in `MutedForeground`. The keys of a shortcut
  /// are 4 apart, with nothing between them. Small is 16, padded 4, at 10, as the tooltip's key; large is 24, padded
  /// 7, at 12 and 6 apart, as the list of shortcuts. Plain is the menu's: the text alone.
  fn recipe() -> Recipe {
    use KbdPart::{Key, Label, Root, Separator};
    use PaletteColor::*;
    let mut recipe = Recipe::new()
      .base(Root, |s| s.gap(4.0))
      .base(Key, |s| {
        s.height(20.0)
          .padding_x(6.0)
          .radius(RadiusSize::Sm)
          .background(Muted)
          .foreground(MutedForeground)
          .border(Line::inside(BorderSize::Sm, PaletteColor::Border))
      })
      .base(Label, |s| {
        s.typography(TypographyStyle::Mono)
          .font_size(11.0)
          .line_height(1.0)
          .foreground(MutedForeground)
      })
      .base(Separator, |s| {
        s.typography(TypographyStyle::Caption)
          .font_size(11.0)
          .foreground(MutedForeground)
      });
    for (size, height, padding, font, gap) in [(KbdSize::Sm, 16.0, 4.0, 10.0, 4.0), (KbdSize::Lg, 24.0, 7.0, 12.0, 6.0)]
    {
      recipe = recipe
        .size(size, Root, |s| s.gap(gap))
        .size(size, Key, |s| s.height(height).padding_x(padding))
        .size(size, Label, |s| s.font_size(font))
        .size(size, Separator, |s| s.font_size(font));
    }
    recipe
  }
}

/// The parts of a text of code a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InlineCodePart {
  /// The muted fill around the text.
  Root,
  /// The text, in the family of code.
  Label,
}

names!(InlineCodePart {
  Root => "root",
  Label => "label",
});

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

/// A short text of code in a run of text: a call, a name, a path, a command.
///
/// ```
/// use lurq::ui::InlineCode;
///
/// let call = InlineCode::new("ctx.theme()");
/// ```
///
/// It is read and not operated, and is not cut: it is as wide as its text. Given a [`language`](Self::language), its
/// words are colored as a code block colors them: told apart by the language's tokenizer, in the theme's code colors.
/// To what reads the tree it is `code`, called by its text.
pub struct InlineCode {
  text: Arc<str>,
  language: Option<Arc<str>>,
  tokenizer: Option<CodeTokenizer>,
  states: Vec<Name>,
  rules: Recipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl InlineCode {
  /// A text of code that says `text`.
  pub fn new(text: &str) -> Self {
    Self {
      text: Arc::from(text),
      language: None,
      tokenizer: None,
      states: Vec::new(),
      rules: Recipe::new(),
      id: None,
      key: None,
    }
  }

  /// The language of the text (`rust`, `sql`): its words are told apart by the language's tokenizer and drawn in the
  /// theme's code colors, as in a code block. Plain where the language has no tokenizer.
  ///
  /// ```
  /// use lurq::ui::InlineCode;
  ///
  /// let call = InlineCode::new("ctx.theme().set_mode(Mode::Dark)").language("rust");
  /// ```
  pub fn language(mut self, language: &str) -> Self {
    self.language = Some(Arc::from(language));
    self
  }

  /// Tells the tokens of the text apart with `tokenizer`, in place of its language's.
  pub fn tokenizer(mut self, tokenizer: impl Into<CodeTokenizer>) -> Self {
    self.tokenizer = Some(tokenizer.into());
    self
  }

  /// Styles the tokens named `name` over the theme's code colors, as a code block's
  /// [`token_style`](super::CodeBlock::token_style) does.
  pub fn token_style(self, name: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
    self.style(name, style)
  }

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

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

  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 text in `theme`. Converting it 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,
    };
    let colored = self.language.is_some() || self.tokenizer.is_some();
    let tokens = code_tokens(&self.text, self.language.as_deref(), self.tokenizer.as_ref());
    let view = InlineCodeView {
      text: self.text,
      language: self.language,
      tokens: colored.then_some(tokens),
      recipe: theme
        .resolve::<InlineCode>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<InlineCode>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

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

/// A text of code as a renderer sees it.
pub struct InlineCodeView {
  pub text: Arc<str>,
  pub language: Option<Arc<str>>,
  /// The tokens of the text, where it has a language or a tokenizer.
  pub tokens: Option<Arc<[CodeToken]>>,
  /// The style of each part.
  pub recipe: ResolvedRecipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

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

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

  /// The fill in its style, with nothing in it yet: `code` to what reads the tree, called by its text.
  pub fn root(&self) -> Row {
    let mut root = Row::new()
      .align_items(Alignment::Center)
      .part(&self.part(InlineCodePart::Root))
      .describe("a11y_role", "code")
      .describe("a11y_name", self.text.clone());
    if let Some(id) = &self.id {
      root = root.id(id.clone());
    }
    if let Some(key) = &self.key {
      root = root.key(key.clone());
    }
    root
  }

  /// The text, in the label's style, its tokens in theirs where it has a language.
  pub fn label(&self) -> Element {
    let part = self.part(InlineCodePart::Label);
    let Some(tokens) = &self.tokens else {
      return part.text(&self.text).nowrap().into();
    };
    let rest = part.rest();
    let mut base = rest.text.resolve(self.theme());
    base.color = match rest.foreground.unwrap_or(PaletteColor::Foreground.into()) {
      TextColor::Color(color) => color,
      TextColor::Palette(role) => self.theme().palette_color(role),
    };
    let styles = TokenStyles::new(&self.recipe, &["root", "label"], base, None);
    let spans = styles.spans(&self.text, 0..self.text.len(), tokens);
    Element::from_node(Node::rich_text(spans).text_wrap(false))
  }

  /// How the default renderer builds it: the text on its fill.
  pub fn render(self) -> Element {
    let label = self.label();
    self.root().child(label).into()
  }
}

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

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

  /// The design's inline code (`pencil/lurq-design-system.pen`: Inline Code, in the prose of Typography and the
  /// Markdown document): 13 in the family of code in `Foreground`, on `Muted` with the radius `Sm`, padded 5 across
  /// and 1 above and below.
  fn recipe() -> Recipe {
    use InlineCodePart::{Label, Root};
    Recipe::new()
      .base(Root, |s| {
        s.padding_x(5.0)
          .padding_y(1.0)
          .radius(RadiusSize::Sm)
          .background(PaletteColor::Muted)
          .foreground(PaletteColor::Foreground)
      })
      .base(Label, |s| {
        s.typography(TypographyStyle::Mono)
          .font_size(13.0)
          .foreground(PaletteColor::Foreground)
      })
  }
}