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
//! A toast: a short message in a corner of the window that leaves by
//! itself, and what shows toasts sent to it from anywhere.

use std::{
  sync::{
    Arc, Mutex, PoisonError,
    atomic::{AtomicU64, Ordering},
  },
  time::Duration,
};

use super::{
  Button, Link,
  icon::Icon,
  icons, names,
  part_style::Length,
  recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
  shared::{IconChoice, fading, glyph, pressable},
  theme::{Themed, current_breakpoint, current_theme},
};
use crate::{
  animation::{AnimatableProperty, Animation, Easing, Keyframes, KeyframesId, Transition},
  app::{
    component::{Component, DevtoolsInspectable},
    ctx::{Ctx, Modal, Root as Window, Timeout},
    events::{SwipeDirection, SwipeEvent},
    theme::{
      BorderSize, IconSize, MotionDuration, MotionEasing, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle,
    },
  },
  components::{self, Column, Row, Stack},
  core::{ElementRef, Signal},
  layout::{Alignment, StackAlignment, layout_kind::Justify, text_style::FontWeight},
  node::{CursorIcon, Element, HitTestBehavior, border::Border, dimension::Dimension, padding::Padding},
  time::Instant,
};

/// How long a toast is shown when it says nothing else.
pub const TOAST_DURATION: Duration = Duration::from_secs(5);

/// How many toasts are shown at once. The others wait, the oldest first, for
/// one of these to leave.
pub const TOASTS_SHOWN: usize = 3;

/// The parts of a toast a recipe styles, and of the corner the toasts are shown in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToastPart {
  /// The panel: its width, fill, edge, corners and shadow.
  Root,
  /// What is in the panel above its timer, side by side.
  Content,
  /// The icon of its kind, at the start.
  Icon,
  /// The title and the description, one over the other.
  Text,
  /// What happened, in a few words.
  Title,
  /// More of it, under the title.
  Description,
  /// What holds the action: the button or the link it is given.
  Action,
  /// What closes it, at the end.
  Close,
  /// The rail along its bottom edge that says how long it has left.
  Timer,
  /// The part of the timer that is left.
  Remaining,
  /// The corner of the window the toasts are shown in: how far from its edges.
  Viewport,
  /// The toasts one over another while the pointer is on them.
  List,
  /// The edge of the toast behind the front one, while they are stacked.
  BehindNear,
  /// The edge of the one behind that.
  BehindFar,
}

names!(ToastPart {
  Root => "root",
  Content => "content",
  Icon => "icon",
  Text => "text",
  Title => "title",
  Description => "description",
  Action => "action",
  Close => "close",
  Timer => "timer",
  Remaining => "remaining",
  Viewport => "viewport",
  List => "list",
  BehindNear => "behind-near",
  BehindFar => "behind-far",
});

/// What a toast says it is: the color of its icon, and which icon it has.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ToastVariant {
  /// A message with no icon of its own: "Link copied".
  #[default]
  Neutral,
  /// Something to know: "A new version is ready".
  Info,
  /// Something was done: "Settings saved".
  Success,
  /// Something was done, with a catch: "Saved, but not synced".
  Warning,
  /// Something could not be done: "Could not connect".
  Destructive,
}

names!(ToastVariant {
  Neutral => "neutral",
  Info => "info",
  Success => "success",
  Warning => "warning",
  Destructive => "destructive",
});

impl ToastVariant {
  /// The variant called `name`, where it is one of these: a variant a theme adds is none of them.
  pub fn named(name: Name) -> Option<Self> {
    Self::all().iter().copied().find(|variant| Name::from(*variant) == name)
  }

  /// The icon of the variant in the theme's set: none for a neutral toast.
  pub fn icon(self) -> Option<&'static str> {
    match self {
      Self::Neutral => None,
      Self::Info => Some(icons::INFO),
      Self::Success => Some(icons::CHECK_CIRCLE),
      Self::Warning => Some(icons::WARNING),
      Self::Destructive => Some(icons::CLOSE_CIRCLE),
    }
  }
}

/// The states of a toast a recipe styles, besides what the pointer and the
/// keyboard do to it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToastState {
  /// It has an action: its content is centered on the button, and lower.
  Action,
}

names!(ToastState {
  Action => "action",
});

/// The corner, or the middle of an edge, of the window toasts are shown in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ToastPosition {
  TopLeft,
  Top,
  TopRight,
  BottomLeft,
  Bottom,
  #[default]
  BottomRight,
}

impl ToastPosition {
  /// Every one of them, in order.
  pub const ALL: [ToastPosition; 6] = [
    Self::TopLeft,
    Self::Top,
    Self::TopRight,
    Self::BottomLeft,
    Self::Bottom,
    Self::BottomRight,
  ];

  fn at_bottom(self) -> bool {
    matches!(self, Self::BottomLeft | Self::Bottom | Self::BottomRight)
  }

  fn across(self) -> Alignment {
    match self {
      Self::TopLeft | Self::BottomLeft => Alignment::Start,
      Self::Top | Self::Bottom => Alignment::Center,
      Self::TopRight | Self::BottomRight => Alignment::End,
    }
  }
}

/// What a toast's action is: a button or a link.
#[derive(Clone)]
pub enum ToastAction {
  Button(Button),
  Link(Link),
}

impl ToastAction {
  /// The action with `press` called on a press of it too.
  fn also(self, press: impl Fn() + Send + Sync + 'static) -> Self {
    match self {
      Self::Button(button) => Self::Button(button.on_click(move |_| press())),
      Self::Link(link) => Self::Link(link.on_click(move |_| press())),
    }
  }
}

