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
//! A tooltip: a short text beside an element while the pointer rests on it or
//! the keyboard's focus is on it.
//!
//! It is a mounted component, not a builder that converts into an element:
//! it keeps a timer for its delay, an anchor that is the same from one render
//! to the next, and whether the pointer has shown it, none of which a builder
//! can keep. [`Tooltip`] says what it is, and [`Tooltip::mount`] puts it on
//! the element it describes.

use std::{
  cell::{Cell, RefCell},
  f32::consts::SQRT_2,
  sync::Arc,
  time::Duration,
};

use parking_lot::Mutex;

use super::{
  FontFamily, names,
  part_style::{Length, TransitionDuration},
  recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe},
  theme::{Themed, current_theme},
  tip::{length, side_of},
};
use crate::{
  app::{
    component::Component,
    ctx::{CollisionStrategy, Ctx, OpenState, Overlay, Placement, Timeout},
    events::MouseEvent,
    theme::{PaletteColor, RadiusSize, Theme, TypographyStyle},
  },
  components::{Column, Row},
  core::{ElementRect, ElementRef, Signal},
  layout::{
    Alignment,
    layout_kind::{Justify, LayoutKind},
    text_style::FontWeight,
  },
  node::{
    Element, HitTestBehavior, Node, NodeUpdate, SpacingValue, color::Color, dimension::Dimension,
    transform::Transform2D,
  },
  time::Instant,
};

/// How long the pointer rests on an element before its tooltip shows, as a
/// Markdown link's does: a tooltip's open delay unless it says otherwise.
pub const TOOLTIP_DELAY: Duration = Duration::from_millis(500);

/// How soon after a tooltip went another shows with no delay: the pointer
/// moving along a toolbar shows each button's at once.
pub const TOOLTIP_SKIP_DELAY: Duration = Duration::from_millis(300);

thread_local! {
  /// Until when a tooltip that shows skips its delay: a tooltip went just
  /// before. A window's tooltips are all on its thread.
  static WARM_UNTIL: Cell<Option<Instant>> = const { Cell::new(None) };
}

/// Whether a tooltip went so lately that the next shows at once.
fn warm() -> bool {
  WARM_UNTIL.with(|until| until.get().is_some_and(|until| Instant::now() < until))
}

/// A tooltip went, or the pointer left the element of one that shows: the
/// next to show within the skip delay shows at once.
fn went() {
  WARM_UNTIL.with(|until| until.set(Some(Instant::now() + TOOLTIP_SKIP_DELAY)));
}

/// What puts away a tooltip the pointer showed.
type Hide = Arc<dyn Fn() + Send + Sync>;

thread_local! {
  /// The tooltip the pointer showed last, by its host, and what puts it away.
  static SHOWING: RefCell<Option<(usize, Hide)>> = const { RefCell::new(None) };
}

/// The pointer showed the tooltip of the host `id`: the one it showed before,
/// still there for its grace, goes, so that one tooltip shows at a time.
fn take_turn(id: usize, hide: &Hide) {
  let before = SHOWING.with(|showing| showing.borrow_mut().replace((id, hide.clone())));
  if let Some((before, hide)) = before
    && before != id
  {
    hide();
  }
}

/// Sets `signal` to `value` if it is not that already: a signal set tells
/// what reads it even of the same value.
fn put(signal: &Signal<bool>, value: bool) {
  if signal.get_untracked() != value {
    signal.set(value);
  }
}

/// The parts of a tooltip a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TooltipPart {
  /// The box and its arrow, and the room between them and what they describe.
  Root,
  /// The box: its text and its shortcut, on the primary color.
  Panel,
  /// Its text: the title of a tooltip with a note.
  Label,
  /// The second line under the text, where it has one.
  Note,
  /// The keys of a shortcut after the text, in a chip of their own.
  Shortcut,
  /// What the arrow is drawn in: the triangle between the box and what it
  /// describes, in the color of the box.
  Arrow,
}

names!(TooltipPart {
  Root => "root",
  Panel => "panel",
  Label => "label",
  Note => "note",
  Shortcut => "shortcut",
  Arrow => "arrow",
});

/// The side of what it describes a tooltip is on: the side of its
/// [`Placement`], or the other one where there is no room on that side, its
/// arrow turned with it. It is the recipe's variant of a tooltip, and the
/// name of the side state of the other panels that point at an element.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TooltipSide {
  /// Above it, its arrow pointing down.
  #[default]
  Top,
  Bottom,
  Left,
  Right,
}

names!(TooltipSide {
  Top => "top",
  Bottom => "bottom",
  Left => "left",
  Right => "right",
});

impl TooltipSide {
  /// Whether the tooltip is above or below what it describes.
  fn vertical(self) -> bool {
    matches!(self, Self::Top | Self::Bottom)
  }

  fn opposite(self) -> Self {
    match self {
      Self::Top => Self::Bottom,
      Self::Bottom => Self::Top,
      Self::Left => Self::Right,
      Self::Right => Self::Left,
    }
  }
}

/// The states of a tooltip a recipe styles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TooltipState {
  /// It has an arrow.
  Arrow,
  /// It shows a shortcut after its text.
  Shortcut,
  /// Its text wraps: it is longer than the box is wide. Known once the text
  /// is laid out, so a tooltip shown on an element; one anchored to nothing
  /// is never in it.
  Multiline,
  /// It has a second line under its text.
  Note,
  /// Its text is a path, a command or code: in the theme's mono family.
  Mono,
}

