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
//! An input: one line of text that a person types, bound to a signal.

use std::sync::Arc;

use super::{
  field::{FieldControl, InField},
  icon::Icon,
  names,
  part_style::{Length, PartStyle},
  recipe::{Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
  text_box::{self, BoxStates, EditHandler, Judgment, TextBoxSize},
  theme::{Themed, current_theme},
};
use crate::{
  app::{
    events::{KeyboardEvent, TextInputEvent},
    theme::{ControlSize, IconSize, PaletteColor, Theme, TypographyStyle},
  },
  components::{self, Row, Stack},
  core::Signal,
  layout::{Alignment, StackAlignment, layout_kind::Justify, text_style::TextStyle},
  node::{Element, HitTestBehavior, dimension::Dimension},
};

/// The parts of an input a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InputPart {
  /// The place the input takes: its width, and the room between its icon and its text.
  Root,
  /// The box that is typed in and focused: its edge, its fill, its height, and the type of its value.
  Control,
  /// What the box says while it is empty. It has the type of the control, in its own color.
  Placeholder,
  /// The glyph at the start of the box, where the input has one.
  Icon,
  /// What would complete what is typed, drawn after it: its foreground is its color, and its opacity how faint
  /// it is.
  Completion,
  /// The wavy lines under ranges the app marks: its foreground is their color.
  Squiggle,
}

names!(InputPart {
  Root => "root",
  Control => "control",
  Placeholder => "placeholder",
  Icon => "icon",
  Completion => "completion",
  Squiggle => "squiggle",
});

/// The sizes of an input: the heights of the theme's controls, and the type of each. A textarea has the same.
pub type InputSize = TextBoxSize;

/// The states of an input a recipe styles, besides what the pointer and the
/// keyboard do to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InputState {
  /// What it holds is wrong: its edge is in the destructive color.
  Invalid,
  /// What it holds is allowed, with a caveat: its edge is in the warning color.
  Warning,
  /// What it holds was checked and is right: its edge is in the success color.
  Valid,
  /// It can be read, selected and copied, and not changed.
  ReadOnly,
  /// It takes no input.
  Disabled,
  /// It is as wide as what holds it.
  FullWidth,
  /// It has an icon at its start.
  Icon,
  /// It is in a fluid field ([`Field::fluid`](super::Field::fluid)): the field's label is inside its box, over
  /// what it holds.
  Fluid,
}

names!(InputState {
  Invalid => "invalid",
  Warning => "warning",
  Valid => "valid",
  ReadOnly => "read_only",
  Disabled => "disabled",
  FullWidth => "full_width",
  Icon => "icon",
  Fluid => "fluid",
});

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

/// An input: one line of text that a person types. A name, an email
/// address, a search.
///
/// ```
/// use lurq::{core::Signal, ui::{Input, icons}};
///
/// let name = Signal::new(String::new());
/// let input = Input::new(name.clone()).placeholder("Display name");
/// let search = Input::new(Signal::new(String::new())).placeholder("Search components").icon(icons::SEARCH);
/// let email = Input::new(Signal::new("ivan@".to_owned())).invalid(true);
/// ```
///
/// It is the engine's [`TextInput`](crate::components::TextInput) in the
/// design's dress: what is typed goes into the signal it is given, and what
/// the app sets on the signal is what it shows. Its edge says its state: the
/// ring's color under the pointer and, twice as thick, while it is focused;
/// the destructive, warning or success color where the app says what it
/// holds is wrong, doubtful or right.
#[derive(Clone)]
pub struct Input {
  value: Signal<String>,
  placeholder: Option<Arc<str>>,
  icon: Option<Name>,
  pub(crate) boxed: BoxStates,
  full_width: bool,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  on_input: Vec<EditHandler>,
  on_submit: Vec<SubmitHandler>,
  /// Called as the focus leaves the control: for a component that commits a text then.
  pub(crate) on_leave: Vec<Arc<dyn Fn() + Send + Sync>>,
  completion: Option<Arc<str>>,
  squiggles: Vec<std::ops::Range<usize>>,
  name: Option<Arc<str>>,
  id: Option<Arc<str>>,
  pub(crate) key: Option<Arc<str>>,
}