impl From<Button> for ToastAction {
  fn from(button: Button) -> Self {
    Self::Button(button)
  }
}

impl From<Link> for ToastAction {
  fn from(link: Link) -> Self {
    Self::Link(link)
  }
}

impl From<ToastAction> for Element {
  fn from(action: ToastAction) -> Self {
    match action {
      ToastAction::Button(button) => button.into(),
      ToastAction::Link(link) => link.into(),
    }
  }
}

/// How much of its time a toast has left, as its timer shows it.
#[derive(Clone, Copy, Debug, PartialEq)]
enum TimeLeft {
  /// All of it: nothing counts it down.
  All,
  /// A part of it, from 0 to 1, standing still.
  Part(f32),
  /// What is left runs out over this.
  RunningOut(Duration),
}

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

/// A toast: a short message that something happened, in a corner of the
/// window over everything, that leaves by itself after a while. Settings
/// saved, a file moved to the trash, a connection that failed.
///
/// ```
/// use lurq::ui::{Button, ButtonSize, ButtonVariant, Toast, ToastVariant};
///
/// let saved = Toast::new("Settings saved")
///   .description("Your theme applies to every open window.")
///   .variant(ToastVariant::Success);
/// // With an action, and a rail that says how long it has left.
/// let trashed = Toast::new("File moved to trash")
///   .description("theme-dark.json")
///   .variant(ToastVariant::Success)
///   .action(Button::new("Undo").variant(ButtonVariant::Outline).size(ButtonSize::Sm))
///   .timer(true);
/// ```
///
/// A toast is a panel like any other component, and can be put anywhere. To
/// show one from anywhere and have it leave by itself, send it to a
/// [`Toasts`]: `toasts.show(saved)`. It has a close control unless it is told
/// [`close_button(false)`](Toast::close_button).
#[derive(Clone)]
pub struct Toast {
  title: Arc<str>,
  description: Option<Arc<str>>,
  variant: Name,
  icon: Option<IconChoice>,
  action: Option<ToastAction>,
  close_button: bool,
  label: Option<Arc<str>>,
  timer: bool,
  duration: Duration,
  persistent: bool,
  states: Vec<Name>,
  rules: Recipe,
  forced: Option<Interaction>,
  on_close: Vec<Arc<dyn Fn() + Send + Sync>>,
  /// How much of its time it has left, as what shows it counts it: what its timer shows.
  left: TimeLeft,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl Toast {
  /// A toast that says `title`.
  pub fn new(title: &str) -> Self {
    Self {
      title: Arc::from(title),
      description: None,
      variant: ToastVariant::Neutral.into(),
      icon: None,
      action: None,
      close_button: true,
      label: None,
      timer: false,
      duration: TOAST_DURATION,
      persistent: false,
      states: Vec::new(),
      rules: Recipe::new(),
      forced: None,
      on_close: Vec::new(),
      left: TimeLeft::All,
      id: None,
      key: None,
    }
  }

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

  /// Its tone: a [`ToastVariant`], or a variant a theme adds, which has no icon of its own.
  pub fn variant(mut self, variant: impl Into<Name>) -> Self {
    self.variant = variant.into();
    self
  }

  /// An icon of the theme's set in place of the variant's, which a neutral toast has none of, or none:
  /// `icon(None)`.
  pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
    self.icon = Some(icon.into());
    self
  }

  /// What can be done about it, before the close control: a [`Button`] or a [`Link`]. A toast shown by a
  /// [`Toasts`] leaves when it is pressed. It is the one action: a second takes its place.
  pub fn action(mut self, action: impl Into<ToastAction>) -> Self {
    self.action = Some(action.into());
    self
  }

  /// Whether the toast has its close control. It has unless told otherwise: what a toast is for is to be
  /// closed or to leave.
  pub fn close_button(mut self, close_button: bool) -> Self {
    self.close_button = close_button;
    self
  }

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

  /// Whether the toast has a rail along its bottom edge that says how long it has left.
  pub fn timer(mut self, timer: bool) -> Self {
    self.timer = timer;
    self
  }

  /// How long a [`Toasts`] shows it: [`TOAST_DURATION`] if it says nothing.
  pub fn duration(mut self, duration: Duration) -> Self {
    self.duration = duration;
    self
  }

  /// Whether it stays until it is closed, or its action is pressed.
  pub fn persistent(mut self, persistent: bool) -> Self {
    self.persistent = persistent;
    self
  }

  /// Puts the toast in a state the theme's recipe names, or takes it out.
  pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
    let state = state.into();
    self.states.retain(|held| *held != state);
    if on {
      self.states.push(state);
    }
    self
  }

  /// Called on a press of its close control. A toast shown by a [`Toasts`] leaves then too. A second handler is
  /// called after the first.
  pub fn on_close(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
    self.on_close.push(Arc::new(handler));
    self
  }

  /// Styles one part of this toast over what the theme gives it.
  pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
    self.rules = self.rules.base(part, style);
    self
  }

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

  /// Draws the close control as it is under the pointer, held down or
  /// focused from the keyboard, with nothing pointing at it: for a gallery
  /// or a test.
  pub fn force(mut self, interaction: Option<Interaction>) -> Self {
    self.forced = interaction;
    self
  }

  /// The id of the panel.
  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
  }

  /// How long a [`Toasts`] shows it: `None` while it stays until it is closed.
  fn lasting(&self) -> Option<Duration> {
    (!self.persistent).then_some(self.duration)
  }

  /// Builds the toast in `theme`. Converting a toast 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: None,
      density: None,
      breakpoint: current_breakpoint(),
      states: self.states.clone(),
    }
    .state(ToastState::Action, self.action.is_some());
    // A variant a theme adds has no icon of its own, as a neutral one has none.
    let icon = match self.icon {
      Some(IconChoice(icon)) => icon,
      None => ToastVariant::named(self.variant)
        .and_then(ToastVariant::icon)
        .map(Name::new),
    };
    let view = ToastView {
      title: self.title,
      description: self.description,
      variant: self.variant,
      icon,
      action: self.action,
      close_button: self.close_button,
      label: self.label,
      timer: self.timer,
      recipe: theme
        .resolve::<Toast>(&case, Some(&self.rules))
        .owned_by(self.id.as_ref()),
      forced: self.forced,
      on_close: self.on_close,
      left: self.left,
      id: self.id,
      key: self.key,
    };
    match theme.renderer::<Toast>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }
}

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