names!(TooltipState {
  Arrow => "arrow",
  Shortcut => "shortcut",
  Multiline => "multiline",
  Note => "note",
  Mono => "mono",
});

/// What builds a tooltip's nodes: a theme's in place of the default one. It
/// builds what is shown, not when.
pub type TooltipRenderer = Arc<dyn Fn(TooltipView) -> Element + Send + Sync>;

/// A tooltip: a short text that says what an element does, beside it while
/// the pointer rests on it or the keyboard's focus is on it. An icon button's
/// "Copy", a field's "Stored in the OS keychain".
///
/// ```no_run
/// use lurq::{
///   app::ctx::{Ctx, Placement},
///   node::Element,
///   ui::{Button, Tooltip},
/// };
///
/// fn toolbar(ctx: &mut Ctx) -> Element {
///   let copy = Button::new("Copy").icon("copy").icon_only(true);
///   Tooltip::new("Copy").shortcut("Ctrl+C").placement(Placement::Bottom).mount(ctx, copy)
/// }
/// ```
///
/// It is above the element and centered on it unless its placement says
/// otherwise. It shows after the pointer has rested on the element for its
/// open delay, at once if another tooltip went a moment before, and at once
/// when the focus comes to the element, or to anything in it (a button in a
/// row), from the keyboard. It goes when the pointer has left both the
/// element and the tooltip for its close delay (the pointer can be moved
/// onto it to read it),
/// when the focus leaves, when the element is pressed, and on Escape, which
/// it takes before anything under it. One tooltip of the pointer shows at a
/// time. It takes no focus, and it stands beside the element, over it only
/// where the window has room on neither side, as it is kept in the window.
/// A disabled element shows its tooltip too. Its text is what tooling that
/// reads the tree is told the element is described by, and what the element
/// is called if nothing else names it.
///
/// Converted into an element on its own, a tooltip is its box as it shows,
/// anchored to nothing: for a gallery, a test, or a host of an app's own.
///
/// A label cut to its room with an ellipsis says itself whole in a tooltip
/// that shows only while it is cut:
///
/// ```no_run
/// use lurq::{
///   app::ctx::Ctx,
///   components::{Text, TextOverflow},
///   core::ElementRef,
///   node::Element,
///   ui::Tooltip,
/// };
///
/// fn path(ctx: &mut Ctx, label: &ElementRef, path: &str) -> Element {
///   let text = Text::new(path).nowrap().text_overflow(TextOverflow::Elipsis).ref_element(label.clone());
///   Tooltip::new(path).mono(true).max_width(400.0).when_cut(label).mount(ctx, text)
/// }
/// ```
#[derive(Clone)]
pub struct Tooltip {
  text: Arc<str>,
  note: Option<Arc<str>>,
  mono: bool,
  max_width: Option<Length>,
  when_cut: Option<ElementRef>,
  hint: Option<Arc<str>>,
  over: Option<ElementRef>,
  hung: Option<(ElementRef, OpenState)>,
  shortcut: Option<Arc<str>>,
  placement: Placement,
  offset: Option<SpacingValue>,
  collision: CollisionStrategy,
  arrow: bool,
  open_delay: TransitionDuration,
  close_delay: TransitionDuration,
  force_open: Option<bool>,
  disabled: bool,
  states: Vec<Name>,
  rules: Recipe,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

impl Tooltip {
  /// A tooltip that says `text`, above what it describes and centered on it
  /// (`Placement::Top`), with no arrow.
  pub fn new(text: &str) -> Self {
    Self {
      text: Arc::from(text),
      note: None,
      mono: false,
      max_width: None,
      when_cut: None,
      hint: None,
      over: None,
      hung: None,
      shortcut: None,
      placement: Placement::Top,
      offset: None,
      collision: CollisionStrategy::FlipThenClamp,
      arrow: false,
      open_delay: TransitionDuration::Set(TOOLTIP_DELAY),
      close_delay: TransitionDuration::Set(TOOLTIP_GRACE),
      force_open: None,
      disabled: false,
      states: Vec::new(),
      rules: Recipe::new(),
      id: None,
      key: None,
    }
  }

  /// The keys of a shortcut that does what the element does, after the text:
  /// "Ctrl+B".
  pub fn shortcut(mut self, keys: &str) -> Self {
    self.shortcut = (!keys.is_empty()).then(|| Arc::from(keys));
    self
  }

  /// A second line under the text, which says more: "Signed in as ada@example.com" under "Switch account". The
  /// text is then its title, in a medium weight; both wrap at the box's greatest width.
  pub fn note(mut self, note: &str) -> Self {
    self.note = (!note.is_empty()).then(|| Arc::from(note));
    self
  }

  /// Whether its text is a path, a command or code, set in the theme's mono family.
  pub fn mono(mut self, mono: bool) -> Self {
    self.mono = mono;
    self
  }

  /// The widest the box is before its text wraps, in place of the recipe's (200 in the design's): a path says
  /// itself on one line where the tooltip is given room for it.
  pub fn max_width(mut self, width: impl Into<Length>) -> Self {
    self.max_width = Some(width.into());
    self
  }