/// What hears Enter in a box: what it holds.
pub(crate) type SubmitHandler = Arc<dyn Fn(&str) + Send + Sync>;

impl Input {
  /// An input bound to `value`: it shows what the signal holds, and what is typed is set on it.
  pub fn new(value: Signal<String>) -> Self {
    Self {
      value,
      placeholder: None,
      icon: None,
      boxed: BoxStates::default(),
      full_width: false,
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      on_input: Vec::new(),
      on_submit: Vec::new(),
      on_leave: Vec::new(),
      completion: None,
      squiggles: Vec::new(),
      name: None,
      id: None,
      key: None,
    }
  }

  /// What would complete what is typed, drawn after it in the muted foreground while the input has the focus
  /// with the caret at its end: Tab puts it there, as an edit of the input's. The app gives the rest of the
  /// word or the line, for what the input holds now, and none (`""`) where it has nothing to offer.
  pub fn completion(mut self, completion: &str) -> Self {
    self.completion = (!completion.is_empty()).then(|| Arc::from(completion));
    self
  }

  /// Wavy lines in the destructive color under ranges of what the input holds, bytes of its text: what a
  /// spelling checker of the app's marks.
  pub fn squiggles(mut self, ranges: impl IntoIterator<Item = std::ops::Range<usize>>) -> Self {
    self.squiggles = ranges.into_iter().collect();
    self
  }

  /// What the input says while it is empty.
  pub fn placeholder(mut self, placeholder: &str) -> Self {
    self.placeholder = Some(Arc::from(placeholder));
    self
  }

  /// A glyph of the theme's set at the start of the box: a search's magnifier.
  pub fn icon(mut self, name: impl Into<Name>) -> Self {
    self.icon = Some(name.into());
    self
  }

  /// The icon at the start, or none: for a component made of an input that has an icon of its own.
  pub(crate) fn with_icon(mut self, icon: Option<Name>) -> Self {
    self.icon = icon;
    self
  }

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

  /// Whether what the input holds is wrong. Of invalid, warning and valid, the first that is set is the one shown.
  pub fn invalid(mut self, invalid: bool) -> Self {
    self.boxed.invalid = invalid;
    self
  }

  /// Whether what the input holds is allowed with a caveat.
  pub fn warning(mut self, warning: bool) -> Self {
    self.boxed.warning = warning;
    self
  }

  /// Whether what the input holds was checked and is right.
  pub fn valid(mut self, valid: bool) -> Self {
    self.boxed.valid = valid;
    self
  }

  /// Whether the input can be read, selected and copied, and not changed. It is still a stop of Tab.
  pub fn read_only(mut self, read_only: bool) -> Self {
    self.boxed.read_only = read_only;
    self
  }

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

  /// What the input is called, to what reads the tree. It draws nothing: the label a person reads is the field's,
  /// above it, which gives the input this name unless it has its own.
  pub fn label(mut self, label: &str) -> Self {
    self.boxed.label = Some(Arc::from(label));
    self
  }

  /// Whether the input is as wide as what holds it, in place of the design's 260.
  pub fn full_width(mut self, full_width: bool) -> Self {
    self.full_width = full_width;
    self
  }

  /// Puts the input 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 before an edit is made, with what the input will hold: a handler may refuse it
  /// ([`TextInputEvent::prevent_default`]).
  pub fn on_input(mut self, handler: impl Fn(&TextInputEvent) + Send + Sync + 'static) -> Self {
    self.on_input.push(Arc::new(handler));
    self
  }

  /// Called with what the input holds when Enter is pressed in it, outside a composition and with no modifier: a
  /// search to run, a name to accept. Enter does nothing else then. A second handler is called after the first.
  pub fn on_submit(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
    self.on_submit.push(Arc::new(handler));
    self
  }