/// A toast as a renderer sees it: what it was given, the style of its parts,
/// and its behavior ready to be dressed.
pub struct ToastView {
  pub title: Arc<str>,
  pub description: Option<Arc<str>>,
  /// Its tone: a [`ToastVariant`]'s name, or a theme's.
  pub variant: Name,
  /// The icon it shows, by its name in the theme's set: the variant's, the one it was given, or none.
  pub icon: Option<Name>,
  pub action: Option<ToastAction>,
  /// Whether it has its close control.
  pub close_button: bool,
  /// What it is called to tooling, where that is not its title.
  pub label: Option<Arc<str>>,
  pub timer: bool,
  /// The style of each part of this toast.
  pub recipe: ResolvedRecipe,
  forced: Option<Interaction>,
  on_close: Vec<Arc<dyn Fn() + Send + Sync>>,
  left: TimeLeft,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl ToastView {
  /// The style of a part, as this toast 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 icon in the style of its part, if the toast has one.
  pub fn icon(&self) -> Option<Element> {
    self.icon.map(|icon| glyph(&self.part(ToastPart::Icon), icon, false))
  }

  /// The title over the description.
  pub fn text(&self) -> Column {
    let title = self.part(ToastPart::Title);
    let mut text = Column::new()
      .flex(1.0)
      .part(&self.part(ToastPart::Text))
      .child(wrapping(&title, &self.title));
    if let Some(description) = &self.description {
      text = text.child(wrapping(&self.part(ToastPart::Description), description));
    }
    text
  }

  /// The action it was given, in the style of its part.
  pub fn action(&self) -> Option<Row> {
    // The button or the link stands for the part, and has its id.
    let lent = self.recipe.lend(ToastPart::Action);
    let action: Element = match self.action.clone()? {
      ToastAction::Button(button) => button.rules(&lent).into(),
      ToastAction::Link(link) => link.rules(&lent).into(),
    };
    Some(Row::new().part(&self.part(ToastPart::Action).unnamed()).child(action))
  }

  /// What closes it: a press of it tells every handler of `on_close`. It is
  /// pressed from the keyboard too, and called "Close" to what reads the tree.
  pub fn close(&self) -> components::Button {
    let part = self.part(ToastPart::Close);
    let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
    let mut close = pressable(&part, false)
      .describe("a11y_role", "button")
      .describe("a11y_name", super::current_locale().common.close.clone())
      .child(Icon::new(icons::CLOSE).size(side).build(self.theme()));
    if !self.on_close.is_empty() {
      let handlers = self.on_close.clone();
      close = close.on_click(move |_| {
        for handler in &handlers {
          handler();
        }
      });
    }
    close
  }

  /// How wide the part of the timer that is left is when all of it is: the
  /// panel's width. `None` where the recipe gives the panel no width in pixels.
  pub fn timer_width(&self) -> Option<f32> {
    match self.part(ToastPart::Root).rest().width?.resolve(self.theme())? {
      Dimension::Px(px) => Some(px),
      _ => None,
    }
  }

  /// The timer: its rail, and on it what is left. While the toast's time is
  /// counted down, what is left runs out; while it stands still, it stays
  /// where it is; a toast nothing counts down has all of it.
  pub fn timer(&self) -> Row {
    let mut remaining = Row::new().part(&self.part(ToastPart::Remaining));
    // A share of the rail, which is as wide as the panel: a toast in a room narrower than its recipe's width
    // runs out from the panel's end, not from past it.
    remaining = match self.left {
      TimeLeft::All => remaining.width(Dimension::Pct(100.0)),
      // Standing still it is where it is at once. It has a transition all the same: one runs from the width
      // the element had with a transition, so what is left can only run out from a width that had one.
      TimeLeft::Part(part) => remaining
        .width(Dimension::Pct(100.0 * part.clamp(0.0, 1.0)))
        .transition(Transition::width().duration(Duration::ZERO).linear()),
      // It runs out from where it is to nothing, a transition from one width to the other.
      TimeLeft::RunningOut(left) => remaining
        .width(Dimension::Pct(0.0))
        .transition(Transition::width().duration(left).linear()),
    };
    // The rail cuts nothing off itself: it and what is left are cut by the panel, to its round corners. A
    // clip of the rail's own inside the panel's would be a plain rectangle at the panel's corners.
    Row::new()
      .overflow_visible()
      .part(&self.part(ToastPart::Timer))
      .child(remaining)
  }

  /// How the default renderer builds a toast: its icon, its text, its action
  /// and its close control side by side, and its timer under them. It is a
  /// status to what reads the tree, called by its title.
  pub fn render(self) -> Element {
    let mut content = Row::new()
      .align_items(if self.action.is_some() {
        Alignment::Center
      } else {
        Alignment::Start
      })
      .part(&self.part(ToastPart::Content));
    if let Some(icon) = self.icon() {
      content = content.child(icon);
    }
    content = content.child(self.text());
    if let Some(action) = self.action() {
      content = content.child(action);
    }
    if self.close_button {
      content = content.child(self.close());
    }
    let mut root = Column::new()
      .part(&self.part(ToastPart::Root))
      .describe("a11y_role", "status")
      .describe("a11y_name", self.label.clone().unwrap_or_else(|| self.title.clone()))
      .child(content);
    if self.timer {
      root = root.child(self.timer());
    }
    if let Some(id) = &self.id {
      root = root.id(id.clone());
    }
    if let Some(key) = &self.key {
      root = root.key(key.clone());
    }
    root.into()
  }
}

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

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

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

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