  /// Shows the tooltip only while the text whose ref `text` is is cut, as the last layout drew it: ended by an
  /// ellipsis where its room ran out, or cut to a limit of lines ([`ElementRef::text_cut`]). A label that says
  /// itself whole in its tooltip has one only where it is not whole already. The pointer and the focus show it
  /// as they would; a text that fits shows nothing, and is not described by it to what reads the tree, since it
  /// says the same itself. `text` is the label's own ref, in the element the tooltip is mounted on or anywhere
  /// else. With a [`hint`](Self::hint) it says the hint while the text is whole, and is shown then too.
  pub fn when_cut(mut self, text: &ElementRef) -> Self {
    self.when_cut = Some(text.clone());
    self
  }

  /// What the tooltip says while the text [`when_cut`](Self::when_cut) names is whole, in place of showing nothing:
  /// a tab whose label is a short key says the page's title while the key fits, and the title is its text, said
  /// while the key is cut too. Tooling is told the element is described by the hint. An empty hint is none.
  pub fn hint(mut self, hint: &str) -> Self {
    self.hint = (!hint.is_empty()).then(|| Arc::from(hint));
    self
  }

  /// Whether a text it names by [`when_cut`](Self::when_cut) is whole, as the last layout drew it.
  fn fits(&self) -> bool {
    self.when_cut.as_ref().is_some_and(|text| !text.text_cut())
  }

  /// Whether the tooltip shows only while a text is cut, and that text is whole.
  fn waits_for_cut(&self) -> bool {
    self.hint.is_none() && self.fits()
  }

  /// What the tooltip says now: its hint while the text it names is whole, else its text.
  fn says(&self) -> Arc<str> {
    match &self.hint {
      Some(hint) if self.fits() => hint.clone(),
      _ => self.text.clone(),
    }
  }

  /// Keeps the tooltip clear of `frame`, an element around the one it describes, on the side it opens on: its
  /// distance is measured from the frame's edge, and along it the tooltip lines up with its element as its placement
  /// says. A chip's tooltip over the field the chip sits in, not over the chip. Where the frame has no room on that
  /// side it goes to the frame's other side ([`Overlay::clear_of`]).
  pub fn over(mut self, frame: &ElementRef) -> Self {
    self.over = Some(frame.clone());
    self
  }

  /// The tooltip beside `anchor`, an element of the app's, shown while `open` is (a `bool`, or a `Signal<bool>` the
  /// app sets): the app shows it and puts it away, and the pointer, the focus, a press and Escape do nothing to it.
  /// It takes no pointer: what it covers is hovered and pressed through it. A toolbar that shows its buttons'
  /// tooltips itself, as the pointer comes to them, with no delay of the tooltip's.
  ///
  /// It is an element to put among the children of any container, the anchor's own or another: it takes no room
  /// there. Its open delay, close delay, `force_open` and `when_cut` are not used, and it describes nothing to
  /// tooling: the app names its element.
  pub fn hang(mut self, anchor: &ElementRef, open: impl Into<OpenState>) -> Element {
    self.hung = Some((anchor.clone(), open.into()));
    Element::component::<TooltipHost>(TooltipProps {
      tooltip: Arc::new(self),
      child: Element::new(),
    })
  }

  /// `overlay` at the tooltip's placement, with its collision, kept clear of its frame where it has one.
  fn placed(&self, overlay: Overlay) -> Overlay {
    let overlay = overlay.placement(self.placement).collision(self.collision);
    match &self.over {
      Some(frame) => overlay.clear_of(frame.clone()),
      None => overlay,
    }
  }

  /// Which side of what it describes the tooltip is on, where there is room,
  /// and which edge of it it lines up with: above it and centered
  /// (`Placement::Top`) by default.
  pub fn placement(mut self, placement: Placement) -> Self {
    self.placement = placement;
    self
  }

  /// How far the tooltip stands from what it describes, in place of what the
  /// theme gives it (6 in the design's). The pointer crosses it to the
  /// tooltip without the tooltip going.
  pub fn offset(mut self, offset: impl Into<SpacingValue>) -> Self {
    self.offset = Some(offset.into());
    self
  }

  /// What the tooltip does where there is no room for it on its side: goes to
  /// the other side, then is moved into the window, by default.
  pub fn collision(mut self, collision: CollisionStrategy) -> Self {
    self.collision = collision;
    self
  }

  /// Whether a triangle points from the box to what it describes.
  pub fn arrow(mut self, arrow: bool) -> Self {
    self.arrow = arrow;
    self
  }

  /// How long the pointer rests on the element before the tooltip shows: a
  /// duration of the theme's, or a set one; [`TOOLTIP_DELAY`] unless this
  /// says otherwise. The keyboard's focus shows it at once, and so does the
  /// pointer within [`TOOLTIP_SKIP_DELAY`] of another tooltip going.
  pub fn open_delay(mut self, delay: impl Into<TransitionDuration>) -> Self {
    self.open_delay = delay.into();
    self
  }

  /// How long the tooltip stays after the pointer left both it and the
  /// element: time to cross the room between them. 100 ms by default.
  pub fn close_delay(mut self, delay: impl Into<TransitionDuration>) -> Self {
    self.close_delay = delay.into();
    self
  }

  /// Shows the tooltip whatever the pointer and the focus do (`Some(true)`),
  /// or never (`Some(false)`); `None`, as it starts, leaves it to them. For a
  /// gallery, a test, a tour of the app.
  pub fn force_open(mut self, open: Option<bool>) -> Self {
    self.force_open = open;
    self
  }

  /// Whether the tooltip never shows: the element is as it would be without it.
  pub fn disabled(mut self, disabled: bool) -> Self {
    self.disabled = disabled;
    self
  }

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

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

  /// The id of the tooltip's root: what shows.
  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
  }