  /// The name the input's value has in the form it is in.
  #[cfg(feature = "form")]
  pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
    self.name = Some(name.into());
    self
  }

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

  /// Draws the input as it is under the pointer or focused, 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 control: what is typed in and focused.
  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 input in `theme`. Converting an input into an element does
  /// this in the theme of what is being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    let view = self.view(theme);
    match theme.renderer::<Input>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }

  /// The input as a renderer sees it, in `theme`: what a component made of an input (a password input, a search
  /// field, an input in a group) builds its own nodes from.
  pub(crate) fn view(self, theme: &Theme) -> InputView {
    let case = self
      .boxed
      .case(self.states.clone())
      .state(InputState::FullWidth, self.full_width)
      .state(InputState::Icon, self.icon.is_some());
    InputView {
      value: self.value,
      placeholder: self.placeholder,
      icon: self.icon,
      label: self.boxed.label.clone(),
      invalid: self.boxed.judgment() == Some(Judgment::Invalid),
      read_only: self.boxed.read_only,
      disabled: self.boxed.disabled,
      recipe: theme
        .resolve::<Input>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      forced: self.forced,
      boxed: self.boxed,
      on_input: self.on_input,
      on_submit: self.on_submit,
      on_leave: self.on_leave,
      completion: self.completion,
      squiggles: self.squiggles,
      name: self.name,
      id: self.id,
      key: self.key,
    }
  }
}

impl FieldControl for Input {
  /// Called by the field's label unless it has a name of its own, judged as the field is unless the app judged the
  /// input itself, and disabled where the field is.
  fn in_field(mut self, field: &InField) -> Element {
    self.boxed.in_field(field);
    self.into()
  }

  fn has_fluid_form(&self) -> bool {
    true
  }
}

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

/// An input as a renderer sees it: what it was given, the style of its
/// parts, and its behavior ready to be dressed.
pub struct InputView {
  /// What the input shows and what is typed is set on.
  pub value: Signal<String>,
  pub placeholder: Option<Arc<str>>,
  pub icon: Option<Name>,
  /// What it is called to what reads the tree: its own label, or its field's.
  pub label: Option<Arc<str>>,
  /// Whether what it holds is wrong, as the input shows it.
  pub invalid: bool,
  pub read_only: bool,
  pub disabled: bool,
  /// The style of each part of this input.
  pub recipe: ResolvedRecipe,
  forced: Option<Interaction>,
  boxed: BoxStates,
  on_input: Vec<EditHandler>,
  pub(crate) on_submit: Vec<SubmitHandler>,
  on_leave: Vec<Arc<dyn Fn() + Send + Sync>>,
  /// What would complete what is typed, where the app offers something.
  pub completion: Option<Arc<str>>,
  squiggles: Vec<std::ops::Range<usize>>,
  // Read only where the engine has forms.
  #[cfg_attr(not(feature = "form"), allow(dead_code))]
  name: Option<Arc<str>>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

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

  /// The type of the value: the control's.
  pub fn value_style(&self) -> TextStyle {
    text_box::ink(self.theme(), &self.part(InputPart::Control).rest())
  }

  /// The type of the placeholder: the control's, with what the placeholder's part lays over it.
  pub fn placeholder_style(&self) -> TextStyle {
    let control = self.part(InputPart::Control).rest();
    text_box::ink(self.theme(), &control.merged(&self.part(InputPart::Placeholder).rest()))
  }

  /// How far the text starts from the start of the box: the control's own
  /// padding, and past the icon and the room after it where the input has
  /// one. `None` where the recipe gives the icon no width in pixels.
  pub fn text_start(&self) -> Option<f32> {
    let theme = self.theme();
    let spacing = theme.spacing();
    let padding = self.padding(Side::Start);
    if self.icon.is_none() {
      return Some(padding);
    }
    let icon = match self
      .part(InputPart::Icon)
      .rest()
      .width
      .unwrap_or(Length::Icon(IconSize::Md))
      .resolve(theme)?
    {
      Dimension::Px(px) => px,
      _ => return None,
    };
    let gap = self
      .part(InputPart::Root)
      .rest()
      .gap
      .map(|gap| gap.resolve(&spacing, 0.0))
      .unwrap_or(0.0);
    Some(padding + icon + gap)
  }