  /// The design's toast (`pencil/lurq-design-system.pen`, Toast and
  /// Toast/Rich): a panel 360 wide in the popover's colors, with an edge,
  /// large corners and the large shadow; 16 inside it the icon of 16 in the
  /// variant's color, 12 from the title (14, medium) over the description
  /// (13, muted), and the close control of 16 in the muted color. With an
  /// action it is 14 high inside, centered on the action, and its title is 2
  /// over its description. The timer is a rail of 2 in the secondary color,
  /// with what is left in the primary color. Toasts are 16 from the window's
  /// edges and 10 apart; stacked, the two behind show an edge of 8 each,
  /// 24 and 48 narrower, three quarters and half opaque.
  fn recipe() -> Recipe {
    use PaletteColor::{
      Destructive, Info, MutedForeground, Popover, PopoverForeground, Primary, Secondary, Success, Warning,
    };
    use ToastPart as P;
    let edge = || Border::inside(BorderSize::Sm, PaletteColor::Border);
    let behind = |s: super::PartStyle, width: f32, opacity: f32| {
      s.width(width)
        .height(8.0)
        .background(Popover)
        .border(edge())
        .radius(RadiusSize::Lg)
        .opacity(opacity)
    };
    Recipe::new()
      .base(P::Root, |s| {
        s.width(360.0)
          .max_width(Length::Fill)
          .background(Popover)
          .foreground(PopoverForeground)
          .border(edge())
          .radius(RadiusSize::Lg)
          .shadow(ShadowStyle::Lg)
      })
      .base(P::Content, |s| {
        s.width(Length::Fill).padding_x(16.0).padding_y(16.0).gap(12.0)
      })
      .base(P::Icon, |s| {
        s.square(Length::Icon(IconSize::Md)).foreground(PopoverForeground)
      })
      .base(P::Text, |s| s.gap(4.0))
      .base(P::Title, |s| {
        s.typography(TypographyStyle::Body)
          .weight(FontWeight::Medium)
          .foreground(PopoverForeground)
      })
      .base(P::Description, |s| {
        s.typography(TypographyStyle::Body)
          .font_size(13.0)
          .line_height(1.5)
          .foreground(MutedForeground)
      })
      .base(P::Close, |s| {
        fading(
          s.square(Length::Icon(IconSize::Md))
            .radius(RadiusSize::Sm)
            .foreground(MutedForeground)
            .cursor(CursorIcon::Pointer),
        )
      })
      .hovered(P::Close, |s| s.foreground(PopoverForeground))
      .focus_visible(P::Close, |s| s.focus_ring())
      .base(P::Timer, |s| s.width(Length::Fill).height(2.0).background(Secondary))
      .base(P::Remaining, |s| s.height(2.0).background(Primary))
      .base(P::Viewport, |s| s.padding_x(16.0).padding_y(16.0))
      .base(P::List, |s| s.gap(10.0))
      .base(P::BehindNear, |s| behind(s, 336.0, 0.75))
      .base(P::BehindFar, |s| behind(s, 312.0, 0.5))
      .state(ToastState::Action, P::Content, |s| s.padding_y(14.0).padding_end(12.0))
      .state(ToastState::Action, P::Text, |s| s.gap(2.0))
      .variant(ToastVariant::Info, P::Icon, |s| s.foreground(Info))
      .variant(ToastVariant::Success, P::Icon, |s| s.foreground(Success))
      .variant(ToastVariant::Warning, P::Icon, |s| s.foreground(Warning))
      .variant(ToastVariant::Destructive, P::Icon, |s| s.foreground(Destructive))
  }
}

/// Which toast of a [`Toasts`] it is, to take it away.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ToastId(u64);

/// A toast as a [`Toasts`] holds it. A toast is no value to share between threads, as an element is not: what
/// is in the signal is a toast behind a lock.
#[derive(Clone)]
struct Shown {
  id: ToastId,
  toast: Arc<Mutex<Toast>>,
}

impl Shown {
  fn toast(&self) -> Toast {
    self.toast.lock().unwrap_or_else(PoisonError::into_inner).clone()
  }
}

impl DevtoolsInspectable for Shown {}