  /// Puts the tooltip on `element`, the element it describes, and returns
  /// that element. The pointer and the focus are the element's, or those of
  /// anything in it.
  pub fn mount(self, ctx: &mut Ctx, element: impl Into<Element>) -> Element {
    ctx.mount::<TooltipHost>(TooltipProps {
      tooltip: Arc::new(self),
      child: element.into(),
    })
  }

  /// Puts the tooltip on `element` as [`mount`](Self::mount) does, where no `Ctx` is at hand: it is mounted where a
  /// component renders the element, a builder's own element too.
  pub(crate) fn declared(self, element: impl Into<Element>) -> Element {
    Element::component::<TooltipHost>(TooltipProps {
      tooltip: Arc::new(self),
      child: element.into(),
    })
  }

  /// The tooltip as it is drawn on `side`, in `theme`, its text wrapped or not.
  fn view(&self, theme: &Theme, side: TooltipSide, multiline: bool) -> TooltipView {
    let case = Case {
      variant: Some(side.into()),
      size: None,
      density: None,
      breakpoint: super::current_breakpoint(),
      states: self.states.clone(),
    }
    .state(TooltipState::Arrow, self.arrow)
    .state(TooltipState::Shortcut, self.shortcut.is_some())
    .state(TooltipState::Multiline, multiline)
    .state(TooltipState::Note, self.note.is_some())
    .state(TooltipState::Mono, self.mono);
    // An offset given here is under what `style` and `rules` say of the root: the room on both sides of the
    // tooltip, so that it stays centered.
    let mut rules = Recipe::new();
    if let Some(width) = self.max_width {
      rules = rules.base(TooltipPart::Panel, |s| s.max_width(width));
    }
    if let Some(offset) = self.offset {
      rules = rules.base(TooltipPart::Root, |s| {
        if side.vertical() {
          s.padding_y(offset)
        } else {
          s.padding_x(offset)
        }
      });
    }
    let rules = rules.extend(&self.rules);
    TooltipView {
      text: self.says(),
      note: self.note.clone(),
      shortcut: self.shortcut.clone(),
      side,
      arrow: self.arrow,
      aim: 0.0,
      recipe: theme.resolve::<Tooltip>(&case, Some(&rules)).owned_by(self.id.as_ref()),
      label_ref: None,
      id: self.id.clone(),
      key: self.key.clone(),
    }
  }

  /// Builds what `view` shows: the theme's renderer, or the default one.
  fn render_view(view: TooltipView) -> Element {
    match view.theme().renderer::<Tooltip>() {
      Some(renderer) => renderer(view),
      None => view.render(),
    }
  }

  /// Builds the tooltip's box as it shows, anchored to nothing, in `theme`.
  /// Converting a tooltip into an element does this in the theme of what is
  /// being rendered.
  pub fn build(self, theme: &Theme) -> Element {
    Self::render_view(self.view(theme, side_of(self.placement), false))
  }
}

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