  /// The input's behavior with the style of its control: the engine's text
  /// input bound to the value, which is typed in, focused and disabled. A
  /// read-only one refuses every edit.
  pub fn control(&self) -> components::TextInput {
    let control = components::TextInput::new(self.value.clone())
      .single_line()
      .text_style(self.value_style())
      .placeholder_style(self.placeholder_style())
      .part(&self.part(InputPart::Control));
    let mut control = text_box::text_box(control, &self.boxed, self.on_input.clone());
    if let Some(placeholder) = &self.placeholder {
      control = control.placeholder(placeholder);
    }
    if let Some(start) = self.text_start().filter(|_| self.icon.is_some()) {
      control = control.padding_left(start);
    }
    if !self.squiggles.is_empty() {
      let mut squiggles = components::InputSquiggles::new(self.squiggles.iter().cloned());
      if let Some(color) = self.part(InputPart::Squiggle).rest().foreground {
        squiggles = squiggles.color(color);
      }
      control = control.squiggles(squiggles);
    }
    if let Some(completion) = self.completion.clone().filter(|_| !self.read_only && !self.disabled) {
      let part = self.part(InputPart::Completion).rest();
      let mut ghost = components::InputGhost::new(&completion);
      if let Some(color) = part.foreground.clone() {
        ghost = ghost.color(color);
      }
      if let Some(opacity) = part.opacity_in(self.theme()) {
        ghost = ghost.opacity(opacity);
      }
      // Tab takes the completion while the caret is at the end of what is typed with nothing selected: it is
      // put there as an edit of the input's, and Tab goes nowhere.
      let controller = components::TextInputController::new();
      let (taker, value) = (controller.clone(), self.value.clone());
      control = control
        .ghost(ghost)
        .controller(controller)
        .on_key_down(move |event: KeyboardEvent| {
          let plain = !(event.shift || event.ctrl || event.alt || event.meta);
          if event.key != "Tab" || !event.focus_within || !plain || event.composing || event.default_prevented() {
            return;
          }
          let end = value.with_untracked(String::len);
          let at_end = taker
            .selection()
            .is_ok_and(|selection| selection.caret == end && selection.range().is_empty());
          if at_end && end > 0 && taker.replace_selection(&completion).unwrap_or(false) {
            event.prevent_default();
          }
        });
    }
    #[cfg(feature = "form")]
    if let Some(name) = &self.name {
      control = control.name(name.clone());
    }
    if let Some(id) = &self.id {
      control = control.id(id.clone());
    }
    if let Some(key) = &self.key {
      control = control.key(key.clone());
    }
    if !self.on_submit.is_empty() {
      let (value, submit) = (self.value.clone(), self.on_submit.clone());
      control = control.on_key_down(move |event: KeyboardEvent| {
        if submits(&event) {
          event.prevent_default();
          let held = value.get_untracked();
          for handler in &submit {
            handler(&held);
          }
        }
      });
    }
    if !self.on_leave.is_empty() {
      let leave = self.on_leave.clone();
      control = control.on_blur(move || {
        for handler in &leave {
          handler();
        }
      });
    }
    control
  }

  /// The icon in the style of its part, at the start of the box. The pointer
  /// passes through it to the control under it.
  pub fn icon(&self) -> Option<Row> {
    let name = self.icon?;
    let part = self.part(InputPart::Icon);
    let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
    let padding = self.padding(Side::Start);
    Some(
      Row::new()
        .padding_left(padding)
        // In a fluid field the icon stands on the line of the value, under the field's label.
        .padding_top(self.value_line())
        .align_items(Alignment::Center)
        .pointer_events_none()
        .child(
          Row::new()
            .part(&part)
            .child(Icon::new(name).size(side).build(self.theme())),
        ),
    )
  }

  /// The control's padding at its start or its end, in pixels.
  fn padding(&self, side: Side) -> f32 {
    let [_, end, _, start] = self.part(InputPart::Control).rest().paddings();
    let padding = match side {
      Side::Start => start,
      Side::End => end,
    };
    padding
      .map(|padding| padding.resolve(&self.theme().spacing(), 0.0))
      .unwrap_or(0.0)
  }

  /// The control's padding at its start, in pixels.
  pub(crate) fn start_padding(&self) -> f32 {
    self.padding(Side::Start)
  }

  /// Whether the input is in a fluid field, and its box the fluid one.
  pub(crate) fn fluid(&self) -> bool {
    self.boxed.fluid
  }

  /// How far down what is laid over the middle of the box is moved to stand on the line of the value: nothing but in
  /// a fluid field, where the value is under the field's label ([`text_box::value_line`]).
  pub(crate) fn value_line(&self) -> f32 {
    text_box::value_line(&self.part(InputPart::Control).rest(), self.theme())
  }