/// The toasts an app shows: a handle it makes once, keeps in its root
/// component and clones into whatever shows a toast. Its host, which the
/// root renders once, draws them in a corner of the window over everything.
///
/// ```no_run
/// use lurq::{
///   app::{component::Component, ctx::Ctx},
///   components::{Button, Column},
///   node::Element,
///   ui::{Toast, ToastVariant, Toasts},
/// };
///
/// struct App {
///   toasts: Toasts,
/// }
///
/// impl Component for App {
///   type Props = ();
///
///   fn create(_ctx: &mut Ctx) -> Self {
///     Self { toasts: Toasts::new() }
///   }
///
///   fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
///     let toasts = self.toasts.clone();
///     Column::new()
///       .child(Button::new("Save").on_click(move |_| {
///         toasts.show(Toast::new("Settings saved").variant(ToastVariant::Success));
///       }))
///       // Last, so that its layer is over every other.
///       .child(self.toasts.mount(ctx))
///   }
/// }
/// ```
///
/// A toast leaves after its duration, on a press of its close control or of
/// its action, and by [`Toasts::dismiss`]. While the pointer is on the toasts
/// their time stands still, and they are laid out one over another; when it
/// leaves, their time runs on from where it stood.
#[derive(Clone)]
pub struct Toasts {
  shown: Signal<Vec<Shown>>,
  /// Whether the pointer is on the toasts: their time stands still, and they are not stacked.
  paused: Signal<bool>,
  next: Arc<AtomicU64>,
}

impl Toasts {
  /// No toasts yet.
  pub fn new() -> Self {
    Self {
      shown: Signal::new(Vec::new()),
      paused: Signal::new(false),
      next: Arc::new(AtomicU64::new(1)),
    }
  }

  /// Shows `toast`, in front of those already shown.
  pub fn show(&self, toast: Toast) -> ToastId {
    let id = ToastId(self.next.fetch_add(1, Ordering::Relaxed));
    self.shown.update(|shown| {
      shown.push(Shown {
        id,
        toast: Arc::new(Mutex::new(toast)),
      })
    });
    id
  }

  /// Takes the toast `id` away, if it is still shown.
  pub fn dismiss(&self, id: ToastId) {
    if !self
      .shown
      .with_untracked(|shown| shown.iter().any(|held| held.id == id))
    {
      return;
    }
    self.shown.update(|shown| shown.retain(|held| held.id != id));
    // With nothing left under it, the pointer is on no toast: the next one's time runs.
    if self.shown.with_untracked(Vec::is_empty) && self.paused.get_untracked() {
      self.paused.set(false);
    }
  }

  /// Takes every toast away.
  pub fn clear(&self) {
    if self.shown.with_untracked(Vec::is_empty) {
      return;
    }
    self.shown.set(Vec::new());
    if self.paused.get_untracked() {
      self.paused.set(false);
    }
  }

  /// The toasts shown and waiting, the oldest first.
  pub fn ids(&self) -> Vec<ToastId> {
    self.shown.with(|shown| shown.iter().map(|held| held.id).collect())
  }

  pub fn len(&self) -> usize {
    self.shown.with(Vec::len)
  }

  pub fn is_empty(&self) -> bool {
    self.shown.with(Vec::is_empty)
  }

  /// What draws the toasts at the bottom right of the window, and keeps their timers and the pointer on them.
  /// The app's root mounts it once, as its last child, so that its layer is over every other.
  pub fn mount(&self, ctx: &mut Ctx) -> Element {
    self.mount_at(ctx, ToastPosition::default())
  }

  /// What draws the toasts at `position` in the window: [`mount`](Self::mount) in another corner.
  pub fn mount_at(&self, ctx: &mut Ctx, position: ToastPosition) -> Element {
    ctx.mount::<ToastHost>(ToastHostProps {
      toasts: self.clone(),
      position,
    })
  }

  fn same(&self, other: &Self) -> bool {
    Arc::ptr_eq(&self.next, &other.next)
  }
}

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

/// A toast coming in from under where it stands, and from over it; leaving
/// downward, and upward. The animation engine registers these with the
/// spinner's turn, so that every app has them.
const ENTER_FROM_BELOW: KeyframesId = KeyframesId::new(0xFF11);
const ENTER_FROM_ABOVE: KeyframesId = KeyframesId::new(0xFF12);
const LEAVE_DOWNWARD: KeyframesId = KeyframesId::new(0xFF13);
const LEAVE_UPWARD: KeyframesId = KeyframesId::new(0xFF14);

/// How far a toast moves as it comes in and as it leaves: the distance of the toasts from the window's edge.
const TRAVEL: f32 = 16.0;

/// The keyframes of a toast coming in and leaving: it fades in as it moves
/// to its place from the window's edge, and out as it moves back to it.
pub(crate) fn keyframes() -> [Keyframes; 4] {
  let slide = |id: KeyframesId, from: (f32, f32), to: (f32, f32)| {
    Keyframes::new(id)
      .frame(0.0, |frame| {
        frame.set(AnimatableProperty::OffsetY, from.0);
        frame.set(AnimatableProperty::Opacity, from.1);
      })
      .frame(1.0, |frame| {
        frame.set(AnimatableProperty::OffsetY, to.0);
        frame.set(AnimatableProperty::Opacity, to.1);
      })
  };
  [
    slide(ENTER_FROM_BELOW, (TRAVEL, 0.0), (0.0, 1.0)),
    slide(ENTER_FROM_ABOVE, (-TRAVEL, 0.0), (0.0, 1.0)),
    slide(LEAVE_DOWNWARD, (0.0, 1.0), (TRAVEL, 0.0)),
    slide(LEAVE_UPWARD, (0.0, 1.0), (-TRAVEL, 0.0)),
  ]
}

#[derive(Clone)]
struct ToastHostProps {
  toasts: Toasts,
  position: ToastPosition,
}

impl PartialEq for ToastHostProps {
  fn eq(&self, other: &Self) -> bool {
    self.position == other.position && self.toasts.same(&other.toasts)
  }
}