/// A tooltip as a renderer sees it: what it says, the side it is on, and the
/// style of its parts.
pub struct TooltipView {
  pub text: Arc<str>,
  /// The second line under the text, if it has one.
  pub note: Option<Arc<str>>,
  pub shortcut: Option<Arc<str>>,
  /// The side it is on: the side its placement gives, or the other where there was no room.
  pub side: TooltipSide,
  pub arrow: bool,
  /// How far along the box's edge from its middle the arrow is, toward the
  /// middle of what the tooltip describes: not 0 where the box was pushed
  /// along to stay in the window. Never so far that the arrow leaves the box.
  pub aim: f32,
  /// The style of each part of this tooltip.
  pub recipe: ResolvedRecipe,
  /// What the host reads the label's height by, to know whether it wraps.
  label_ref: Option<ElementRef>,
  id: Option<Arc<str>>,
  key: Option<Arc<str>>,
}

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

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

  /// The box: the text, its note under it, and the shortcut after them.
  pub fn panel(&self) -> Row {
    let label = self.part(TooltipPart::Label);
    let mut panel = Row::new()
      .align_items(Alignment::Center)
      .part(&self.part(TooltipPart::Panel));
    // The text gives way to the box's greatest width, and wraps.
    let mut words = label.text(&self.text).flex_shrink(1.0);
    if let Some(label_ref) = &self.label_ref {
      words = words.ref_element(label_ref.clone());
    }
    panel = match self.note() {
      // The title and its note in a column that gives way as the text alone would, both wrapping in it.
      Some(note) => panel.child(Column::new().flex_shrink(1.0).min_width(0.0).child(words).child(note)),
      None => panel.child(words),
    };
    if let Some(keys) = &self.shortcut {
      // A text too long to have the shortcut beside it wraps across the box, and the shortcut goes under it:
      // beside it the text would be squeezed into what the shortcut leaves.
      panel = panel.wrap();
      let part = self.part(TooltipPart::Shortcut);
      panel = panel.child(
        Row::new()
          .align_items(Alignment::Center)
          .flex_shrink(0.0)
          .part(&part)
          .child(part.text(keys).nowrap()),
      );
    }
    panel
  }

  /// The second line under the text, in the style of its part, if the tooltip has one.
  pub fn note(&self) -> Option<Element> {
    let note = self.note.as_ref()?;
    let part = self.part(TooltipPart::Note);
    Some(
      Row::new()
        .min_width(0.0)
        .part(&part)
        .child(part.text(note).flex_shrink(1.0))
        .into(),
    )
  }

  /// The arrow: a square in the color of the box, turned a quarter of a
  /// right angle, its middle on the edge of the arrow's part that meets the
  /// box, so that the part, which clips, shows the half that points away from
  /// it. `None` without an arrow, and where the recipe gives the arrow's part
  /// no size in pixels or the box no color.
  pub fn arrow(&self) -> Option<Element> {
    let (along, away) = self.arrow_size()?;
    let part = self.part(TooltipPart::Arrow);
    let fill = self.part(TooltipPart::Panel).rest().background?;
    let vertical = self.side.vertical();
    let side = along / SQRT_2;
    // The arrow's part is on the side of the box toward what it describes: its edge that meets the box is the
    // near one above or left of what it describes, the far one below or right of it.
    let shift = match self.side {
      TooltipSide::Top | TooltipSide::Left => -away / 2.0,
      TooltipSide::Bottom | TooltipSide::Right => away / 2.0,
    };
    let (dx, dy) = if vertical { (0.0, shift) } else { (shift, 0.0) };
    let tip = Row::new()
      .width(side)
      .height(side)
      .flex_shrink(0.0)
      .background(fill)
      .offset(dx, dy)
      .transform(Transform2D::rotate_deg(45.0));
    // The part's long side is its main axis, so the square is not shrunk to its short one. It is moved along
    // the box by the aim, not laid out there: the box's size does not change with it.
    Some(if vertical {
      Row::new()
        .justify(Justify::Center)
        .align_items(Alignment::Center)
        .part(&part)
        .offset(self.aim, 0.0)
        .child(tip)
        .into()
    } else {
      Column::new()
        .justify(Justify::Center)
        .align_items(Alignment::Center)
        .part(&part)
        .offset(0.0, self.aim)
        .child(tip)
        .into()
    })
  }

  /// How long the arrow is along the box's edge, and how far out from it it
  /// goes: the size of the arrow's part. `None` without an arrow, and where
  /// the recipe gives the part no size in pixels.
  pub fn arrow_size(&self) -> Option<(f32, f32)> {
    if !self.arrow {
      return None;
    }
    let theme = self.theme();
    let px = |length: Option<Length>| match length?.resolve(theme)? {
      Dimension::Px(px) => Some(px),
      _ => None,
    };
    let rest = self.part(TooltipPart::Arrow).rest();
    let (width, height) = (px(rest.width)?, px(rest.height)?);
    Some(if self.side.vertical() {
      (width, height)
    } else {
      (height, width)
    })
  }

  /// How the default renderer builds a tooltip: the box, and the arrow on
  /// the side of it toward what it describes.
  pub fn render(self) -> Element {
    let (panel, arrow) = (self.panel(), self.arrow());
    let root = self.part(TooltipPart::Root);
    let toward_after = matches!(self.side, TooltipSide::Top | TooltipSide::Left);
    let mut children: Vec<Element> = vec![panel.into()];
    if let Some(arrow) = arrow {
      if toward_after {
        children.push(arrow);
      } else {
        children.insert(0, arrow);
      }
    }
    let mut root: Element = if self.side.vertical() {
      Column::new()
        .align_items(Alignment::Center)
        .part(&root)
        .describe("a11y_role", "tooltip")
        .with_children(children)
        .into()
    } else {
      Row::new()
        .align_items(Alignment::Center)
        .part(&root)
        .describe("a11y_role", "tooltip")
        .with_children(children)
        .into()
    };
    if let Some(id) = &self.id {
      root = root.id(id.clone());
    }
    if let Some(key) = &self.key {
      root = root.key(key.clone());
    }
    root
  }
}

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

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

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

  /// The design's tooltip (`pencil/lurq-design-system.pen`, Tooltip and
  /// Tooltip/Arrow): a box in the primary color with a radius of 6, its text
  /// in the primary's foreground in 12, 10 from its sides and 6 from its top
  /// and bottom, and no wider than 200, where a longer text wraps. A shortcut
  /// is 8 after the text, in a chip of 16 high, 4 from its sides, with a
  /// radius of 3, in a white of 15%, its keys in the mono family in 10. The
  /// arrow is 12 along the box and 6 out from it. It stands 6 from what it
  /// describes. A text that wraps has 8 above and below it, in lines of 1.4.
  /// A note is under the text, 2 below it, in 12 of the regular weight in
  /// lines of 1.4, the text over it in a medium weight; a tooltip with a note
  /// has 6 above and below its lines. A mono tooltip's text is in the mono
  /// family.
  fn recipe() -> Recipe {
    use PaletteColor::{Primary, PrimaryForeground};
    use TooltipPart::{Arrow, Label, Note, Panel, Root, Shortcut};
    use TooltipSide::{Bottom, Left, Right, Top};
    Recipe::new()
      .base(Panel, |s| {
        s.background(Primary)
          .foreground(PrimaryForeground)
          .radius(RadiusSize::Md)
          .padding_x(10.0)
          .padding_y(6.0)
          .gap(8.0)
          .max_width(200.0)
      })
      .base(Label, |s| s.typography(TypographyStyle::Caption))
      .base(Shortcut, |s| {
        s.height(16.0)
          .padding_x(4.0)
          .radius(3.0)
          .background(Color::from_hex("#FFFFFF26"))
          .font_family(FontFamily::Mono)
          .font_size(10.0)
      })
      .base(Arrow, |s| s.width(12.0).height(6.0))
      // A text that wraps: 8 above and below it, in lines of 1.4.
      .state(TooltipState::Multiline, Panel, |s| s.padding_y(8.0))
      .state(TooltipState::Multiline, Label, |s| s.line_height(1.4))
      .base(Note, |s| {
        s.typography(TypographyStyle::Caption)
          .weight(FontWeight::Normal)
          .line_height(1.4)
          .padding_top(2.0)
      })
      .state(TooltipState::Note, Panel, |s| s.padding_y(6.0))
      .state(TooltipState::Note, Label, |s| s.weight(FontWeight::Medium))
      .state(TooltipState::Mono, Label, |s| s.font_family(FontFamily::Mono))
      // The room between the tooltip and what it describes, on both sides of it so that it stays centered.
      .variant(Top, Root, |s| s.padding_y(6.0))
      .variant(Bottom, Root, |s| s.padding_y(6.0))
      .variant(Left, Root, |s| s.padding_x(6.0))
      .variant(Right, Root, |s| s.padding_x(6.0))
      .variant(Left, Arrow, |s| s.width(6.0).height(12.0))
      .variant(Right, Arrow, |s| s.width(6.0).height(12.0))
  }
}

