lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
//! A number input: a number a person types, or steps with the keys and two buttons.

use std::{
  cell::{Cell, RefCell},
  collections::HashMap,
  sync::{Arc, Mutex, Weak},
};

use super::{
  field::{FieldControl, InField},
  icon::Icon,
  icons, names,
  part_style::{FontFamily, Length, PartStyle},
  recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
  shared::fading,
  text_box::{self, BoxStates, Judgment, TextBoxSize},
  theme::{Themed, current_theme},
};
use crate::{
  app::{
    events::{KeyboardEvent, TextInputEvent},
    theme::{ControlSize, OpacityLevel, PaletteColor, RadiusSize, Theme},
  },
  components::{self, Column, Row, Stack},
  core::Signal,
  layout::{
    Alignment, StackAlignment,
    layout_kind::Justify,
    text_style::{FontWeight, TextAlign, TextStyle},
  },
  node::{CursorIcon, Element, HitTestBehavior, dimension::Dimension, node_kind::KeyboardKind},
};

/// The parts of a number input a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NumberInputPart {
  /// The place the input takes: its width.
  Root,
  /// The box that is typed in and focused: its edge, its fill, its height, and the type of the number.
  Control,
  /// What the box says while it is empty.
  Placeholder,
  /// What holds the buttons over the box: how far in from the box's edge they are, and the corners they are cut to.
  Buttons,
  /// The button that takes a step down.
  Decrease,
  /// The button that takes a step up.
  Increase,
  /// The line between a button and the number.
  Separator,
  /// The glyph of a button.
  Icon,
}

names!(NumberInputPart {
  Root => "root",
  Control => "control",
  Placeholder => "placeholder",
  Buttons => "buttons",
  Decrease => "decrease",
  Increase => "increase",
  Separator => "separator",
  Icon => "icon",
});

/// The sizes of a number input: the heights of the theme's controls, and the type of each.
pub type NumberInputSize = TextBoxSize;

/// Where a number input's buttons are: its variants.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum NumberInputLayout {
  /// One at each end, the number between them in the middle: a minus at the start, a plus at the end. The board's.
  #[default]
  Split,
  /// One over the other at the end, a chevron up over a chevron down, the number at the start.
  Stacked,
  /// None: the number is stepped by the keys alone.
  Bare,
}

names!(NumberInputLayout {
  Split => "split",
  Stacked => "stacked",
  Bare => "bare",
});

/// The states of a number input a recipe styles, besides what the pointer and the keyboard do to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NumberInputState {
  /// 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: its buttons do nothing.
  ReadOnly,
  /// It takes no input.
  Disabled,
  /// It is as wide as what holds it.
  FullWidth,
  /// Its value is the least it can be: the button that steps down is disabled.
  AtMin,
  /// Its value is the greatest it can be: the button that steps up is disabled.
  AtMax,
  /// It is in a fluid field ([`Field::fluid`](super::Field::fluid)): the field's label is inside its box, over the
  /// number, and its buttons are on the line of the number.
  Fluid,
}

names!(NumberInputState {
  Invalid => "invalid",
  Warning => "warning",
  Valid => "valid",
  ReadOnly => "read_only",
  Disabled => "disabled",
  FullWidth => "full_width",
  AtMin => "at_min",
  AtMax => "at_max",
  Fluid => "fluid",
});

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

type Formatter = Arc<dyn Fn(f64) -> String + Send + Sync>;
type Parser = Arc<dyn Fn(&str) -> Option<f64> + Send + Sync>;
type ChangeHandler = Arc<dyn Fn(Option<f64>) + Send + Sync>;

/// How a number input writes its number, and reads what is pasted into it: a prefix, a suffix, the separators of
/// decimals and of thousands, or the app's own formatter and parser.
///
/// ```
/// use lurq::ui::NumberFormat;
///
/// let price = NumberFormat::new().prefix("$").grouping(true);
/// let weight = NumberFormat::new().suffix(" kg");
/// // A locale that writes a comma for decimals and a dot between thousands.
/// let german = NumberFormat::new().separators(',', '.').grouping(true).suffix(" €");
/// // The app's own: a percentage of a fraction.
/// let percent = NumberFormat::custom(
///   |value| format!("{:.0}%", value * 100.0),
///   |text| text.trim().trim_end_matches('%').trim().parse::<f64>().ok().map(|n| n / 100.0),
/// );
/// ```
///
/// What it writes is shown while the input is not focused. While it is typed in, the input shows the number alone,
/// with the decimal separator and no prefix, suffix or grouping, and takes digits, a minus and that separator.
#[derive(Clone)]
pub struct NumberFormat {
  prefix: Arc<str>,
  suffix: Arc<str>,
  decimal: char,
  group: char,
  grouping: bool,
  format: Option<Formatter>,
  parse: Option<Parser>,
}

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

impl NumberFormat {
  /// The number alone, with a dot for decimals and no grouping: `1234.5`.
  pub fn new() -> Self {
    Self {
      prefix: Arc::from(""),
      suffix: Arc::from(""),
      decimal: '.',
      group: ',',
      grouping: false,
      format: None,
      parse: None,
    }
  }

  /// The app's own formatter and parser: `format` writes what is shown out of the focus, a value already rounded
  /// to the input's precision; `parse` reads what it wrote, or what is pasted in. What is typed in the focus is
  /// read as a number with the decimal separator ([`NumberFormat::separators`]).
  pub fn custom(
    format: impl Fn(f64) -> String + Send + Sync + 'static,
    parse: impl Fn(&str) -> Option<f64> + Send + Sync + 'static,
  ) -> Self {
    Self {
      format: Some(Arc::new(format)),
      parse: Some(Arc::new(parse)),
      ..Self::new()
    }
  }