impl DevtoolsInspectable for ToastHostProps {}

/// What draws the toasts of a [`Toasts`] in a corner of the window, in a
/// layer over everything that takes no press beside them and keeps no Tab
/// from the page. A component, since each toast keeps a timer of its own.
struct ToastHost {
  pile: Arc<Mutex<Pile>>,
  /// Runs out when the toasts behind the front one are behind it again, or a new one has come in over them:
  /// they are not drawn from then on.
  settle: Timeout,
  renders: Signal<u64>,
}

/// What the host remembers of its toasts from one render to the next.
#[derive(Default)]
struct Pile {
  /// The toast in front at the last render.
  front: Option<ToastId>,
  /// Whether the toasts behind the front one are drawn: while the pointer is on the toasts, while they go
  /// back behind the front one, and while a new one comes in over them.
  open: bool,
  /// Whether they were laid out one over another at the last render.
  spread: bool,
  /// The toast a new one is coming in over: it is seen under it until that one is in, and fades then.
  covered: Option<ToastId>,
  /// Whether the one that was covered has yet to fade: the next render gives it the time to.
  fades: bool,
  /// How high each toast was last laid out, and the element that says so.
  heights: Vec<(ToastId, ElementRef, f32)>,
}

impl Component for ToastHost {
  type Props = ToastHostProps;