/// A tooltip and the element it describes.
#[derive(Clone)]
struct TooltipProps {
  tooltip: Arc<Tooltip>,
  child: Element,
}

/// The element is built anew by every render of what holds it, so props are
/// never the same as before.
impl PartialEq for TooltipProps {
  fn eq(&self, _: &Self) -> bool {
    false
  }
}

impl crate::app::component::DevtoolsInspectable for TooltipProps {}

/// How long a tooltip stays after the pointer left the element or the
/// tooltip unless its close delay says otherwise: time to cross the room
/// between them, so that the pointer can be moved onto the tooltip to read
/// it, and off it, without it going.
const TOOLTIP_GRACE: Duration = Duration::from_millis(100);

/// Where the pointer is: on the element, on the tooltip.
#[derive(Default)]
struct Pointer {
  on_element: bool,
  on_tooltip: bool,
}

/// What shows a tooltip on the element it describes, and when.
struct TooltipHost {
  /// Whether the pointer has rested on the element for the delay, and not left both it and the tooltip since.
  hovered: Signal<bool>,
  /// Whether the tooltip may show: Escape (the runtime closes the top layer that takes it) or a press of the
  /// element turns it off, and it stays off until the pointer comes again, or until nothing asks for the
  /// tooltip (the pointer and the focus both gone), when a new one takes its place.
  allowed: Mutex<Signal<bool>>,
  /// Whether the tooltip was put on the other side, where there was no room on its own: its arrow turns with it.
  flipped: Signal<bool>,
  /// How far along the box the arrow is moved toward the element's middle, where the box was pushed along.
  aim: Signal<f32>,
  /// Whether the text wraps.
  multiline: Signal<bool>,
  /// What the readers of where the tooltip was put need from the last render: the side its placement gives, the
  /// element's anchor, the arrow's length along the box and the label's font size.
  placing: Arc<Mutex<Placing>>,
  pointer: Arc<Mutex<Pointer>>,
  /// The open delay: before the pointer shows it.
  delay: Timeout,
  /// The close delay: the grace after the pointer left before it goes.
  grace: Timeout,
  /// The element's anchor where the element has none of its own.
  anchor: ElementRef,
  /// What shows, and its label.
  shown: ElementRef,
  label: ElementRef,
  /// Who this host is among the tooltips the pointer shows, and what puts its tooltip away.
  id: usize,
  hide: Hide,
}

/// See [`TooltipHost::placing`].
struct Placing {
  side: TooltipSide,
  anchor: ElementRef,
  along: f32,
  font_size: f32,
}

impl TooltipHost {
  /// Reads where the overlay put what shows: on which side of the element, and how far along from the
  /// element's middle; the overlay does not say.
  fn read_placement(placing: &Mutex<Placing>, rect: ElementRect, flipped: &Signal<bool>, aim: &Signal<f32>) {
    // Read and let go before a signal is set: what the signal tells may read it too.
    let (side, anchor, along) = {
      let placing = placing.lock();
      (placing.side, placing.anchor.clone(), placing.along)
    };
    let ((x, y), (anchor_x, anchor_y)) = (rect.center(), anchor.bounds().center());
    let other = match side {
      TooltipSide::Top => y > anchor_y,
      TooltipSide::Bottom => y < anchor_y,
      TooltipSide::Left => x > anchor_x,
      TooltipSide::Right => x < anchor_x,
    };
    put(flipped, other);
    // The root is as long as the box along the side's edge: its room is on the other axis.
    let (off, length) = if side.vertical() {
      (anchor_x - x, rect.width)
    } else {
      (anchor_y - y, rect.height)
    };
    let limit = (length / 2.0 - along).max(0.0);
    let off = (off.clamp(-limit, limit) * 2.0).round() / 2.0;
    if (aim.get_untracked() - off).abs() > 0.25 {
      aim.set(off);
    }
  }
}

impl TooltipHost {
  /// `tooltip` as it is drawn beside `anchor` now, on the side it was put on, and what the readers of where it was
  /// put need noted.
  fn view(&self, tooltip: &Tooltip, theme: &Theme, anchor: &ElementRef) -> TooltipView {
    let placed = side_of(tooltip.placement);
    let side = if self.flipped.get() { placed.opposite() } else { placed };
    let mut view = tooltip.view(theme, side, self.multiline.get());
    view.aim = self.aim.get();
    view.label_ref = Some(self.label.clone());
    let mut placing = self.placing.lock();
    placing.side = placed;
    placing.anchor = anchor.clone();
    placing.along = view.arrow_size().map_or(0.0, |(along, _)| along);
    placing.font_size = view
      .part(TooltipPart::Label)
      .rest()
      .text
      .resolve(view.theme())
      .font_size;
    view
  }