  /// What is written before the number: a currency's sign.
  pub fn prefix(mut self, prefix: &str) -> Self {
    self.prefix = Arc::from(prefix);
    self
  }

  /// What is written after the number: a unit.
  pub fn suffix(mut self, suffix: &str) -> Self {
    self.suffix = Arc::from(suffix);
    self
  }

  /// Whether the thousands are set apart: `1,234,567`.
  pub fn grouping(mut self, grouping: bool) -> Self {
    self.grouping = grouping;
    self
  }

  /// The separator of decimals, the one that is typed, and the one between thousands: a locale's.
  pub fn separators(mut self, decimal: char, group: char) -> Self {
    self.decimal = decimal;
    self.group = group;
    self
  }

  /// The number as it is typed: `precision` decimals with the decimal separator, no prefix, suffix or grouping.
  fn plain(&self, value: f64, precision: usize) -> String {
    let text = format!("{value:.precision$}");
    // A value that rounds to nothing is written without a sign.
    let text = match text.strip_prefix('-') {
      Some(rest) if rest.chars().all(|c| c == '0' || c == '.') => rest.to_owned(),
      _ => text,
    };
    if self.decimal == '.' {
      text
    } else {
      text.replace('.', &self.decimal.to_string())
    }
  }

  /// The number as it is shown out of the focus.
  fn display(&self, value: f64, precision: usize) -> String {
    if let Some(format) = &self.format {
      return format(value);
    }
    let plain = self.plain(value, precision);
    let plain = if self.grouping {
      let (sign, rest) = match plain.strip_prefix('-') {
        Some(rest) => ("-", rest),
        None => ("", plain.as_str()),
      };
      let (whole, fraction) = match rest.find(self.decimal) {
        Some(at) => rest.split_at(at),
        None => (rest, ""),
      };
      let mut grouped = String::new();
      for (index, digit) in whole.chars().enumerate() {
        if index > 0 && (whole.len() - index) % 3 == 0 {
          grouped.push(self.group);
        }
        grouped.push(digit);
      }
      format!("{sign}{grouped}{fraction}")
    } else {
      plain
    };
    format!("{}{plain}{}", self.prefix, self.suffix)
  }

  /// The number in `text`, as typed or as shown: the app's parser first, then the number with the prefix, the
  /// suffix and the grouping taken off.
  fn parse(&self, text: &str) -> Option<f64> {
    if let Some(parse) = &self.parse
      && let Some(value) = parse(text)
    {
      return value.is_finite().then_some(value);
    }
    let text = text.trim();
    let text = text.strip_prefix(self.prefix.trim()).unwrap_or(text).trim();
    let text = text.strip_suffix(self.suffix.trim()).unwrap_or(text).trim();
    let number: String = text
      .chars()
      .filter(|c| *c != self.group || self.group == self.decimal)
      .map(|c| if c == self.decimal { '.' } else { c })
      .collect();
    let value = number.parse::<f64>().ok()?;
    value.is_finite().then_some(value)
  }
}

/// What a number input is bound to.
#[derive(Clone)]
enum Bound {
  /// A number there always is: an emptied field takes back the number it had.
  Value(Signal<f64>),
  /// A number that may be none: an emptied field is none.
  Optional(Signal<Option<f64>>),
  /// The app's, told back by `on_change`.
  Controlled(Option<f64>),
}

/// What the input's handlers know of it: its value, its range, its step and how it writes it.
#[derive(Clone)]
struct Model {
  bound: Bound,
  on_change: Vec<ChangeHandler>,
  on_change_end: Vec<ChangeHandler>,
  min: Option<f64>,
  max: Option<f64>,
  step: f64,
  precision: usize,
  format: NumberFormat,
  /// The range of the last build, held by the input's handlers: see [`range_held`].
  range: Option<Arc<Mutex<Range>>>,
  /// Of a controlled input whose value is out of its range, what keeps the app from being told of the clamped value
  /// again while it is: see [`told_once`].
  told: Option<Arc<()>>,
}

/// The least and the greatest value of a number input.
type Range = (Option<f64>, Option<f64>);

/// A controlled input's value out of its range, by the input's id or key, the value and the range.
type Told = (Option<Arc<str>>, u64, Option<u64>, Option<u64>);

thread_local! {
  /// The controlled inputs whose app was told the value clamped into the range, while their inputs are in the tree.
  static TOLD: RefCell<HashMap<Told, Weak<()>>> = RefCell::new(HashMap::new());
}

/// What keeps a controlled input from telling its app of the value clamped again, and whether it is to tell now: the
/// app holds the value, and is told once of each value out of each range, as a press of a stepper would tell it.
fn told_once(told: Told) -> (Arc<()>, bool) {
  TOLD.with(|all| {
    let mut all = all.borrow_mut();
    if let Some(alive) = all.get(&told).and_then(Weak::upgrade) {
      return (alive, false);
    }
    all.retain(|_, alive| alive.strong_count() > 0);
    let alive = Arc::new(());
    all.insert(told, Arc::downgrade(&alive));
    (alive, true)
  })
}

thread_local! {
  /// The value the focused number input had when it took the focus, or when an edit of it was last over: what
  /// tells whether Enter or the focus leaving ends a change. One input has the focus at a time.
  static EDIT_START: Cell<Option<Option<f64>>> = const { Cell::new(None) };
  /// The value as a button of a number input was pressed, while it is held: what its release compares with. A
  /// window has one pointer that holds a button.
  static HELD_FROM: Cell<Option<Option<f64>>> = const { Cell::new(None) };
}

thread_local! {
  /// The range each number input bound to a signal was last built with, by the id of its signal, while its input
  /// is in the tree. A window's inputs are all on its thread.
  static RANGES: RefCell<HashMap<usize, Weak<Mutex<Range>>>> = RefCell::new(HashMap::new());
}