  fn create(ctx: &mut Ctx) -> Self {
    let renders = ctx.signal(0_u64);
    let pile = Arc::new(Mutex::new(Pile::default()));
    let settle = ctx.create_timeout(Duration::ZERO, {
      let (renders, pile) = (renders.clone(), pile.clone());
      move || {
        let mut pile = pile.lock().unwrap_or_else(PoisonError::into_inner);
        // The one a new toast came in over is under it now, and fades there before it is not drawn.
        match pile.covered.take() {
          Some(_) => pile.fades = true,
          None => pile.open = false,
        }
        drop(pile);
        renders.update(|count| *count += 1)
      }
    });
    Self { pile, settle, renders }
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let _ = self.renders.get();
    let ToastHostProps { toasts, position } = ctx.props::<ToastHostProps>().clone();
    // The newest first: those shown, and how long each lasts.
    let front: Vec<(ToastId, Option<Duration>)> = toasts.shown.with(|shown| {
      shown
        .iter()
        .rev()
        .take(TOASTS_SHOWN)
        .map(|held| (held.id, held.toast().lasting()))
        .collect()
    });
    if front.is_empty() {
      // Closed, the layer stays while the last toast leaves.
      *self.pile.lock().unwrap_or_else(PoisonError::into_inner) = Pile::default();
      return Element::from(Modal::new(Element::new()).open_when(false));
    }
    let paused = toasts.paused.get();
    let theme = ctx.theme().clone();
    let recipe = theme.resolve::<Toast>(
      &Case {
        breakpoint: current_breakpoint(),
        ..Case::default()
      },
      None,
    );
    let bottom = position.at_bottom();
    let moving = theme.duration_value(MotionDuration::Base);

    // The toasts are one pile whatever the pointer does: each in its place by its id, the newest in front,
    // all standing at the window's edge. Under the pointer those behind move out, one over another; with the
    // pointer gone they move back behind the front one and are then not drawn. Nothing is laid out anew
    // between the two, so nothing jumps.
    let (open, spread, covered, heights) = {
      let mut pile = self.pile.lock().unwrap_or_else(PoisonError::into_inner);
      pile
        .heights
        .retain(|(id, ..)| front.iter().any(|(shown, _)| shown == id));
      for (id, _) in &front {
        if !pile.heights.iter().any(|(held, ..)| held == id) {
          pile.heights.push((*id, ElementRef::new(), 0.0));
        }
      }
      let was = pile
        .front
        .filter(|was| *was != front[0].0 && front.iter().any(|(id, _)| id == was));
      pile.front = Some(front[0].0);
      if paused {
        self.settle.cancel();
        pile.open = true;
        pile.covered = None;
      } else if was.is_some() && !theme.reduced_motion() {
        // A toast that comes in front of one still shown comes in over it: the one that was in front stays
        // drawn where it is until the new one is in.
        pile.open = true;
        pile.covered = was;
        self.settle.set_duration(theme.duration_value(MotionDuration::Slow));
        self.settle.restart();
      } else if pile.spread || pile.fades {
        // The pointer has gone, or the new toast is in: they are drawn while they move back and fade.
        self.settle.set_duration(moving);
        self.settle.restart();
      }
      pile.fades = false;
      pile.spread = paused;
      (pile.open, pile.spread, pile.covered, pile.heights.clone())
    };
    let height = |id: ToastId| {
      heights
        .iter()
        .find(|(held, ..)| *held == id)
        .map_or(0.0, |(.., height)| *height)
    };
    let gap = recipe
      .part(ToastPart::List)
      .rest()
      .gap
      .map_or(0.0, |gap| gap.resolve(&theme.spacing(), 0.0));
    // Away from the window's edge is up at the bottom of the window and down at its top.
    let away = if bottom { -1.0 } else { 1.0 };

    // A toast taken away leaves toward the window's edge: a keyframe animation, which reduced motion goes without.
    let leave = (!theme.reduced_motion()).then(|| {
      Animation::new(if bottom { LEAVE_DOWNWARD } else { LEAVE_UPWARD })
        .duration(moving)
        .easing(theme.easings().try_get(MotionEasing::Exit).unwrap_or(Easing::Linear))
    });
    let slide = Transition::offset_y().duration(moving).easing(
      theme
        .easings()
        .try_get(MotionEasing::Standard)
        .unwrap_or(Easing::Linear),
    );

    let fade = Transition::opacity().duration(moving).easing(
      theme
        .easings()
        .try_get(MotionEasing::Standard)
        .unwrap_or(Easing::Linear),
    );

    let behind = front.len() - 1;
    let mut pile = Stack::new().overflow_visible().presence().stack_align(if bottom {
      StackAlignment::BottomCenter
    } else {
      StackAlignment::TopCenter
    });
    // Laid out one over another they take the room of all of them, so that the pointer between two of them is
    // still on the toasts.
    if spread {
      let all: f32 = front.iter().map(|(id, _)| height(*id)).sum::<f32>() + gap * behind as f32;
      pile = pile.min_height(Dimension::Px(all));
    }

    // Behind the front one, an edge of each of the others, on the side away from the window's edge: drawn
    // taller than it shows, its far side under the toast in front. They fade while the toasts are laid out.
    let near = recipe.part(ToastPart::BehindNear);
    let peek = match near.rest().height.and_then(|height| height.resolve(recipe.theme())) {
      Some(Dimension::Px(px)) => px,
      _ => 0.0,
    };
    let in_front = height(front[0].0);
    let edge = |part: ToastPart, nth: f32| {
      Row::new()
        .overflow_visible()
        .pointer_events_none()
        .offset(0.0, away * (in_front + peek * nth - peek * 3.0))
        .opacity(if spread { 0.0 } else { 1.0 })
        .transition(Transition::opacity().duration(moving))
        .child(Row::new().part(&recipe.part(part)).height(Dimension::Px(peek * 3.0)))
    };
    // An edge stands by the height of the front toast, which is known once that was laid out.
    if in_front > 0.0 {
      if behind >= 2 {
        pile = pile.child(edge(ToastPart::BehindFar, 2.0).key("behind-far"));
      }
      if behind >= 1 {
        pile = pile.child(edge(ToastPart::BehindNear, 1.0).key("behind-near"));
      }
    }

    // The toasts, the furthest back first, each moved away from the window's edge by those in front of it.
    let mut before = vec![0.0; front.len()];
    for nth in 1..front.len() {
      before[nth] = before[nth - 1] + height(front[nth - 1].0) + gap;
    }
    for (nth, (id, duration)) in front.iter().copied().enumerate().rev() {
      let drawn = nth == 0 || open;
      let item = ctx.mount_keyed::<ToastItem>(
        &id.0.to_string(),
        ToastItemProps {
          toasts: toasts.clone(),
          id,
          paused,
          duration,
          shown: drawn,
          bottom,
        },
      );
      let measured = heights
        .iter()
        .find(|(held, ..)| *held == id)
        .map(|(_, measured, _)| measured.clone())
        .unwrap_or_default();
      // It says how high it is whenever that changes: those behind it are moved by it.
      let (held, renders) = (self.pile.clone(), self.renders.clone());
      measured.observe_rect(move |rect| {
        let mut pile = held.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some(entry) = pile.heights.iter_mut().find(|(known, ..)| *known == id)
          && (entry.2 - rect.height).abs() >= 0.5
          // One that is not drawn has no height: it keeps the one it had.
          && rect.height > 0.0
        {
          entry.2 = rect.height;
          drop(pile);
          renders.update(|count| *count += 1);
        }
      });
      let place = Row::new()
        .overflow_visible()
        .key(id.0.to_string())
        .ref_element(measured)
        .offset(0.0, if spread { away * before[nth] } else { 0.0 })
        // One behind the front one fades as it goes behind it, and comes back as it moves out: its panel and
        // its shadow are gone by the time it is not drawn, and nothing is seen to vanish.
        .opacity(if nth == 0 || spread || covered == Some(id) { 1.0 } else { 0.0 })
        .transition(slide.clone())
        .transition(fade.clone());
      let place = match &leave {
        Some(leave) => place.exit_animation(leave.clone()),
        None => place,
      };
      pile = pile.child(place.child(item));
    }

    // With the pointer on them their time stands still, and they are laid out one over another.
    let (enter, leave) = (toasts.paused.clone(), toasts.paused.clone());
    let shown = Row::new()
      .overflow_visible()
      .on_mouse_enter(move || enter.set(true))
      .on_mouse_leave(move || leave.set(false))
      .child(pile);
    // Clear of what the window's edges hold: a phone's notch, its home indicator, its keyboard. The layer is
    // under the title bar a window's chrome draws already.
    let safe = ctx.safe_area();
    let viewport = Column::new()
      .size(Dimension::Pct(100.0), Dimension::Pct(100.0))
      .hit_test(HitTestBehavior::ContentOnly)
      .overflow_visible()
      .padding(
        Padding::new()
          .top(safe.top)
          .right(safe.right)
          .bottom(safe.bottom + safe.keyboard)
          .left(safe.left),
      )
      .child(
        Column::new()
          .size(Dimension::Pct(100.0), Dimension::Pct(100.0))
          .hit_test(HitTestBehavior::ContentOnly)
          .overflow_visible()
          .justify(if bottom { Justify::End } else { Justify::Start })
          .align_items(position.across())
          .part(&recipe.part(ToastPart::Viewport))
          .child(shown),
      );
    // A layer like the window chrome's: over the page and its dialogs, taking a press only on what is in it,
    // and holding Tab to none of it, as a dialog's layer does.
    Element::from(
      Modal::new(viewport)
        .open_when(true)
        .target(Window)
        .dismiss_on_escape(false)
        .window_chrome_layer(),
    )
  }
}