  /// A tooltip the app shows itself beside `anchor` ([`Tooltip::hang`]): its layer while `open`, which takes no
  /// pointer and is put away by nothing but the app.
  fn hung(&self, tooltip: &Tooltip, anchor: &ElementRef, open: bool) -> Element {
    let view = self.view(tooltip, &current_theme(), anchor);
    if !open || view.text.is_empty() {
      return Overlay::new(Element::new()).open_when(false).into();
    }
    let shown = Tooltip::render_view(view).map_node(|node| node.ref_element(self.shown.clone()));
    tooltip
      .placed(Overlay::new(shown).anchor(anchor.clone()))
      .hit_test(HitTestBehavior::None)
      .into()
  }
}

impl Component for TooltipHost {
  type Props = TooltipProps;

  fn create(ctx: &mut Ctx) -> Self {
    let hovered = ctx.signal(false);
    let pointer = Arc::new(Mutex::new(Pointer::default()));
    let id = Arc::as_ptr(&pointer) as usize;
    let hide: Hide = {
      let hovered = hovered.clone();
      Arc::new(move || put(&hovered, false))
    };
    let delay = {
      let (hovered, hide) = (hovered.clone(), hide.clone());
      ctx.create_timeout(TOOLTIP_DELAY, move || {
        put(&hovered, true);
        take_turn(id, &hide);
      })
    };
    let grace = {
      let (hovered, pointer) = (hovered.clone(), pointer.clone());
      ctx.create_timeout(TOOLTIP_GRACE, move || {
        let pointer = pointer.lock();
        if !pointer.on_element && !pointer.on_tooltip && hovered.get_untracked() {
          hovered.set(false);
          went();
        }
      })
    };
    let (anchor, shown, label) = (ElementRef::new(), ElementRef::new(), ElementRef::new());
    let (flipped, aim, multiline) = (ctx.signal(false), ctx.signal(0.0_f32), ctx.signal(false));
    let placing = Arc::new(Mutex::new(Placing {
      side: TooltipSide::Top,
      anchor: anchor.clone(),
      along: 0.0,
      font_size: 0.0,
    }));
    {
      let (placing, flipped, aim) = (placing.clone(), flipped.clone(), aim.clone());
      shown.observe_rect(move |rect| Self::read_placement(&placing, rect, &flipped, &aim));
    }
    {
      // A label more than about a line and a half high wraps. The lines of a wrapped text are taller, so a text
      // that wraps stays wrapped, and one that does not is never as high.
      let (placing, multiline) = (placing.clone(), multiline.clone());
      label.observe_rect(move |rect| {
        let font_size = placing.lock().font_size;
        put(&multiline, font_size > 0.0 && rect.height > font_size * 1.6);
      });
    }
    Self {
      hovered,
      allowed: Mutex::new(ctx.signal(true)),
      flipped,
      aim,
      multiline,
      placing,
      pointer,
      delay,
      grace,
      anchor,
      shown,
      label,
      id,
      hide,
    }
  }

  fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
    let TooltipProps { tooltip, child } = ctx.props::<TooltipProps>().clone();
    if tooltip.disabled {
      return child;
    }
    if let Some((anchor, open)) = &tooltip.hung {
      return self.hung(&tooltip, anchor, open.is_open());
    }
    let theme = current_theme();
    let (open_delay, close_delay) = (length(tooltip.open_delay, &theme), length(tooltip.close_delay, &theme));
    self.delay.set_duration(open_delay);
    self.grace.set_duration(close_delay);
    // A disabled element is not hovered, but it hears the pointer come and go: its tooltip is on it as on any.
    let child = holds_children(child);
    // An element that has an anchor of its own keeps it, and the tooltip is anchored to it.
    let anchor = child.node.element_ref.clone().unwrap_or_else(|| self.anchor.clone());