/// What the input bound to the signal `binding` keeps of its range, and the range it had at its last build, `None`
/// at its first.
fn range_held(binding: usize, now: Range) -> (Arc<Mutex<Range>>, Option<Range>) {
  RANGES.with(|ranges| {
    let mut ranges = ranges.borrow_mut();
    if let Some(held) = ranges.get(&binding).and_then(Weak::upgrade) {
      let before = std::mem::replace(&mut *held.lock().unwrap(), now);
      return (held, Some(before));
    }
    ranges.retain(|_, held| held.strong_count() > 0);
    let held = Arc::new(Mutex::new(now));
    ranges.insert(binding, Arc::downgrade(&held));
    (held, None)
  })
}

impl Model {
  fn value(&self) -> Option<f64> {
    match &self.bound {
      Bound::Value(value) => Some(value.get_untracked()),
      Bound::Optional(value) => value.get_untracked(),
      Bound::Controlled(value) => *value,
    }
  }

  /// The value, read so that the render reading it is run again when it changes.
  fn tracked_value(&self) -> Option<f64> {
    match &self.bound {
      Bound::Value(value) => Some(value.get()),
      Bound::Optional(value) => value.get(),
      Bound::Controlled(value) => *value,
    }
  }

  /// Whether an emptied field is no value.
  fn optional(&self) -> bool {
    !matches!(self.bound, Bound::Value(_))
  }

  /// Sets the value, where it changed, and tells the handlers. A number there always is takes no `None`.
  fn write(&self, value: Option<f64>) {
    match &self.bound {
      Bound::Value(signal) => {
        let Some(value) = value else {
          return;
        };
        if signal.get_untracked() == value {
          return;
        }
        signal.set(value);
      }
      Bound::Optional(signal) => {
        if signal.get_untracked() == value {
          return;
        }
        signal.set(value);
      }
      Bound::Controlled(held) => {
        if *held == value {
          return;
        }
      }
    }
    for handler in &self.on_change {
      handler(value);
    }
  }

  fn round(&self, value: f64) -> f64 {
    let scale = 10f64.powi(self.precision as i32);
    (value * scale).round() / scale
  }

  fn clamp(&self, value: f64) -> f64 {
    let value = self.min.map_or(value, |min| value.max(min));
    self.max.map_or(value, |max| value.min(max))
  }

  /// `value` as the input keeps it: rounded to its precision and in its range.
  fn settle(&self, value: f64) -> f64 {
    self.clamp(self.round(self.clamp(value)))
  }

  fn display(&self, value: Option<f64>) -> String {
    value.map_or_else(String::new, |value| self.format.display(value, self.precision))
  }

  fn edit(&self, value: Option<f64>) -> String {
    value.map_or_else(String::new, |value| self.format.plain(value, self.precision))
  }

  /// Whether `text` is a number being typed: a minus first where the range has room below zero, digits, and one
  /// decimal separator where the precision keeps decimals. An empty field is one too.
  fn accepts(&self, text: &str) -> bool {
    let negative = self.min.is_none_or(|min| min < 0.0);
    let decimals = self.precision > 0;
    let mut separators = 0;
    text.chars().enumerate().all(|(index, c)| match c {
      '0'..='9' => true,
      '-' => index == 0 && negative,
      c if c == self.format.decimal => {
        separators += 1;
        decimals && separators == 1
      }
      _ => false,
    })
  }

  /// The value `steps` steps from `from` (none: nought, or the end of the range nearer to it), on the grid of the step
  /// from the least value: a value between two steps goes to the next one in the direction of the step.
  fn stepped(&self, from: Option<f64>, steps: i32) -> f64 {
    let base = self.min.unwrap_or(0.0);
    let Some(from) = from else {
      return self.settle(0.0);
    };
    let at = (from - base) / self.step;
    // A value a hair off the grid, by the error of a fraction, is on it.
    let on = if steps > 0 {
      (at + 1e-9).floor()
    } else {
      (at - 1e-9).ceil()
    };
    self.settle(base + (on + steps as f64) * self.step)
  }

  /// Whether `value` is the least the range allows.
  fn at_min(&self, value: Option<f64>) -> bool {
    matches!((value, self.min), (Some(value), Some(min)) if value <= min)
  }

  /// Whether `value` is the greatest the range allows.
  fn at_max(&self, value: Option<f64>) -> bool {
    matches!((value, self.max), (Some(value), Some(max)) if value >= max)
  }

  /// Tells the handlers of the end of a change of `before` into `after`, where it is one.
  fn ended(&self, before: Option<f64>, after: Option<f64>) {
    if before == after {
      return;
    }
    for handler in &self.on_change_end {
      handler(after);
    }
  }

  /// A change that is over at once (a step, Home or End): told as it ends, from what the value was before it. Where
  /// the input has the focus, what Enter or the focus leaving compares with is the value now.
  fn step_over(&self, before: Option<f64>, after: Option<f64>) {
    self.ended(before, after);
    EDIT_START.with(|start| {
      if start.get().is_some() {
        start.set(Some(after));
      }
    });
  }

  /// Takes the step of `steps` from what `text` holds, or from the value, writes it and shows it: as it is typed
  /// where the text was being typed (`editing`), else as it is shown. Gives the value it took.
  fn step(&self, text: &Signal<String>, steps: i32, editing: bool) -> f64 {
    let held = text.get_untracked();
    let from = self.format.parse(&held).or_else(|| self.value());
    let value = self.stepped(from, steps);
    self.write(Some(value));
    let shown = if editing {
      self.edit(Some(value))
    } else {
      self.display(Some(value))
    };
    if held != shown {
      text.set(shown);
    }
    value
  }

  /// Takes the value to the end of the range `value` is, where the range has that end. Gives the value it took.
  fn jump(&self, text: &Signal<String>, value: f64) -> f64 {
    let value = self.settle(value);
    self.write(Some(value));
    text.set(self.edit(Some(value)));
    value
  }