  /// The room the control keeps at its end for what is `width` wide over it there: its own padding, the width, and
  /// the room an icon has before the text.
  pub(crate) fn end_room(&self, width: f32) -> f32 {
    let gap = self
      .part(InputPart::Root)
      .rest()
      .gap
      .map(|gap| gap.resolve(&self.theme().spacing(), 0.0))
      .unwrap_or(0.0);
    self.padding(Side::End) + width + gap
  }

  /// How a component made of an input builds it: `control` (this input's [`Self::control`], with what the
  /// component adds to it), its icon over its start, and `end` over its end, in from the control's padding there.
  /// Only what is in `end` takes the pointer: around it the pointer reaches the control. In a fluid field both stand
  /// on the line of the value.
  pub(crate) fn render_with_end(&self, control: components::TextInput, end: Option<Row>) -> Stack {
    let mut root = Stack::new()
      .stack_align(StackAlignment::CenterStart)
      .part(&self.part(InputPart::Root))
      .child(control);
    if let Some(icon) = self.icon() {
      root = root.child(icon);
    }
    if let Some(end) = end {
      root = root.child(
        end
          .width(Dimension::Pct(100.0))
          .padding_right(self.padding(Side::End))
          .padding_top(self.value_line())
          .align_items(Alignment::Center)
          .justify(Justify::End)
          .hit_test(HitTestBehavior::ContentOnly),
      );
    }
    root
  }

  /// How the default renderer builds an input: the control, and its icon laid over its start.
  pub fn render(self) -> Element {
    // The control is the box, so that the ring of its focus is its own edge; the icon lies over it.
    let mut root = Stack::new()
      .stack_align(StackAlignment::CenterStart)
      .part(&self.part(InputPart::Root))
      .child(self.control());
    if let Some(icon) = self.icon() {
      root = root.child(icon);
    }
    root.into()
  }
}

/// A side of the control.
#[derive(Clone, Copy)]
enum Side {
  Start,
  End,
}

impl crate::ui::Styled for Input {
  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 Input {
  const NAME: &'static str = "input";
  const ROOT: &'static str = "control";
  type Renderer = InputRenderer;

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

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

  /// The design's input (`pencil/lurq-design-system.pen`, Input): a box 260
  /// wide and 36 high, the background's fill in an edge of 1 in the color of
  /// an input's, 6 round, its text 12 from its edge in the body's type and
  /// its placeholder in the muted foreground. Its edge is the only signal of
  /// its state: the ring's color under the pointer, and a line of 2 inside the
  /// box while it is focused; the destructive, warning and success colors for what it holds.
  /// A disabled one is half opaque on the muted fill; a read-only one is on
  /// the muted fill in the color of a border. Its icon is 16, 8 before the
  /// text. Small is 32 with text of 13, large 40 with text of 15.
  fn recipe() -> Recipe {
    use InputPart::{Control, Icon, Placeholder, Root};
    use PaletteColor::{Foreground, MutedForeground, Success};
    let recipe = Recipe::new()
      .base(Root, |s| s.width(260.0).max_width(Length::Fill).gap(8.0))
      .base(Control, |s| {
        text_box::box_style(s)
          .height(ControlSize::Md)
          .foreground(Foreground)
          .typography(TypographyStyle::Body)
      })
      .base(Icon, |s| s.square(IconSize::Md).foreground(MutedForeground))
      .base(InputPart::Completion, |s| s.foreground(MutedForeground).opacity(0.7))
      .base(InputPart::Squiggle, |s| s.foreground(PaletteColor::Destructive))
      .state(InputState::FullWidth, Root, |s| s.width(Length::Fill))
      .state(InputState::Valid, Icon, |s| s.foreground(Success));
    let recipe = text_box::box_sizes(recipe, Control, true);
    let recipe = text_box::box_rules(recipe, Root, Control, Placeholder);
    text_box::fluid_rules(recipe, Root, Control)
  }
}

/// Whether a key event is the Enter that submits a box: in it, outside a composition, with no modifier, and taken by
/// nothing else yet.
pub(crate) fn submits(event: &KeyboardEvent) -> bool {
  event.key == "Enter"
    && event.focus_within
    && !event.composing
    && !(event.ctrl || event.alt || event.meta)
    && !event.default_prevented()
}