    // Reading them subscribes: this renders again when the pointer, the focus or Escape changes them. The focus
    // is the element's or that of anything in it, a button in a row.
    let asked = self.hovered.get() || anchor.focus_visible_within();
    let allowed = {
      let mut allowed = self.allowed.lock();
      if !asked {
        // Nothing asks for it: whatever put it away is over, and the next time it is asked for it shows.
        *allowed = Signal::new(true);
      }
      allowed.clone()
    };
    let view = self.view(&tooltip, &theme, &anchor);
    // One that waits for its text to be cut shows nothing while it is whole.
    let shows = !view.text.is_empty() && tooltip.force_open.unwrap_or(asked && !tooltip.waits_for_cut());
    // A tooltip that went from under the pointer is told of no leave: the pointer is on it no longer.
    if !shows || (tooltip.force_open.is_none() && !allowed.get()) {
      self.pointer.lock().on_tooltip = false;
    }
    let overlay = if shows {
      let tooltip_enter = {
        let (pointer, grace) = (self.pointer.clone(), self.grace.clone());
        move || {
          pointer.lock().on_tooltip = true;
          grace.cancel();
        }
      };
      let tooltip_leave = {
        let (pointer, grace, hovered) = (self.pointer.clone(), self.grace.clone(), self.hovered.clone());
        move || {
          pointer.lock().on_tooltip = false;
          if hovered.get_untracked() {
            grace.restart();
          }
        }
      };
      let shown = Tooltip::render_view(view).map_node(|node| {
        node
          .ref_element(self.shown.clone())
          .on_mouse_enter(tooltip_enter)
          .on_mouse_leave(tooltip_leave)
      });
      let overlay = tooltip
        .placed(Overlay::new(shown).anchor(anchor.clone()))
        // The pointer can be moved onto the tooltip, its root and the room in it toward the element included (with
        // `ContentOnly` the root, which holds the handlers, would not be hit). It stands beside the element, so it
        // covers nothing of it.
        .hit_test(HitTestBehavior::Auto);
      match tooltip.force_open {
        // Shown by the app: Escape is not the tooltip's to take.
        Some(_) => overlay,
        // The runtime turns `allowed` off on an Escape while this is the top layer that takes it, so the key
        // closes the tooltip and not the dialog under it.
        None => overlay.open(allowed.clone()).dismiss_on_escape(true),
      }
    } else {
      Overlay::new(Element::new()).open_when(false)
    };
    // An element is not shared between threads as it is: the decoration, which is, holds it in a lock.
    let overlay = Arc::new(Mutex::new(Element::from(overlay)));

    let enter = {
      let (hovered, allowed, delay, grace, pointer, wait) = (
        self.hovered.clone(),
        allowed.clone(),
        self.delay.clone(),
        self.grace.clone(),
        self.pointer.clone(),
        open_delay,
      );
      let (id, hide) = (self.id, self.hide.clone());
      move || {
        pointer.lock().on_element = true;
        grace.cancel();
        put(&allowed, true);
        if hovered.get_untracked() {
          return;
        }
        if wait.is_zero() || warm() {
          delay.cancel();
          hovered.set(true);
          take_turn(id, &hide);
        } else {
          delay.restart();
        }
      }
    };
    let leave = {
      let (hovered, allowed, delay, grace, pointer) = (
        self.hovered.clone(),
        allowed.clone(),
        self.delay.clone(),
        self.grace.clone(),
        self.pointer.clone(),
      );
      let tooltip = tooltip.clone();
      move || {
        pointer.lock().on_element = false;
        delay.cancel();
        if !hovered.get_untracked() {
          return;
        }
        if tooltip.waits_for_cut() {
          // Nothing showed: nothing to move onto, and the next tooltip along waits for its delay.
          hovered.set(false);
        } else if allowed.get_untracked() {
          // It stays for its grace, and the next tooltip along shows at once.
          grace.restart();
          went();
        } else {
          // Put away already: nothing is there to move onto.
          hovered.set(false);
        }
      }
    };
    // A press puts it away until the pointer comes again or the focus leaves.
    let press = {
      let (hovered, allowed, delay, grace) = (
        self.hovered.clone(),
        allowed.clone(),
        self.delay.clone(),
        self.grace.clone(),
      );
      move |_: MouseEvent| {
        delay.cancel();
        grace.cancel();
        if hovered.get_untracked() && allowed.get_untracked() {
          went();
        }
        put(&hovered, false);
        put(&allowed, false);
      }
    };

    let text = tooltip.hint.clone().unwrap_or_else(|| tooltip.text.clone());
    // A text that says itself whole in its tooltip is not described by it again; one with a hint is, by the hint.
    let described = tooltip.when_cut.is_none() || tooltip.hint.is_some();
    let describe = move |node: Node| {
      // Named by what it says of itself, or by a text in it: a button by its label. What tooling is told is kept
      // only where there is tooling to tell.
      let named = !crate::node::TOOLING
        || node
          .debug_attrs()
          .iter()
          .any(|(name, value)| &**name == "a11y_name" && !value.trim().is_empty())
        || says_something(&node);
      let mut node = node
        .ref_element(anchor.clone())
        .on_mouse_enter(enter.clone())
        .on_mouse_leave(leave.clone())
        .on_mouse_down(press.clone());
      if described {
        NodeUpdate::describe(&mut node, Arc::from("a11y_description"), text.clone());
      }
      if !named {
        NodeUpdate::describe(&mut node, Arc::from("a11y_name"), text.clone());
      }
      // The overlay is declared in the element: a layer is found among the children of a container.
      NodeUpdate::child(&mut node, overlay.lock().clone().into_node());
      node
    };
    child.decorate_root(describe)
  }
}

/// Whether `node` or something in it is a text that says something: what
/// names an element to what reads the tree where nothing else does. An icon
/// is a glyph of the private use areas, which says nothing.
fn says_something(node: &Node) -> bool {
  let private = |c: char| matches!(c, '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{10FFFF}');
  node
    .text_content()
    .is_some_and(|text| text.chars().any(|c| !c.is_whitespace() && !private(c)))
    || node.children().iter().any(says_something)
}

/// `element`, in a row of its own where its root lays out no children (a
/// text, a wrapper of one child): what declares the overlay must be a
/// container, or the overlay is never laid out. The row gives way where what
/// holds it has no room, as the element would: a label cut with an ellipsis is
/// cut in it.
fn holds_children(element: Element) -> Element {
  match element.node.layout_kind() {
    LayoutKind::Row { .. } | LayoutKind::Column { .. } | LayoutKind::Stack { .. } | LayoutKind::Grid(_) => element,
    _ => Row::new().flex_shrink(1.0).min_width(0.0).child(element).into(),
  }
}