#[derive(Clone)]
struct ToastItemProps {
  toasts: Toasts,
  id: ToastId,
  /// Whether the pointer is on the toasts: its time stands still.
  paused: bool,
  /// How long it lasts: `None` while it stays until it is closed.
  duration: Option<Duration>,
  /// Whether it is drawn: one behind the front one, while they are stacked, is not, and its time runs.
  shown: bool,
  /// Whether the toasts are at the bottom of the window: a toast comes in from under its place.
  bottom: bool,
}

impl PartialEq for ToastItemProps {
  fn eq(&self, other: &Self) -> bool {
    self.id == other.id
      && self.paused == other.paused
      && self.duration == other.duration
      && self.shown == other.shown
      && self.bottom == other.bottom
      && self.toasts.same(&other.toasts)
  }
}

impl DevtoolsInspectable for ToastItemProps {}

/// What a toast's timer has counted.
struct Clock {
  /// How long it had left when its time last stood still.
  left: Duration,
  /// Since when its time runs: `None` while it stands still.
  since: Option<Instant>,
  /// Whether it was drawn by the last render: its timer runs out from the next one on.
  drawn: bool,
  /// When it was first drawn: it comes in from then on.
  entered: Option<Instant>,
}

/// One toast a host shows, with its timer: it takes the toast away when the
/// toast's time is up, and keeps what is left of it while its time stands still.
struct ToastItem {
  timeout: Option<Timeout>,
  clock: Mutex<Clock>,
  /// Renders it once more right after it is first drawn: a transition runs from one width to another, so the
  /// timer is drawn where it is first and runs out from there.
  again: Timeout,
  renders: Signal<u64>,
}

impl Component for ToastItem {
  type Props = ToastItemProps;

  fn create(ctx: &mut Ctx) -> Self {
    let props = ctx.props::<ToastItemProps>().clone();
    let timeout = props.duration.map(|duration| {
      let (toasts, id) = (props.toasts.clone(), props.id);
      ctx.create_timeout(duration, move || toasts.dismiss(id))
    });
    let renders = ctx.signal(0_u64);
    let again = ctx.create_timeout(Duration::ZERO, {
      let renders = renders.clone();
      move || renders.update(|count| *count += 1)
    });
    Self {
      timeout,
      clock: Mutex::new(Clock {
        left: props.duration.unwrap_or_default(),
        since: None,
        drawn: false,
        entered: None,
      }),
      again,
      renders,
    }
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let _ = self.renders.get();
    let props = ctx.props::<ToastItemProps>().clone();
    let now = Instant::now();
    let mut clock = self.clock.lock().unwrap_or_else(PoisonError::into_inner);
    // Under the pointer its time stands still with what is left of it; let go, it runs on from there.
    if let Some(timeout) = &self.timeout {
      match (props.paused, clock.since) {
        (true, Some(since)) => {
          clock.left = clock.left.saturating_sub(now.saturating_duration_since(since));
          clock.since = None;
          timeout.cancel();
        }
        (false, None) => {
          clock.since = Some(now);
          timeout.set_duration(clock.left);
          timeout.start();
        }
        _ => {}
      }
    }
    if !props.shown {
      clock.drawn = false;
      return Element::new();
    }
    let toast = props
      .toasts
      .shown
      .with(|shown| shown.iter().find(|held| held.id == props.id).map(Shown::toast));
    let Some(mut toast) = toast else {
      return Element::new();
    };

    let left = match clock.since {
      Some(since) => clock.left.saturating_sub(now.saturating_duration_since(since)),
      None => clock.left,
    };
    toast.left = match props.duration {
      None => TimeLeft::All,
      Some(_) if clock.drawn && clock.since.is_some() => TimeLeft::RunningOut(left),
      Some(duration) => TimeLeft::Part(left.as_secs_f32() / duration.as_secs_f32().max(f32::EPSILON)),
    };
    if !clock.drawn {
      clock.drawn = true;
      self.again.restart();
    }
    // It comes in from the window's edge once, when it is first drawn: a keyframe animation, which reduced motion
    // goes without.
    let theme = ctx.theme().clone();
    let entered = *clock.entered.get_or_insert(now);
    let coming = theme.duration_value(MotionDuration::Slow);
    drop(clock);

    let dismiss = {
      let (toasts, id) = (props.toasts.clone(), props.id);
      move || toasts.dismiss(id)
    };
    toast.action = toast.action.map(|action| action.also(dismiss.clone()));
    // A finger throws it off: to a side, or toward the window's edge.
    let thrown = {
      let (dismiss, bottom) = (dismiss.clone(), props.bottom);
      move |swipe: SwipeEvent| {
        let away = match swipe.direction {
          SwipeDirection::Left | SwipeDirection::Right => true,
          SwipeDirection::Down => bottom,
          SwipeDirection::Up => !bottom,
        };
        if away {
          dismiss();
        }
      }
    };
    let mut item = Row::new().overflow_visible().on_swipe(thrown);
    if !theme.reduced_motion() && now.saturating_duration_since(entered) < coming {
      item = item.animation(
        Animation::new(if props.bottom {
          ENTER_FROM_BELOW
        } else {
          ENTER_FROM_ABOVE
        })
        .duration(coming)
        .easing(theme.easings().try_get(MotionEasing::Enter).unwrap_or(Easing::Linear)),
      );
    }
    Element::from(item.child(toast.on_close(dismiss)))
  }
}