  /// Puts what `text` holds right: the number in it rounded, kept in the range and written again, an empty field no
  /// value (or the value it had, where there is always one), and anything else the value it had. Gives the value
  /// it is then.
  fn commit(&self, text: &Signal<String>, editing: bool) -> Option<f64> {
    let held = text.get_untracked();
    let shown = |value: Option<f64>| if editing { self.edit(value) } else { self.display(value) };
    let (value, next) = if held.trim().is_empty() {
      if self.optional() {
        self.write(None);
        (None, String::new())
      } else {
        (self.value(), shown(self.value()))
      }
    } else {
      match self.format.parse(&held) {
        Some(value) => {
          let value = self.settle(value);
          self.write(Some(value));
          (Some(value), shown(Some(value)))
        }
        None => (self.value(), shown(self.value())),
      }
    };
    if held != next {
      text.set(next);
    }
    value
  }
}

/// A number input: a number a person types, or steps with the arrow keys and two buttons. A quantity, a price, a
/// size in pixels.
///
/// ```
/// use lurq::{core::Signal, ui::{NumberFormat, NumberInput, NumberInputLayout}};
///
/// let quantity = Signal::new(1.0);
/// let input = NumberInput::new(quantity.clone()).min(1.0).max(99.0);
/// // A price in cents, its thousands set apart, the buttons stacked at the end.
/// let price = NumberInput::new(Signal::new(1250.0))
///   .min(0.0)
///   .step(0.5)
///   .precision(2)
///   .format(NumberFormat::new().prefix("$").grouping(true))
///   .layout(NumberInputLayout::Stacked);
/// // A number that may be left out: an emptied field is none.
/// let limit = NumberInput::optional(Signal::new(None)).placeholder("No limit");
/// ```
///
/// What is typed is kept as text while it is typed, and is the value whenever it is a number: a minus, digits and
/// one decimal separator are taken as they are typed, and nothing else. On Enter and when the focus leaves, the text
/// is put right: the number rounded to the precision, kept in the range and written in the format. Up and Down take
/// a step, Page Up and Page Down ten, Home and End go to the least and the greatest value where the range has them.
/// A wheel turned over it scrolls what it is in and does not change it. Its buttons take a step when pressed, and
/// another every twentieth of a second while held; they are not stops of Tab, and the one toward an end of the range
/// the value is at is disabled. To what reads the tree it is a `spinbutton` with its value, its least and its
/// greatest, and its buttons are "Increase" and "Decrease" ([`NumberInput::increase_label`],
/// [`NumberInput::decrease_label`]). [`NumberInput::on_change`] hears each change as it is made,
/// [`NumberInput::on_change_end`] the value when Enter, the focus leaving or a step is over.
pub struct NumberInput {
  model: Model,
  layout: NumberInputLayout,
  placeholder: Option<Arc<str>>,
  boxed: BoxStates,
  full_width: bool,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  precision: Option<usize>,
  increase_label: Arc<str>,
  decrease_label: Arc<str>,
  name: Option<Arc<str>>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl NumberInput {
  /// A number input bound to `value`: it shows what the signal holds, and what is typed or stepped is set on it.
  /// There is always a number: an emptied field takes back the one it had when it is left.
  pub fn new(value: Signal<f64>) -> Self {
    Self::bound(Bound::Value(value))
  }

  /// A number input bound to a number that may be none: an emptied field sets `None`, not nought.
  pub fn optional(value: Signal<Option<f64>>) -> Self {
    Self::bound(Bound::Optional(value))
  }

  /// A number input that shows `value`, held by the app, and tells `on_change` each change a person makes: the app
  /// sets what it shows. `None` is an empty field.
  /// Two built at the one place in the app's code, in a loop, are told apart by their `id` or `key`.
  pub fn controlled(value: impl Into<Option<f64>>, on_change: impl Fn(Option<f64>) + Send + Sync + 'static) -> Self {
    Self::bound(Bound::Controlled(value.into())).on_change(on_change)
  }

  fn bound(bound: Bound) -> Self {
    Self {
      model: Model {
        bound,
        on_change: Vec::new(),
        on_change_end: Vec::new(),
        min: None,
        max: None,
        step: 1.0,
        precision: 0,
        format: NumberFormat::new(),
        range: None,
        told: None,
      },
      layout: NumberInputLayout::default(),
      placeholder: None,
      boxed: BoxStates::default(),
      full_width: false,
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      precision: None,
      increase_label: super::current_locale().fields.increase.clone(),
      decrease_label: super::current_locale().fields.decrease.clone(),
      name: None,
      id: None,
      key: None,
    }
  }

  /// The least value. None where it is not given: Home then moves the caret, and a minus can be typed.
  pub fn min(mut self, min: impl Into<f64>) -> Self {
    self.model.min = Some(min.into());
    self
  }

  /// The greatest value. None where it is not given: End then moves the caret.
  pub fn max(mut self, max: impl Into<f64>) -> Self {
    self.model.max = Some(max.into());
    self
  }

  /// How far apart the values a step takes it to are, from the least: 1 where it is not given. Page Up and Page
  /// Down take ten.
  pub fn step(mut self, step: impl Into<f64>) -> Self {
    let step = step.into();
    if step.is_finite() && step > 0.0 {
      self.model.step = step;
    }
    self
  }

  /// How many decimals the value keeps and shows. Where it is not given, as many as the step has: none for whole
  /// steps, which then take no decimal separator.
  pub fn precision(mut self, precision: usize) -> Self {
    self.precision = Some(precision.min(12));
    self
  }

  /// How the number is written: see [`NumberFormat`].
  pub fn format(mut self, format: NumberFormat) -> Self {
    self.model.format = format;
    self
  }

  /// Where the buttons are, or that there are none.
  pub fn layout(mut self, layout: NumberInputLayout) -> Self {
    self.layout = layout;
    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 [`NumberInputSize`], 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: typing, the keys and the buttons do
  /// nothing. 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. A field gives it its label.
  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 132.
  pub fn full_width(mut self, full_width: bool) -> Self {
    self.full_width = full_width;
    self
  }

  /// Called with the value each time a person changes it: as a number is typed, stepped, put right or emptied. Not
  /// called for what is already so. Each call adds a handler.
  pub fn on_change(mut self, handler: impl Fn(Option<f64>) + Send + Sync + 'static) -> Self {
    self.model.on_change.push(Arc::new(handler));
    self
  }

  /// Called with the value when a change is over, where the value is another than it was as it began: Enter or the
  /// focus leaving after typing, each step of a key, Home and End, and the release of a button held down, however many
  /// steps it took. Each call adds a handler.
  pub fn on_change_end(mut self, handler: impl Fn(Option<f64>) + Send + Sync + 'static) -> Self {
    self.model.on_change_end.push(Arc::new(handler));
    self
  }

  /// What the button that steps up is called, to what reads the tree: "Increase" where it is not given.
  pub fn increase_label(mut self, label: &str) -> Self {
    self.increase_label = Arc::from(label);
    self
  }

  /// What the button that steps down is called, to what reads the tree: "Decrease" where it is not given.
  pub fn decrease_label(mut self, label: &str) -> Self {
    self.decrease_label = Arc::from(label);
    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
  }

  /// The name the input's text has in the form it is in. A form's number (`FormHandle::number`) bound with
  /// [`NumberInput::new`] holds its value.
  #[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.
  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
  }

  /// The key of the control. Each build makes the control's text anew, so the control is found again by its key:
  /// one is given where the app gives none.
  pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
    self.key = Some(key.into());
    self
  }

  /// Builds the input in `theme`. Converting a number input into an element does this in the theme of what is
  /// being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    let mut model = self.model;
    model.precision = self.precision.unwrap_or_else(|| decimals_of(model.step));
    if let (Some(min), Some(max)) = (model.min, model.max)
      && max < min
    {
      model.max = Some(min);
    }
    // Read so that what renders the input renders it again when the app's value changes: the text is made from it.
    let mut value = model.tracked_value();
    // A range that changed under the value takes it in at once, as a slider's does: shown so, written, and told. A
    // number being typed past an end is kept until Enter or the focus leaving puts it right.
    let binding = match &model.bound {
      Bound::Value(signal) => Some(signal.id()),
      Bound::Optional(signal) => Some(signal.id()),
      Bound::Controlled(_) => None,
    };
    let changed = binding.is_some_and(|binding| {
      let (held, before) = range_held(binding, (model.min, model.max));
      model.range = Some(held);
      before.is_some_and(|before| before != (model.min, model.max))
    });
    if changed
      && let Some(held) = value
      && model.clamp(held) != held
    {
      let clamped = model.clamp(held);
      model.write(Some(clamped));
      value = Some(clamped);
    }
    // The app holds a controlled value, and the input cannot set it: it shows the value in the range, tells the app
    // once, and shows what the app answers with.
    if let Bound::Controlled(Some(held)) = model.bound
      && model.clamp(held) != held
    {
      let clamped = model.clamp(held);
      let name = self.id.clone().or_else(|| self.key.clone());
      let (alive, tell) = told_once((
        name,
        held.to_bits(),
        model.min.map(f64::to_bits),
        model.max.map(f64::to_bits),
      ));
      model.told = Some(alive);
      value = Some(clamped);
      if tell {
        for handler in &model.on_change {
          handler(Some(clamped));
        }
      }
    }
    let (at_min, at_max) = (model.at_min(value), model.at_max(value));
    let case = self
      .boxed
      .case(self.states.clone())
      .state(NumberInputState::FullWidth, self.full_width)
      .state(NumberInputState::AtMin, at_min)
      .state(NumberInputState::AtMax, at_max);
    let case = Case {
      variant: Some(self.layout.into()),
      ..case
    };
    let view = NumberInputView {
      text: Signal::new(model.display(value)),
      value,
      min: model.min,
      max: model.max,
      step: model.step,
      precision: model.precision,
      layout: self.layout,
      placeholder: self.placeholder,
      label: self.boxed.label.clone(),
      invalid: self.boxed.judgment() == Some(Judgment::Invalid),
      read_only: self.boxed.read_only,
      disabled: self.boxed.disabled,
      at_min,
      at_max,
      recipe: theme
        .resolve::<NumberInput>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      forced: self.forced,
      model,
      increase_label: self.increase_label,
      decrease_label: self.decrease_label,
      boxed: self.boxed,
      name: self.name,
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<NumberInput>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

/// How many decimals `step` has, as it would be written: 0.25 has two.
fn decimals_of(step: f64) -> usize {
  (0..=12)
    .find(|places| {
      let scale = 10f64.powi(*places);
      ((step * scale).round() - step * scale).abs() < 1e-9 * scale.max(1.0)
    })
    .unwrap_or(12) as usize
}

impl FieldControl for NumberInput {
  /// 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<NumberInput> for Element {
  fn from(input: NumberInput) -> Self {
    input.build(&current_theme())
  }
}

/// A number input as a renderer sees it: what it was given, the style of its parts, and its behavior ready to be
/// dressed.
pub struct NumberInputView {
  /// What the control shows, made anew in each build from the value: the control keeps what is typed in it while
  /// it has the focus.
  pub text: Signal<String>,
  /// The value as the input was built with it.
  pub value: Option<f64>,
  pub min: Option<f64>,
  pub max: Option<f64>,
  pub step: f64,
  /// How many decimals the value keeps and shows: the one given, or the step's.
  pub precision: usize,
  pub layout: NumberInputLayout,
  pub placeholder: Option<Arc<str>>,
  /// 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,
  /// Whether the value is the least the range allows: the button that steps down is disabled.
  pub at_min: bool,
  /// Whether the value is the greatest the range allows: the button that steps up is disabled.
  pub at_max: bool,
  /// The style of each part of this input.
  pub recipe: ResolvedRecipe,
  forced: Option<Interaction>,
  model: Model,
  increase_label: Arc<str>,
  decrease_label: Arc<str>,
  boxed: BoxStates,
  // 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 NumberInputView {
  /// 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 number: the control's.
  pub fn value_style(&self) -> TextStyle {
    text_box::ink(self.theme(), &self.part(NumberInputPart::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(NumberInputPart::Control).rest();
    text_box::ink(
      self.theme(),
      &control.merged(&self.part(NumberInputPart::Placeholder).rest()),
    )
  }

  /// A length of a part's style in pixels: 0 where it has none, or none in pixels.
  fn px(&self, length: Option<Length>) -> f32 {
    match length.and_then(|length| length.resolve(self.theme())) {
      Some(Dimension::Px(px)) => px,
      _ => 0.0,
    }
  }

  /// A part's padding along the row, at its start and its end.
  fn padding_x(&self, part: NumberInputPart) -> (f32, f32) {
    let spacing = self.theme().spacing();
    let style = self.part(part).rest();
    let [_, end, _, start] = style.paddings();
    (
      start.map_or(0.0, |padding| padding.resolve(&spacing, 0.0)),
      end.map_or(0.0, |padding| padding.resolve(&spacing, 0.0)),
    )
  }

  /// How far the buttons reach into the box from its start and from its end: the room the number leaves them.
  pub fn buttons_reach(&self) -> (f32, f32) {
    let (inset_start, inset_end) = self.padding_x(NumberInputPart::Buttons);
    let separator = self.px(self.part(NumberInputPart::Separator).rest().width);
    let decrease = self.px(self.part(NumberInputPart::Decrease).rest().width);
    let increase = self.px(self.part(NumberInputPart::Increase).rest().width);
    match self.layout {
      NumberInputLayout::Split => (inset_start + decrease + separator, increase + separator + inset_end),
      NumberInputLayout::Stacked => (0.0, increase.max(decrease) + separator + inset_end),
      NumberInputLayout::Bare => (0.0, 0.0),
    }
  }

  /// The input's behavior with the style of its control: the engine's text input, which is typed in, focused and
  /// disabled, and which takes what a number is typed with, steps with the keys and is put right on Enter and when
  /// the focus leaves it.
  pub fn control(&self) -> components::TextInput {
    let model = self.model.clone();
    let read_only = self.boxed.read_only;
    // What is typed: taken where it is a number being typed and then the value where it is a number; else refused,
    // unless it is a whole number as it is written, pasted in, which is then typed in its place.
    let typed = {
      let model = model.clone();
      Arc::new(move |event: &TextInputEvent| {
        let text = event.new_value();
        if model.accepts(text) {
          if text.is_empty() {
            if model.optional() {
              model.write(None);
            }
          } else if let Some(value) = model.format.parse(text) {
            model.write(Some(value));
          }
          return;
        }
        event.prevent_default();
        // A number written with what is around it, pasted: typed as it is, where it is one that could be typed.
        if let Some(value) = model.format.parse(text).map(|value| model.round(value))
          && model.accepts(&model.edit(Some(value)))
        {
          model.write(Some(value));
          event.value.set(model.edit(Some(value)));
        }
      }) as text_box::EditHandler
    };
    let control_part = self.part(NumberInputPart::Control);
    let (gap_start, gap_end) = self.padding_x(NumberInputPart::Control);
    let (reach_start, reach_end) = self.buttons_reach();
    let align = match self.layout {
      NumberInputLayout::Split => TextAlign::Center,
      NumberInputLayout::Stacked | NumberInputLayout::Bare => TextAlign::Left,
    };
    let keyboard = if model.precision > 0 || model.min.is_none_or(|min| min < 0.0) {
      KeyboardKind::Decimal
    } else {
      KeyboardKind::Number
    };
    let control = components::TextInput::new(self.text.clone())
      .single_line()
      .text_style(self.value_style())
      .placeholder_style(self.placeholder_style())
      .text_align(align)
      .part(&control_part)
      .padding_left(reach_start + gap_start)
      .padding_right(reach_end + gap_end)
      .keyboard(keyboard)
      // Each build makes the text anew: the control keeps what is half typed while it has the focus.
      .keep_text_while_focused(true);
    let mut control = text_box::text_box_as(control, &self.boxed, vec![typed], "spinbutton");
    if let Some(value) = self.value {
      control = control
        .describe("a11y_valuenow", value.to_string())
        .describe("a11y_valuetext", self.model.display(Some(value)));
    }
    if let Some(min) = self.min {
      control = control.describe("a11y_valuemin", min.to_string());
    }
    if let Some(max) = self.max {
      control = control.describe("a11y_valuemax", max.to_string());
    }
    if let Some(placeholder) = &self.placeholder {
      control = control.placeholder(placeholder);
    }
    if !read_only {
      let text = self.text.clone();
      let keys = model.clone();
      control = control.on_key_down(move |event: KeyboardEvent| {
        if !event.focus_within || event.ctrl || event.alt || event.meta || event.composing {
          return;
        }
        let steps = match event.key.as_str() {
          "ArrowUp" => Some(1),
          "ArrowDown" => Some(-1),
          "PageUp" => Some(10),
          "PageDown" => Some(-10),
          _ => None,
        };
        // A step of a key is a change that is over as it is made.
        let before = keys.value();
        if let Some(steps) = steps {
          event.prevent_default();
          let after = keys.step(&text, steps, true);
          keys.step_over(before, Some(after));
          return;
        }
        match (event.key.as_str(), keys.min, keys.max) {
          ("Home", Some(min), _) => {
            event.prevent_default();
            let after = keys.jump(&text, min);
            keys.step_over(before, Some(after));
          }
          ("End", _, Some(max)) => {
            event.prevent_default();
            let after = keys.jump(&text, max);
            keys.step_over(before, Some(after));
          }
          // The text is put right and Enter goes on to what it does besides: it sends the form. What was typed
          // since the focus came, or since the last change was over, is over.
          ("Enter", ..) => {
            let before = EDIT_START.with(Cell::get).unwrap_or(before);
            let after = keys.commit(&text, true);
            keys.ended(before, after);
            EDIT_START.with(|start| start.set(Some(after)));
          }
          _ => {}
        }
      });
    }
    // In the focus the number is typed as it is, without what is written around it; out of it, it is written.
    let (focus_text, focus_model) = (self.text.clone(), model.clone());
    let (blur_text, blur_model) = (self.text.clone(), model);
    control = control
      .on_focus(move || {
        EDIT_START.with(|start| start.set(Some(focus_model.value())));
        let held = focus_text.get_untracked();
        if let Some(value) = focus_model.format.parse(&held) {
          let typed = focus_model.edit(Some(value));
          if held != typed {
            focus_text.set(typed);
          }
        }
      })
      .on_blur(move || {
        let start = EDIT_START.with(Cell::take);
        if !read_only {
          let before = start.unwrap_or_else(|| blur_model.value());
          let after = blur_model.commit(&blur_text, false);
          blur_model.ended(before, after);
        }
      });
    #[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());
    }
    control.key(self.key.clone().unwrap_or_else(|| Arc::from("number-input")))
  }

  /// A button that takes `steps` steps, in the style of `part`, with `icon`: pressed and held by the pointer, not a
  /// stop of Tab and not taking the focus, disabled where the input is, where it is read only, and at the end of the
  /// range it steps toward. Its id is the input's with `-increase` or `-decrease` after it.
  pub fn button(&self, part: NumberInputPart, icon: &'static str, steps: i32) -> Row {
    let style = self.part(part);
    let icon_part = self.part(NumberInputPart::Icon);
    let side = icon_part.rest().width.unwrap_or(Length::Px(16.0));
    let at_end = if steps > 0 { self.at_max } else { self.at_min };
    let disabled = self.disabled || self.read_only || at_end;
    let (text, model) = (self.text.clone(), self.model.clone());
    let name = if steps > 0 {
      self.increase_label.clone()
    } else {
      self.decrease_label.clone()
    };
    let button = Row::new()
      .part(&style)
      .align_items(Alignment::Center)
      .justify(Justify::Center)
      // A press of it leaves the focus where it is: on the number being typed, or nowhere.
      .focusable(false)
      .disabled(disabled)
      .repeat_press(true)
      .on_click(move |event: crate::app::events::MouseEvent| {
        let editing = model.accepts(&text.get_untracked());
        let before = model.value();
        let after = model.step(&text, steps, editing);
        if event.from_keyboard {
          model.step_over(before, Some(after));
          return;
        }
        // A press held down steps again and again: the change is over as it is let go.
        HELD_FROM.with(|from| {
          if from.get().is_none() {
            from.set(Some(before));
          }
        });
        model.step_over(Some(after), Some(after));
      })
      .on_press_end({
        let model = self.model.clone();
        move || {
          if let Some(before) = HELD_FROM.with(Cell::take) {
            model.step_over(before, model.value());
          }
        }
      })
      .describe("a11y_role", "button")
      .describe("a11y_name", name)
      .describe("a11y_disabled", if disabled { "true" } else { "false" })
      .child(
        Row::new()
          .part(&icon_part)
          .pointer_events_none()
          .child(Icon::new(icon).size(side).build(self.theme())),
      );
    // Its id is the input's with `-increase` or `-decrease` after it.
    match &self.id {
      Some(id) => button.id(format!("{id}-{}", if steps > 0 { "increase" } else { "decrease" })),
      None => button,
    }
  }

  /// A line between a button and the number. The pointer passes through it.
  pub fn separator(&self) -> Row {
    Row::new()
      .part(&self.part(NumberInputPart::Separator))
      .pointer_events_none()
  }

  /// The buttons laid over the box, as the layout has them; none for a bare one. Only the buttons take the pointer:
  /// elsewhere it reaches the box under them. They are laid over the whole of the box: as high as it is, or as the
  /// least it is where it is as high as what it holds (in a fluid field, where the part's padding puts them on the
  /// line of the number).
  pub fn buttons(&self) -> Option<Row> {
    let control = self.part(NumberInputPart::Control).rest();
    let height = match self.px(control.height) {
      height if height > 0.0 => height,
      _ => self.px(control.min_height),
    };
    let room = || Row::new().flex(1.0).pointer_events_none();
    let row = Row::new()
      .part(&self.part(NumberInputPart::Buttons))
      .width(Dimension::Pct(100.0))
      .height(height)
      .align_items(Alignment::Stretch)
      .hit_test(HitTestBehavior::ContentOnly);
    match self.layout {
      NumberInputLayout::Split => Some(
        row
          .child(self.button(NumberInputPart::Decrease, icons::MINUS, -1))
          .child(self.separator())
          .child(room())
          .child(self.separator())
          .child(self.button(NumberInputPart::Increase, icons::PLUS, 1)),
      ),
      NumberInputLayout::Stacked => Some(
        row.child(room()).child(self.separator()).child(
          Column::new()
            .align_items(Alignment::Stretch)
            .child(self.button(NumberInputPart::Increase, icons::CHEVRON_UP, 1).flex(1.0))
            .child(
              self
                .button(NumberInputPart::Decrease, icons::CHEVRON_DOWN, -1)
                .flex(1.0),
            ),
        ),
      ),
      NumberInputLayout::Bare => None,
    }
  }

  /// How the default renderer builds a number input: the control, which is the box and holds the ring of the
  /// focus, and its buttons laid over its ends.
  pub fn render(self) -> Element {
    let mut root = Stack::new()
      .stack_align(StackAlignment::CenterStart)
      .part(&self.part(NumberInputPart::Root))
      .child(self.control());
    if let Some(buttons) = self.buttons() {
      root = root.child(buttons);
    }
    root.into()
  }
}

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

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

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

  /// The design's number input (`pencil/lurq-design-system.pen`, Number Input): a box 132 wide and 36 high, an
  /// input's box (the background's fill in an edge of 1 in the color of an input's, 6 round, the ring's color under
  /// the pointer and a line of 2 inside it in the focus), its number in the middle in the code's type at 14 in the
  /// foreground; a minus at its start and a plus at its end, each 36 wide with a line of 1 in the color of an
  /// input's between it and the number, their glyphs 16 in the foreground. A button under the pointer is in the
  /// accent's fill; the one toward the end of the range the value is at is half opaque. Small is 32 with type of 13,
  /// large 40 with type of 15, the buttons as wide as the box is high. Stacked, the buttons are 24 wide at the end, a
  /// chevron of 14 up over one down with a line between them, and the number is at the start, 12 in.
  ///
  /// In a fluid field, which the board does not draw for it, the box is the fluid one, as wide as the field, and the
  /// buttons stand on the line of the number, under the field's label: 25 high with the small radius, from the
  /// label's line to 4 under the number's, the lines beside them as high. Stacked, they are one over the other about
  /// the number's line, down to the line of the box.
  fn recipe() -> Recipe {
    use NumberInputLayout::{Split, Stacked};
    use NumberInputPart::{Buttons, Control, Decrease, Icon, Increase, Placeholder, Root, Separator};
    use PaletteColor::{Foreground, Highlight, HighlightForeground, Input};
    let button = |s: PartStyle| fading(s).width(34.0).foreground(Foreground).cursor(CursorIcon::Pointer);
    let mut recipe = Recipe::new()
      .base(Root, |s| s.width(132.0))
      .base(Control, |s| {
        text_box::box_style(s)
          .height(ControlSize::Md)
          .foreground(Foreground)
          .font_family(FontFamily::Mono)
          .font_size(14.0)
          .weight(FontWeight::Normal)
      })
      // The number in the middle stands clear of the buttons by 4.
      .variant(Split, Control, |s| s.padding_x(4.0))
      .base(Buttons, |s| s.padding_x(1.0).padding_y(1.0).radius(RadiusSize::Md))
      .base(Decrease, button)
      .base(Increase, button)
      .base(Separator, |s| s.width(1.0).background(Input))
      .base(Icon, |s| s.square(16.0))
      .hovered(Decrease, |s| s.background(Highlight).foreground(HighlightForeground))
      .hovered(Increase, |s| s.background(Highlight).foreground(HighlightForeground))
      .variant(Stacked, Decrease, |s| s.width(24.0))
      .variant(Stacked, Increase, |s| s.width(24.0).underline(text_box::edge(Input)))
      .variant(Stacked, Icon, |s| s.square(14.0))
      .state(NumberInputState::FullWidth, Root, |s| s.width(Length::Fill))
      .state(NumberInputState::AtMin, Decrease, |s| {
        s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
      })
      .state(NumberInputState::AtMax, Increase, |s| {
        s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
      })
      .state(NumberInputState::ReadOnly, Decrease, |s| s.cursor(CursorIcon::Default))
      .state(NumberInputState::ReadOnly, Increase, |s| s.cursor(CursorIcon::Default))
      .state(NumberInputState::Disabled, Decrease, |s| s.cursor(CursorIcon::Default))
      .state(NumberInputState::Disabled, Increase, |s| s.cursor(CursorIcon::Default));
    // A button of the board's layout is as wide as the box is high, less the box's edge and the line beside it: 36
    // with its line, at the medium size.
    for (size, width) in [(TextBoxSize::Sm, 30.0), (TextBoxSize::Lg, 38.0)] {
      let side = move |s: PartStyle| s.width(width);
      recipe = recipe
        .when(Selector::new().variant(Split).size(size), Decrease, side)
        .when(Selector::new().variant(Split).size(size), Increase, side);
    }
    let recipe = text_box::box_sizes(recipe, Control, true);
    let recipe = text_box::box_rules(recipe, Root, Control, Placeholder);
    let fluid_button = |s: PartStyle| s.radius(RadiusSize::Sm);
    let stacked = || Selector::new().variant(Stacked).state(NumberInputState::Fluid);
    text_box::fluid_rules(recipe, Root, Control)
      // The buttons from the label's line to as far under the number's line as the label is over it.
      .state(NumberInputState::Fluid, Buttons, |s| {
        s.padding_top(text_box::FLUID_TOP - text_box::FLUID_GAP)
          .padding_bottom(text_box::FLUID_PAD - text_box::FLUID_GAP)
      })
      .state(NumberInputState::Fluid, Decrease, fluid_button)
      .state(NumberInputState::Fluid, Increase, fluid_button)
      // One over the other they need more: down to the line of the box, and as far over the number's line.
      .when(stacked(), Buttons, |s| {
        s.padding_top(text_box::FLUID_TOP - text_box::FLUID_PAD + 1.0)
          .padding_bottom(1.0)
      })
      .when(stacked(), Decrease, |s| s.radius(0.0))
      .when(stacked(), Increase, |s| s.radius(0.0))
  }
}