eave-api 0.1.3

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

use std::ops::RangeInclusive;

/// The role of a piece of text. The theme decides the color.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Tone {
    #[default]
    Normal,
    /// Secondary information.
    Dim,
    /// The thing to notice: today in a calendar, the active workspace.
    Accent,
    Warning,
    Critical,
    /// Healthy, or gaining: a charging battery.
    Good,
}

/// A status symbol. It names what to show and how full it is; the host draws it in the text's
/// tone, at the text's size. Fractions are 0.0 to 1.0.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Icon {
    /// A speaker with sound waves for the level. Above 1.0 is amplified.
    Volume { level: f32, muted: bool },
    /// A Wi-Fi fan with as many bars as the signal. `None` when there's no link.
    Wifi { strength: Option<f32> },
    /// A wired connection.
    Wired,
    /// A battery filled to its charge.
    Battery { charge: f32, charging: bool },
    /// A padlock: a secured network.
    Lock,
    /// An `i` in a circle: more about this.
    Info,
    /// A chevron pointing left: back, or earlier.
    Back,
    /// A chevron pointing right: on, or later.
    Forward,
    /// A check mark: the one in use.
    Check,
    /// A circling arrow: look again.
    Refresh,
    /// A cross: close this.
    Close,
    /// An eye: show what's hidden.
    Reveal,
    /// A lightning bolt: charging.
    Bolt,
    /// A power plug: on mains power.
    Plug,
    /// A microphone, struck through when muted.
    Mic { muted: bool },
    /// A loudspeaker box: built-in speakers.
    Speaker,
    /// Headphones, or a headset.
    Headphones,
    /// A screen: a monitor or TV that plays sound.
    Display,
    /// A bell: notifications, struck through when they're silenced.
    Bell { muted: bool },
    /// Three level bars, like an equalizer: media. Uneven while `playing`, low and level when
    /// not.
    Media { playing: bool },
    /// A triangle pointing right: play.
    Play,
    /// Two upright bars: pause.
    Pause,
    /// A triangle pointing left against a bar: back to the previous track.
    Previous,
    /// A triangle pointing right against a bar: on to the next track.
    Next,
}

/// A piece of UI. Build it with the functions in this module.
pub struct Node<M>(Kind<M>);

#[doc(hidden)]
pub enum Kind<M> {
    Label {
        text: String,
        tone: Option<Tone>,
    },
    Heading {
        text: String,
        tone: Option<Tone>,
    },
    Icon {
        icon: Icon,
        tone: Option<Tone>,
    },
    AppIcon {
        app_id: String,
        tone: Option<Tone>,
    },
    Image {
        file: &'static [u8],
        tint: bool,
        tone: Option<Tone>,
    },
    Sprite {
        frames: &'static [&'static [u8]],
        /// Indices into `frames`, in the order they play.
        order: &'static [u8],
        /// Plays for as long as it shows, not only when it shows up or changes.
        looping: bool,
        tone: Option<Tone>,
    },
    Cover {
        url: String,
        /// Shown until the picture is loaded, and instead of it if it can't be.
        fallback: Box<Node<M>>,
        /// The main picture of a popover, not an icon.
        large: bool,
        tone: Option<Tone>,
    },
    Counter {
        value: i64,
        range: RangeInclusive<i64>,
        unit: String,
        tone: Option<Tone>,
    },
    Alternate {
        options: Vec<Node<M>>,
        current: usize,
        /// Shown instead of `current` while the pointer is over the item.
        hovered: Option<usize>,
        /// As wide as the option on screen, hovered by its own width, after a rest ([`expand`]).
        grows: bool,
    },
    Row(Vec<Node<M>>),
    Column(Vec<Node<M>>),
    Grid {
        columns: usize,
        cells: Vec<Node<M>>,
    },
    Button {
        content: Box<Node<M>>,
        on_press: M,
        on_secondary: Option<M>,
        /// The main action of a popover page: filled, so it stands out.
        prominent: bool,
    },
    Switcher {
        options: Vec<(Node<M>, M)>,
        current: Option<usize>,
    },
    Gulp(Box<Node<M>>),
    /// Centered across the panel's width.
    Center(Box<Node<M>>),
    Separator,
    Empty,
    ListItem {
        title: String,
        subtitle: Option<String>,
        leading: Option<Box<Node<M>>>,
        trailing: Option<Box<Node<M>>>,
        selected: bool,
        on_press: Option<M>,
        on_secondary: Option<M>,
    },
    List(Vec<Node<M>>),
    Section {
        title: String,
        trailing: Option<Box<Node<M>>>,
    },
    Header {
        title: String,
        on_back: Option<M>,
        trailing: Option<Box<Node<M>>>,
    },
    Detail {
        name: String,
        value: Box<Node<M>>,
    },
    Fill,
    Slider {
        value: f32,
        range: RangeInclusive<f32>,
        step: f32,
        on_change: Box<dyn Fn(f32) -> M>,
        on_release: Option<M>,
    },
    Toggle {
        on: bool,
        on_toggle: M,
    },
    Meter {
        fraction: f32,
        /// Where a limit sits along it, like a battery's charge limit.
        limit: Option<f32>,
        tone: Option<Tone>,
    },
    TextInput {
        placeholder: String,
        value: String,
        on_input: Box<dyn Fn(String) -> M>,
        on_submit: Option<M>,
        secret: bool,
        trailing: Option<Box<Node<M>>>,
        tone: Option<Tone>,
    },
    Display(Box<Node<M>>),
    Mark(Box<Node<M>>),
    Badge {
        text: String,
        tone: Option<Tone>,
    },
    /// Pages and their names. The host shows one at a time and owns which.
    Tabs(Vec<(String, Node<M>)>),
    Markdown {
        text: String,
        tone: Option<Tone>,
    },
    TextArea {
        placeholder: String,
        value: String,
        on_input: Box<dyn Fn(String) -> M>,
        on_submit: Option<M>,
        trailing: Option<Box<Node<M>>>,
    },
    Scroll {
        content: Box<Node<M>>,
        /// Keeps the end in view as content arrives there, like a chat.
        bottom: bool,
    },
}

pub fn label<M>(text: impl Into<String>) -> Node<M> {
    Node(Kind::Label {
        text: text.into(),
        tone: None,
    })
}

/// A title, larger than a label. Meant for popovers.
pub fn heading<M>(text: impl Into<String>) -> Node<M> {
    Node(Kind::Heading {
        text: text.into(),
        tone: None,
    })
}

/// A symbol, sized like a label.
pub fn icon<M>(icon: Icon) -> Node<M> {
    Node(Kind::Icon { icon, tone: None })
}

/// An application's icon, found by its app id or window class (`firefox`, `org.gnome.Nautilus`)
/// in the user's icon theme. Sized like an [`icon`], in the app's own colors: a tone only dims it.
/// Until the host has found it, or if there is none, it shows the id's first letter.
pub fn app_icon<M>(app_id: impl Into<String>) -> Node<M> {
    Node(Kind::AppIcon {
        app_id: app_id.into(),
        tone: None,
    })
}

/// An icon the plugin ships: an SVG or PNG file compiled into it with `include_bytes!`, told
/// apart by its first bytes. Sized like an [`icon`], in the file's own colors: a tone only dims
/// it, as with [`app_icon`]. The host draws it once, off the UI thread, and shows nothing in its
/// place until then.
pub fn image<M>(file: &'static [u8]) -> Node<M> {
    Node(Kind::Image {
        file,
        tint: false,
        tone: None,
    })
}

/// Like [`image`], but only the file's shape counts: it's drawn in the text's tone, like an
/// [`icon`]. For a monochrome symbol the vocabulary doesn't have.
pub fn symbol<M>(file: &'static [u8]) -> Node<M> {
    Node(Kind::Image {
        file,
        tint: true,
        tone: None,
    })
}

/// A little animation the plugin ships, like a pixel-art mascot: `frames` are PNG or SVG files
/// compiled in with `include_bytes!`, all the same size, and `order` lists which frame shows when,
/// by index into `frames`. The host keeps the frames' shape and picks the height (a little under
/// a label's in the bar, taller in a popover), scaling pixels up whole, never blurred: ship pixel
/// art at its own size. The host shows a frame for a quarter of a second. It plays the loop a
/// couple of times when it shows up or changes, then rests on the first frame of `order`;
/// [`Node::looping`] keeps it going. A tone only dims it.
pub fn sprite<M>(frames: &'static [&'static [u8]], order: &'static [u8]) -> Node<M> {
    Node(Kind::Sprite {
        frames,
        order,
        looping: false,
        tone: None,
    })
}

/// A picture a program hands over at runtime, by URL: a track's cover art. `file://` and
/// `https://` URLs load; the host fetches, crops it square and rounds it, off the UI thread, and
/// keeps the few latest. Drawn at icon size, or big with [`Node::large`]. Until it's there, or if
/// it can't be loaded, `fallback` shows in its place. A tone only dims it.
pub fn cover<M>(url: impl Into<String>, fallback: Node<M>) -> Node<M> {
    Node(Kind::Cover {
        url: url.into(),
        fallback: Box::new(fallback),
        large: false,
        tone: None,
    })
}

/// A number from `range`, with a unit after it (`"%"`, `"°"`, or `""`), shown like a label. It
/// keeps room for the widest number in `range`, so it doesn't change width as it changes. When
/// `value` changes, the host counts to it through every number in between.
pub fn counter<M>(value: i64, range: RangeInclusive<i64>, unit: impl Into<String>) -> Node<M> {
    Node(Kind::Counter {
        value,
        range,
        unit: unit.into(),
        tone: None,
    })
}

/// One of `options` at a time: the one at `current`, or the last one if it's past the end. It's as
/// big as the biggest option, so it doesn't change size when `current` does. The host fades from
/// one to the other. Keep the options the same from one
/// view to the next, so the host can tell which one is coming in.
pub fn alternate<M>(options: impl IntoIterator<Item = Node<M>>, current: usize) -> Node<M> {
    Node(Kind::Alternate {
        options: options.into_iter().collect(),
        current,
        hovered: None,
        grows: false,
    })
}

/// `normal`, or `hovered` while the pointer is over the item, fading between them like an
/// [`alternate`]: an icon that shows its percent, a time that shows the date.
pub fn hover<M>(normal: Node<M>, hovered: Node<M>) -> Node<M> {
    alternate([normal, hovered], 0).on_hover(1)
}

/// `collapsed`, or `expanded` once the pointer rests on this node, fading between them like a
/// [`hover`]. Unlike `hover`, it's only as big as what it shows, so the item grows to make room
/// and the island springs along, and it reacts to the pointer over it, not the whole item: a
/// workspace that shows every window when you point at it.
pub fn expand<M>(collapsed: Node<M>, expanded: Node<M>) -> Node<M> {
    Node(Kind::Alternate {
        options: vec![collapsed, expanded],
        current: 0,
        hovered: Some(1),
        grows: true,
    })
}

/// Children side by side, vertically centered.
pub fn row<M>(children: impl IntoIterator<Item = Node<M>>) -> Node<M> {
    Node(Kind::Row(children.into_iter().collect()))
}

/// Children stacked top to bottom.
pub fn column<M>(children: impl IntoIterator<Item = Node<M>>) -> Node<M> {
    Node(Kind::Column(children.into_iter().collect()))
}

/// `content` centered across the panel's width: a cover, a title, a row of controls. Text in it
/// stays on one line, cut and faded at the edges of its room if it's too long. In the bar, it's
/// just `content`.
pub fn center<M>(content: Node<M>) -> Node<M> {
    Node(Kind::Center(Box::new(content)))
}

/// Cells laid out left to right in rows of `columns`, all the same width. A calendar, a keypad.
pub fn grid<M>(columns: usize, cells: impl IntoIterator<Item = Node<M>>) -> Node<M> {
    Node(Kind::Grid {
        columns: columns.max(1),
        cells: cells.into_iter().collect(),
    })
}

pub fn button<M>(content: Node<M>, on_press: M) -> Node<M> {
    Node(Kind::Button {
        content: Box::new(content),
        on_press,
        on_secondary: None,
        prominent: false,
    })
}

/// A row of choices, one of them current: workspaces, output devices. Each option sends its
/// message when clicked. The host marks the current option and moves the mark smoothly when
/// `current` changes.
pub fn switcher<M>(
    options: impl IntoIterator<Item = (Node<M>, M)>,
    current: Option<usize>,
) -> Node<M> {
    Node(Kind::Switcher {
        options: options.into_iter().collect(),
        current,
    })
}

/// Keeps gulping, like a bottle being poured: the host swells `content` gently and steadily for as
/// long as it's on screen. For something filling up, like a charging battery's percent.
pub fn gulp<M>(content: Node<M>) -> Node<M> {
    Node(Kind::Gulp(Box::new(content)))
}

/// A thin horizontal line between groups.
pub fn separator<M>() -> Node<M> {
    Node(Kind::Separator)
}

/// Takes up a grid cell, or nothing elsewhere.
pub fn empty<M>() -> Node<M> {
    Node(Kind::Empty)
}

/// A row in a popover list: a network, a device, a window. Give it a [`subtitle`](Node::subtitle),
/// a [`leading`](Node::leading) icon, a [`trailing`](Node::trailing) node at the far end (a lock,
/// an info button), mark the one in use with [`selected`](Node::selected), and make it clickable
/// with [`on_press`](Node::on_press). A long title fades out at the end rather than wrapping.
pub fn list_item<M>(title: impl Into<String>) -> Node<M> {
    Node(Kind::ListItem {
        title: title.into(),
        subtitle: None,
        leading: None,
        trailing: None,
        selected: false,
        on_press: None,
        on_secondary: None,
    })
}

/// Rows stacked closely, usually [`list_item`]s. In a popover, a long list scrolls instead of
/// growing past a few rows.
pub fn list<M>(rows: impl IntoIterator<Item = Node<M>>) -> Node<M> {
    Node(Kind::List(rows.into_iter().collect()))
}

/// A small caption over a group in a popover ("Output", "Health"), with an optional
/// [`trailing`](Node::trailing) node at the far end.
pub fn section<M>(title: impl Into<String>) -> Node<M> {
    Node(Kind::Section {
        title: title.into(),
        trailing: None,
    })
}

/// The title of a popover page. Sub-pages get a back button with [`on_back`](Node::on_back); a
/// [`trailing`](Node::trailing) node sits at the far end (a switch, a count).
pub fn header<M>(title: impl Into<String>) -> Node<M> {
    Node(Kind::Header {
        title: title.into(),
        on_back: None,
        trailing: None,
    })
}

/// A named value on one line: the name dimmed at the start, the value at the end.
pub fn detail<M>(name: impl Into<String>, value: Node<M>) -> Node<M> {
    Node(Kind::Detail {
        name: name.into(),
        value: Box::new(value),
    })
}

/// Takes the free space in a popover row, pushing what follows to the end. Nothing in the bar.
pub fn fill<M>() -> Node<M> {
    Node(Kind::Fill)
}

/// A value dragged along `range`: a volume. Sends `on_change` while dragging; add
/// [`on_release`](Node::on_release) to act once it's let go, and [`step`](Node::step) to snap.
pub fn slider<M: 'static>(
    value: f32,
    range: RangeInclusive<f32>,
    on_change: impl Fn(f32) -> M + 'static,
) -> Node<M> {
    Node(Kind::Slider {
        value,
        range,
        step: 1.0,
        on_change: Box::new(on_change),
        on_release: None,
    })
}

/// An on/off switch. Sends `on_toggle` when clicked; the host slides it over.
pub fn toggle<M>(on: bool, on_toggle: M) -> Node<M> {
    Node(Kind::Toggle { on, on_toggle })
}

/// A bar filled to `fraction` (0.0 to 1.0), in its tone: a charge, a signal. The host eases it to
/// a new value.
pub fn meter<M>(fraction: f32) -> Node<M> {
    Node(Kind::Meter {
        fraction,
        limit: None,
        tone: None,
    })
}

/// A field to type into, showing `value`. Sends `on_input` with the new text on every change.
/// It takes the focus when it appears, and while it has it, keys stay in the popover; Esc still
/// closes it. [`on_submit`](Node::on_submit) is sent on Enter. One per popover page. A
/// [`Tone::Critical`] tone marks it as wrong.
pub fn text_input<M: 'static>(
    placeholder: impl Into<String>,
    value: impl Into<String>,
    on_input: impl Fn(String) -> M + 'static,
) -> Node<M> {
    Node(Kind::TextInput {
        placeholder: placeholder.into(),
        value: value.into(),
        on_input: Box::new(on_input),
        on_submit: None,
        secret: false,
        trailing: None,
        tone: None,
    })
}

/// A field to type several lines into, showing `value`: a message. It grows with its text up
/// to a few lines, then scrolls. Sends `on_input` with the new text on every change, and
/// [`on_submit`](Node::on_submit) on Enter; Shift+Enter starts a new line. In a popover it takes
/// the focus when it appears, like a [`text_input`]. One per popover page.
pub fn text_area<M: 'static>(
    placeholder: impl Into<String>,
    value: impl Into<String>,
    on_input: impl Fn(String) -> M + 'static,
) -> Node<M> {
    Node(Kind::TextArea {
        placeholder: placeholder.into(),
        value: value.into(),
        on_input: Box::new(on_input),
        on_submit: None,
        trailing: None,
    })
}

/// Text written in Markdown, as people and programs write messages: paragraphs, emphasis,
/// `code`, lists, quotes, headings, code blocks and tables. The host sets it in its own type and
/// colors, wrapped to the width it has. Links show as links but don't open: the bar starts no
/// programs.
pub fn markdown<M>(text: impl Into<String>) -> Node<M> {
    Node(Kind::Markdown {
        text: text.into(),
        tone: None,
    })
}

/// Its content, scrolling in a popover once it's taller than the host allows a page to grow: a
/// conversation, a long document. With [`Node::bottom`] it keeps its end in view. In the bar it's
/// just its content.
pub fn scroll<M>(content: Node<M>) -> Node<M> {
    Node(Kind::Scroll {
        content: Box::new(content),
        bottom: false,
    })
}

/// Its text, large: the one number a popover is about, like a battery's charge.
pub fn display<M>(content: Node<M>) -> Node<M> {
    Node(Kind::Display(Box::new(content)))
}

/// Its content marked with a ring: today in a calendar.
pub fn mark<M>(content: Node<M>) -> Node<M> {
    Node(Kind::Mark(Box::new(content)))
}

/// A short code in a small outlined box: a keyboard layout's `US`.
pub fn badge<M>(text: impl Into<String>) -> Node<M> {
    Node(Kind::Badge {
        text: text.into(),
        tone: None,
    })
}

/// Pages behind a row of tabs, one page showing at a time: a popover's Output, Input and Apps.
/// The host draws the tabs, switches pages when one is clicked and starts on the first each time
/// the popover opens, so the plugin keeps no state for it. In the bar, only the first page shows.
pub fn tabs<M>(pages: impl IntoIterator<Item = (impl Into<String>, Node<M>)>) -> Node<M> {
    Node(Kind::Tabs(
        pages
            .into_iter()
            .map(|(name, page)| (name.into(), page))
            .collect(),
    ))
}

impl<M> Node<M> {
    /// Sets the tone of this text, or of every text inside this node that has none yet.
    pub fn tone(mut self, tone: Tone) -> Self {
        self.set_tone(tone);
        self
    }

    /// For an [`alternate`]: shows the option at `index` while the pointer is over the item,
    /// whatever `current` is. Other nodes have nothing to show on hover and ignore it.
    pub fn on_hover(mut self, index: usize) -> Self {
        if let Kind::Alternate { hovered, .. } = &mut self.0 {
            *hovered = Some(index);
        }
        self
    }

    /// For a [`button`] or [`list_item`]: sent on a secondary (right) click on it. Other nodes
    /// ignore it.
    pub fn on_secondary(mut self, message: M) -> Self {
        if let Kind::Button { on_secondary, .. } | Kind::ListItem { on_secondary, .. } = &mut self.0
        {
            *on_secondary = Some(message);
        }
        self
    }

    /// For a [`button`]: the main action of its page, filled so it stands out. Other nodes ignore
    /// it.
    pub fn prominent(mut self) -> Self {
        if let Kind::Button { prominent, .. } = &mut self.0 {
            *prominent = true;
        }
        self
    }

    /// For a [`list_item`]: sent on a click on it. Other nodes ignore it.
    pub fn on_press(mut self, message: M) -> Self {
        if let Kind::ListItem { on_press, .. } = &mut self.0 {
            *on_press = Some(message);
        }
        self
    }

    /// For a [`list_item`]: a second, dimmer line under the title. Other nodes ignore it.
    pub fn subtitle(mut self, text: impl Into<String>) -> Self {
        if let Kind::ListItem { subtitle, .. } = &mut self.0 {
            *subtitle = Some(text.into());
        }
        self
    }

    /// For a [`list_item`]: an icon before the title. Other nodes ignore it.
    pub fn leading(mut self, node: Node<M>) -> Self {
        if let Kind::ListItem { leading, .. } = &mut self.0 {
            *leading = Some(Box::new(node));
        }
        self
    }

    /// For a [`list_item`], [`section`], [`header`], [`text_input`] or [`text_area`]: a node at the
    /// far end, like a lock or an info button. Other nodes ignore it.
    pub fn trailing(mut self, node: Node<M>) -> Self {
        if let Kind::ListItem { trailing, .. }
        | Kind::Section { trailing, .. }
        | Kind::Header { trailing, .. }
        | Kind::TextInput { trailing, .. }
        | Kind::TextArea { trailing, .. } = &mut self.0
        {
            *trailing = Some(Box::new(node));
        }
        self
    }

    /// For a [`list_item`]: marks it as the one in use. Other nodes ignore it.
    pub fn selected(mut self, yes: bool) -> Self {
        if let Kind::ListItem { selected, .. } = &mut self.0 {
            *selected = yes;
        }
        self
    }

    /// For a [`header`]: shows a back button that sends `message`. Other nodes ignore it.
    pub fn on_back(mut self, message: M) -> Self {
        if let Kind::Header { on_back, .. } = &mut self.0 {
            *on_back = Some(message);
        }
        self
    }

    /// For a [`slider`]: the step its value snaps to (1 by default). Other nodes ignore it.
    pub fn step(mut self, by: f32) -> Self {
        if let Kind::Slider { step, .. } = &mut self.0 {
            *step = by;
        }
        self
    }

    /// For a [`slider`]: sent when it's let go. Other nodes ignore it.
    pub fn on_release(mut self, message: M) -> Self {
        if let Kind::Slider { on_release, .. } = &mut self.0 {
            *on_release = Some(message);
        }
        self
    }

    /// For a [`text_input`] or [`text_area`]: sent on Enter. Other nodes ignore it.
    pub fn on_submit(mut self, message: M) -> Self {
        if let Kind::TextInput { on_submit, .. } | Kind::TextArea { on_submit, .. } = &mut self.0 {
            *on_submit = Some(message);
        }
        self
    }

    /// For a [`text_input`]: hides what's typed, like a password. Other nodes ignore it.
    pub fn secret(mut self, yes: bool) -> Self {
        if let Kind::TextInput { secret, .. } = &mut self.0 {
            *secret = yes;
        }
        self
    }

    /// For a [`sprite`]: plays for as long as it shows, not only when it shows up or changes.
    /// Every frame redraws the bar, so keep it for what wants your eye, or for popovers. Other
    /// nodes ignore it.
    pub fn looping(mut self) -> Self {
        if let Kind::Sprite { looping, .. } = &mut self.0 {
            *looping = true;
        }
        self
    }

    /// For a [`cover`]: drawn big, as the main picture of a popover, not as an icon. Other nodes
    /// ignore it.
    pub fn large(mut self) -> Self {
        if let Kind::Cover { large, .. } = &mut self.0 {
            *large = true;
        }
        self
    }

    /// For a [`scroll`]: keeps its end in view as content arrives there, unless you've scrolled
    /// up to read. Other nodes ignore it.
    pub fn bottom(mut self) -> Self {
        if let Kind::Scroll { bottom, .. } = &mut self.0 {
            *bottom = true;
        }
        self
    }

    /// For a [`meter`]: marks a limit along it (0.0 to 1.0). Other nodes ignore it.
    pub fn limit(mut self, at: f32) -> Self {
        if let Kind::Meter { limit, .. } = &mut self.0 {
            *limit = Some(at);
        }
        self
    }

    fn set_tone(&mut self, new: Tone) {
        match &mut self.0 {
            Kind::Label { tone, .. }
            | Kind::Heading { tone, .. }
            | Kind::Icon { tone, .. }
            | Kind::AppIcon { tone, .. }
            | Kind::Image { tone, .. }
            | Kind::Sprite { tone, .. }
            | Kind::Counter { tone, .. }
            | Kind::Meter { tone, .. }
            | Kind::TextInput { tone, .. }
            | Kind::Markdown { tone, .. }
            | Kind::Badge { tone, .. } => {
                tone.get_or_insert(new);
            }
            Kind::Cover { tone, fallback, .. } => {
                tone.get_or_insert(new);
                fallback.set_tone(new);
            }
            Kind::Alternate {
                options: children, ..
            }
            | Kind::Row(children)
            | Kind::Column(children)
            | Kind::Grid {
                cells: children, ..
            }
            | Kind::List(children) => {
                children.iter_mut().for_each(|child| child.set_tone(new));
            }
            Kind::Button { content, .. }
            | Kind::Gulp(content)
            | Kind::Center(content)
            | Kind::Display(content)
            | Kind::Mark(content)
            | Kind::Scroll { content, .. }
            | Kind::Detail { value: content, .. } => content.set_tone(new),
            Kind::ListItem {
                leading, trailing, ..
            } => {
                leading
                    .iter_mut()
                    .chain(trailing.iter_mut())
                    .for_each(|child| child.set_tone(new));
            }
            Kind::Tabs(pages) => {
                for (_, page) in pages {
                    page.set_tone(new);
                }
            }
            Kind::Switcher { options, .. } => {
                options
                    .iter_mut()
                    .for_each(|(child, _)| child.set_tone(new));
            }
            Kind::Separator
            | Kind::Empty
            | Kind::Section { .. }
            | Kind::Header { .. }
            | Kind::Fill
            | Kind::Slider { .. }
            | Kind::TextArea { .. }
            | Kind::Toggle { .. } => {}
        }
    }

    /// Converts every message in this node. Sliders and text fields keep `f` to convert the
    /// messages they make later, so it must be `Clone + 'static`, like a function or a closure
    /// that captures nothing.
    pub fn map<N: 'static>(self, f: &(impl Fn(M) -> N + Clone + 'static)) -> Node<N>
    where
        M: 'static,
    {
        let map_all = |nodes: Vec<Node<M>>| nodes.into_iter().map(|node| node.map(f)).collect();
        let map_box = |node: Option<Box<Node<M>>>| node.map(|node| Box::new(node.map(f)));

        Node(match self.0 {
            Kind::Label { text, tone } => Kind::Label { text, tone },
            Kind::Heading { text, tone } => Kind::Heading { text, tone },
            Kind::Icon { icon, tone } => Kind::Icon { icon, tone },
            Kind::AppIcon { app_id, tone } => Kind::AppIcon { app_id, tone },
            Kind::Image { file, tint, tone } => Kind::Image { file, tint, tone },
            Kind::Sprite {
                frames,
                order,
                looping,
                tone,
            } => Kind::Sprite {
                frames,
                order,
                looping,
                tone,
            },
            Kind::Cover {
                url,
                fallback,
                large,
                tone,
            } => Kind::Cover {
                url,
                fallback: Box::new(fallback.map(f)),
                large,
                tone,
            },
            Kind::Counter {
                value,
                range,
                unit,
                tone,
            } => Kind::Counter {
                value,
                range,
                unit,
                tone,
            },
            Kind::Alternate {
                options,
                current,
                hovered,
                grows,
            } => Kind::Alternate {
                options: map_all(options),
                current,
                hovered,
                grows,
            },
            Kind::Row(children) => Kind::Row(map_all(children)),
            Kind::Column(children) => Kind::Column(map_all(children)),
            Kind::Grid { columns, cells } => Kind::Grid {
                columns,
                cells: map_all(cells),
            },
            Kind::Button {
                content,
                on_press,
                on_secondary,
                prominent,
            } => Kind::Button {
                content: Box::new(content.map(f)),
                on_press: f(on_press),
                on_secondary: on_secondary.map(f),
                prominent,
            },
            Kind::Switcher { options, current } => Kind::Switcher {
                options: options
                    .into_iter()
                    .map(|(node, message)| (node.map(f), f(message)))
                    .collect(),
                current,
            },
            Kind::Gulp(content) => Kind::Gulp(Box::new(content.map(f))),
            Kind::Center(content) => Kind::Center(Box::new(content.map(f))),
            Kind::Separator => Kind::Separator,
            Kind::Empty => Kind::Empty,
            Kind::ListItem {
                title,
                subtitle,
                leading,
                trailing,
                selected,
                on_press,
                on_secondary,
            } => Kind::ListItem {
                title,
                subtitle,
                leading: map_box(leading),
                trailing: map_box(trailing),
                selected,
                on_press: on_press.map(f),
                on_secondary: on_secondary.map(f),
            },
            Kind::List(rows) => Kind::List(map_all(rows)),
            Kind::Section { title, trailing } => Kind::Section {
                title,
                trailing: map_box(trailing),
            },
            Kind::Header {
                title,
                on_back,
                trailing,
            } => Kind::Header {
                title,
                on_back: on_back.map(f),
                trailing: map_box(trailing),
            },
            Kind::Detail { name, value } => Kind::Detail {
                name,
                value: Box::new(value.map(f)),
            },
            Kind::Fill => Kind::Fill,
            Kind::Slider {
                value,
                range,
                step,
                on_change,
                on_release,
            } => {
                let g = f.clone();
                Kind::Slider {
                    value,
                    range,
                    step,
                    on_change: Box::new(move |value| g(on_change(value))),
                    on_release: on_release.map(f),
                }
            }
            Kind::Toggle { on, on_toggle } => Kind::Toggle {
                on,
                on_toggle: f(on_toggle),
            },
            Kind::Meter {
                fraction,
                limit,
                tone,
            } => Kind::Meter {
                fraction,
                limit,
                tone,
            },
            Kind::TextInput {
                placeholder,
                value,
                on_input,
                on_submit,
                secret,
                trailing,
                tone,
            } => {
                let g = f.clone();
                Kind::TextInput {
                    placeholder,
                    value,
                    on_input: Box::new(move |text| g(on_input(text))),
                    on_submit: on_submit.map(f),
                    secret,
                    trailing: map_box(trailing),
                    tone,
                }
            }
            Kind::Display(content) => Kind::Display(Box::new(content.map(f))),
            Kind::Mark(content) => Kind::Mark(Box::new(content.map(f))),
            Kind::Badge { text, tone } => Kind::Badge { text, tone },
            Kind::Tabs(pages) => Kind::Tabs(
                pages
                    .into_iter()
                    .map(|(name, page)| (name, page.map(f)))
                    .collect(),
            ),
            Kind::Markdown { text, tone } => Kind::Markdown { text, tone },
            Kind::TextArea {
                placeholder,
                value,
                on_input,
                on_submit,
                trailing,
            } => {
                let g = f.clone();
                Kind::TextArea {
                    placeholder,
                    value,
                    on_input: Box::new(move |text| g(on_input(text))),
                    on_submit: on_submit.map(f),
                    trailing: map_box(trailing),
                }
            }
            Kind::Scroll { content, bottom } => Kind::Scroll {
                content: Box::new(content.map(f)),
                bottom,
            },
        })
    }

    #[doc(hidden)]
    pub fn into_kind(self) -> Kind<M> {
        self.0
    }

    #[doc(hidden)]
    pub fn kind(&self) -> &Kind<M> {
        &self.0
    }
}

/// What a widget shows in the bar.
pub struct Item<M> {
    content: Option<Node<M>>,
    on_press: Option<M>,
    on_secondary: Option<M>,
    on_scroll: Option<(M, M)>,
}

impl<M> Item<M> {
    pub fn new(content: Node<M>) -> Self {
        Self {
            content: Some(content),
            on_press: None,
            on_secondary: None,
            on_scroll: None,
        }
    }

    /// Takes no space in the bar. For widgets with nothing to show, like a battery on a desktop.
    pub fn hidden() -> Self {
        Self {
            content: None,
            on_press: None,
            on_secondary: None,
            on_scroll: None,
        }
    }

    /// Sent on a primary click. Replaces the default of toggling the popover.
    pub fn on_press(mut self, message: M) -> Self {
        self.on_press = Some(message);
        self
    }

    /// Sent on a secondary (right) click.
    pub fn on_secondary(mut self, message: M) -> Self {
        self.on_secondary = Some(message);
        self
    }

    /// Sent once per scroll step over the item, `up` or `down`. The host turns smooth touchpad
    /// scrolling into steps.
    pub fn on_scroll(mut self, up: M, down: M) -> Self {
        self.on_scroll = Some((up, down));
        self
    }

    pub fn map<N: 'static>(self, f: &(impl Fn(M) -> N + Clone + 'static)) -> Item<N>
    where
        M: 'static,
    {
        Item {
            content: self.content.map(|content| content.map(f)),
            on_press: self.on_press.map(f),
            on_secondary: self.on_secondary.map(f),
            on_scroll: self.on_scroll.map(|(up, down)| (f(up), f(down))),
        }
    }

    #[doc(hidden)]
    pub fn into_parts(self) -> ItemParts<M> {
        ItemParts {
            content: self.content,
            on_press: self.on_press,
            on_secondary: self.on_secondary,
            on_scroll: self.on_scroll,
        }
    }
}

#[doc(hidden)]
pub struct ItemParts<M> {
    pub content: Option<Node<M>>,
    pub on_press: Option<M>,
    pub on_secondary: Option<M>,
    /// Up, then down.
    pub on_scroll: Option<(M, M)>,
}

/// The contents of a popover. The host draws the surface, its background and its edges, and lays
/// every popover out at the same width, or at a wider one if it asks ([`Panel::wide`]).
pub struct Panel<M> {
    content: Node<M>,
    on_open: Option<M>,
    on_close: Option<M>,
    wide: bool,
}

impl<M> Panel<M> {
    pub fn new(content: Node<M>) -> Self {
        Self {
            content,
            on_open: None,
            on_close: None,
            wide: false,
        }
    }

    /// Laid out wider than other popovers, for a page that's mostly reading: a conversation, a
    /// document. The host decides how wide.
    pub fn wide(mut self) -> Self {
        self.wide = true;
        self
    }

    #[doc(hidden)]
    pub fn is_wide(&self) -> bool {
        self.wide
    }

    /// Sent each time the popover opens: start a scan, show the first page.
    pub fn on_open(mut self, message: M) -> Self {
        self.on_open = Some(message);
        self
    }

    /// Sent each time the popover starts closing: stop listening, forget what was typed.
    pub fn on_close(mut self, message: M) -> Self {
        self.on_close = Some(message);
        self
    }

    pub fn map<N: 'static>(self, f: &(impl Fn(M) -> N + Clone + 'static)) -> Panel<N>
    where
        M: 'static,
    {
        Panel {
            content: self.content.map(f),
            on_open: self.on_open.map(f),
            on_close: self.on_close.map(f),
            wide: self.wide,
        }
    }

    #[doc(hidden)]
    pub fn into_node(self) -> Node<M> {
        self.content
    }

    #[doc(hidden)]
    pub fn on_open_message(self) -> Option<M> {
        self.on_open
    }

    #[doc(hidden)]
    pub fn on_close_message(self) -> Option<M> {
        self.on_close
    }
}

/// How much a [`Notice`] matters. The host decides what that looks like.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Urgency {
    /// Background news: a download finished.
    Low,
    #[default]
    Normal,
    /// Needs attention now: a battery about to die.
    Critical,
}

/// A notification to show on screen, from [`Widget::notices`](crate::Widget::notices).
///
/// It says what the notification is, not how it looks: the host lays out the notification, places it and
/// animates it in and out. Its `key` is how the host tells notices apart from one view to the
/// next: a notice that keeps its key and changes its text is updated in place, and one whose key
/// is gone from the list leaves the screen.
pub struct Notice<M> {
    key: u64,
    summary: String,
    app: Option<String>,
    app_icon: Option<String>,
    image: Option<String>,
    body: Option<String>,
    markdown: bool,
    urgency: Urgency,
    actions: Vec<(String, M)>,
    on_press: Option<M>,
    on_dismiss: Option<M>,
    expires: Option<(std::time::Duration, M)>,
    reply: Option<Reply<M>>,
}

/// A field on a [`Notice`] to type an answer into, like a reply to a message: several lines,
/// Enter sends and Shift+Enter starts a new line.
///
/// It shows with the notice, but the host takes the keyboard only once it's clicked, and gives it
/// back on Esc, on sending, or on a click elsewhere. The notice doesn't expire while it has the
/// keyboard.
pub struct Reply<M> {
    placeholder: String,
    value: String,
    on_input: std::rc::Rc<dyn Fn(String) -> M>,
    on_submit: Option<M>,
    on_cancel: Option<M>,
}

impl<M> Reply<M> {
    /// Shows `value`, and sends `on_input` with the new text on every change.
    pub fn new(
        placeholder: impl Into<String>,
        value: impl Into<String>,
        on_input: impl Fn(String) -> M + 'static,
    ) -> Self {
        Self {
            placeholder: placeholder.into(),
            value: value.into(),
            on_input: std::rc::Rc::new(on_input),
            on_submit: None,
            on_cancel: None,
        }
    }

    /// Sent on Enter, or a click on the field's send button.
    pub fn on_submit(mut self, message: M) -> Self {
        self.on_submit = Some(message);
        self
    }

    /// Sent on Esc.
    pub fn on_cancel(mut self, message: M) -> Self {
        self.on_cancel = Some(message);
        self
    }

    pub fn map<N: 'static>(self, f: &(impl Fn(M) -> N + Clone + 'static)) -> Reply<N>
    where
        M: 'static,
    {
        let g = f.clone();
        let on_input = self.on_input;
        Reply {
            placeholder: self.placeholder,
            value: self.value,
            on_input: std::rc::Rc::new(move |text| g(on_input(text))),
            on_submit: self.on_submit.map(f),
            on_cancel: self.on_cancel.map(f),
        }
    }

    #[doc(hidden)]
    pub fn into_parts(self) -> ReplyParts<M> {
        ReplyParts {
            placeholder: self.placeholder,
            value: self.value,
            on_input: self.on_input,
            on_submit: self.on_submit,
            on_cancel: self.on_cancel,
        }
    }
}

#[doc(hidden)]
#[derive(Clone)]
pub struct ReplyParts<M> {
    pub placeholder: String,
    pub value: String,
    pub on_input: std::rc::Rc<dyn Fn(String) -> M>,
    pub on_submit: Option<M>,
    pub on_cancel: Option<M>,
}

impl<M> Notice<M> {
    pub fn new(key: u64, summary: impl Into<String>) -> Self {
        Self {
            key,
            summary: summary.into(),
            app: None,
            app_icon: None,
            image: None,
            body: None,
            markdown: false,
            urgency: Urgency::Normal,
            actions: Vec::new(),
            on_press: None,
            on_dismiss: None,
            expires: None,
            reply: None,
        }
    }

    /// The name of the app it comes from.
    pub fn app(mut self, name: impl Into<String>) -> Self {
        self.app = Some(name.into());
        self
    }

    /// The app's icon, by app id, like [`app_icon`].
    pub fn app_icon(mut self, app_id: impl Into<String>) -> Self {
        self.app_icon = Some(app_id.into());
        self
    }

    /// A picture to show instead of the app's icon, by URL, like a [`cover`]: an icon file the
    /// app gave as a path.
    pub fn image(mut self, url: impl Into<String>) -> Self {
        self.image = Some(url.into());
        self
    }

    /// Plain text under the summary. The host wraps it and cuts it off after a few lines.
    pub fn body(mut self, text: impl Into<String>) -> Self {
        self.body = Some(text.into());
        self
    }

    /// The body is Markdown, like a [`markdown`] node.
    pub fn markdown(mut self) -> Self {
        self.markdown = true;
        self
    }

    pub fn urgency(mut self, urgency: Urgency) -> Self {
        self.urgency = urgency;
        self
    }

    /// A button on the notification that sends `message`. The first one is the main action.
    pub fn action(mut self, label: impl Into<String>, message: M) -> Self {
        self.actions.push((label.into(), message));
        self
    }

    /// Sent on a click on the notification itself, outside its buttons.
    pub fn on_press(mut self, message: M) -> Self {
        self.on_press = Some(message);
        self
    }

    /// Sent when its close button is clicked. Without it, it has none.
    pub fn on_dismiss(mut self, message: M) -> Self {
        self.on_dismiss = Some(message);
        self
    }

    /// Sent once it has been on screen for `after`. The host doesn't count while the pointer is
    /// on it or it's waiting to be shown. Without it, it stays
    /// until it leaves the list.
    pub fn expires(mut self, after: std::time::Duration, message: M) -> Self {
        self.expires = Some((after, message));
        self
    }

    /// A field to type an answer into ([`Reply`]).
    pub fn reply(mut self, reply: Reply<M>) -> Self {
        self.reply = Some(reply);
        self
    }

    pub fn map<N: 'static>(self, f: &(impl Fn(M) -> N + Clone + 'static)) -> Notice<N>
    where
        M: 'static,
    {
        Notice {
            key: self.key,
            summary: self.summary,
            app: self.app,
            app_icon: self.app_icon,
            image: self.image,
            body: self.body,
            markdown: self.markdown,
            urgency: self.urgency,
            actions: self
                .actions
                .into_iter()
                .map(|(label, message)| (label, f(message)))
                .collect(),
            on_press: self.on_press.map(f),
            on_dismiss: self.on_dismiss.map(f),
            expires: self.expires.map(|(after, message)| (after, f(message))),
            reply: self.reply.map(|reply| reply.map(f)),
        }
    }

    pub fn key(&self) -> u64 {
        self.key
    }

    #[doc(hidden)]
    pub fn into_parts(self) -> NoticeParts<M> {
        NoticeParts {
            key: self.key,
            summary: self.summary,
            app: self.app,
            app_icon: self.app_icon,
            image: self.image,
            body: self.body,
            markdown: self.markdown,
            urgency: self.urgency,
            actions: self.actions,
            on_press: self.on_press,
            on_dismiss: self.on_dismiss,
            expires: self.expires,
            reply: self.reply.map(Reply::into_parts),
        }
    }
}

#[doc(hidden)]
#[derive(Clone)]
pub struct NoticeParts<M> {
    pub key: u64,
    pub summary: String,
    pub app: Option<String>,
    pub app_icon: Option<String>,
    pub image: Option<String>,
    pub body: Option<String>,
    pub markdown: bool,
    pub urgency: Urgency,
    pub actions: Vec<(String, M)>,
    pub on_press: Option<M>,
    pub on_dismiss: Option<M>,
    pub expires: Option<(std::time::Duration, M)>,
    pub reply: Option<ReplyParts<M>>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn map_converts_every_message() {
        let node = row([
            button(label("a"), 1).on_secondary(4),
            column([button(label("b"), 2), label("c")]),
            switcher([(label("d"), 3)], Some(0)),
        ]);

        let Kind::Row(children) = node.map(&|n: i32| n * 10).into_kind() else {
            panic!("row became something else");
        };
        let mut messages = Vec::new();
        collect(children, &mut messages);
        assert_eq!(messages, [10, 40, 20, 30]);
    }

    fn collect(nodes: Vec<Node<i32>>, out: &mut Vec<i32>) {
        for node in nodes {
            match node.into_kind() {
                Kind::Button {
                    on_press,
                    on_secondary,
                    ..
                } => {
                    out.push(on_press);
                    out.extend(on_secondary);
                }
                Kind::Switcher { options, .. } => {
                    out.extend(options.into_iter().map(|(_, message)| message))
                }
                Kind::Row(children) | Kind::Column(children) => collect(children, out),
                _ => {}
            }
        }
    }

    #[test]
    fn hover_shows_the_second_option() {
        let node: Node<()> = hover(label("a"), label("b"));
        assert!(matches!(
            node.into_kind(),
            Kind::Alternate {
                current: 0,
                hovered: Some(1),
                ..
            }
        ));
        let node: Node<()> = label("a").on_hover(1);
        assert!(matches!(node.into_kind(), Kind::Label { .. }));
    }

    #[test]
    fn tone_fills_only_unset_text() {
        let node: Node<()> =
            row([label("a").tone(Tone::Accent), label("b"), icon(Icon::Wired)]).tone(Tone::Dim);
        let Kind::Row(children) = node.into_kind() else {
            unreachable!()
        };
        let tones: Vec<_> = children
            .into_iter()
            .map(|child| match child.into_kind() {
                Kind::Label { tone, .. } | Kind::Icon { tone, .. } => tone,
                _ => None,
            })
            .collect();
        assert_eq!(
            tones,
            [Some(Tone::Accent), Some(Tone::Dim), Some(Tone::Dim)]
        );
    }

    #[test]
    fn map_reaches_new_nodes_and_their_closures() {
        let node = column([
            header("h").on_back(1).trailing(toggle(true, 2)),
            list([list_item("a")
                .on_press(3)
                .on_secondary(4)
                .trailing(button(icon(Icon::Info), 5))]),
            slider(0.5, 0.0..=1.0, |v| (v * 10.0) as i32).on_release(6),
            text_input("p", "v", |text: String| text.len() as i32).on_submit(7),
            scroll(text_area("p", "v", |text: String| text.len() as i32 + 1).on_submit(8)).bottom(),
        ]);
        let Kind::Column(children) = node.map(&|n: i32| n * 10).into_kind() else {
            panic!("column became something else");
        };
        let mut children = children.into_iter().map(Node::into_kind);
        let Some(Kind::Header {
            on_back: Some(10),
            trailing: Some(trailing),
            ..
        }) = children.next()
        else {
            panic!("header lost its back message");
        };
        assert!(matches!(
            trailing.into_kind(),
            Kind::Toggle { on_toggle: 20, .. }
        ));
        let Some(Kind::List(rows)) = children.next() else {
            panic!("list lost");
        };
        let Some(Kind::ListItem {
            on_press: Some(30),
            on_secondary: Some(40),
            trailing: Some(trailing),
            ..
        }) = rows.into_iter().next().map(Node::into_kind)
        else {
            panic!("list item lost its messages");
        };
        assert!(matches!(
            trailing.into_kind(),
            Kind::Button { on_press: 50, .. }
        ));
        let Some(Kind::Slider {
            on_change,
            on_release: Some(60),
            ..
        }) = children.next()
        else {
            panic!("slider lost");
        };
        assert_eq!(on_change(0.3), 30);
        let Some(Kind::TextInput {
            on_input,
            on_submit: Some(70),
            ..
        }) = children.next()
        else {
            panic!("text input lost");
        };
        assert_eq!(on_input("abcd".into()), 40);
        let Some(Kind::Scroll {
            content,
            bottom: true,
        }) = children.next()
        else {
            panic!("scroll lost");
        };
        let Kind::TextArea {
            on_input,
            on_submit: Some(80),
            ..
        } = content.into_kind()
        else {
            panic!("text area lost");
        };
        assert_eq!(on_input("abcd".into()), 50);
    }

    #[test]
    fn tabs_map_and_tone_every_page() {
        let node = tabs([("a", button(label("x"), 1)), ("b", button(label("y"), 2))])
            .tone(Tone::Dim)
            .map(&|n: i32| n * 10);
        let Kind::Tabs(pages) = node.into_kind() else {
            panic!("tabs became something else");
        };
        let names: Vec<_> = pages.iter().map(|(name, _)| name.as_str()).collect();
        assert_eq!(names, ["a", "b"]);
        let mut messages = Vec::new();
        for (_, page) in pages {
            let Kind::Button {
                content, on_press, ..
            } = page.into_kind()
            else {
                panic!("page lost its button");
            };
            assert!(matches!(
                content.into_kind(),
                Kind::Label {
                    tone: Some(Tone::Dim),
                    ..
                }
            ));
            messages.push(on_press);
        }
        assert_eq!(messages, [10, 20]);
    }

    #[test]
    fn notice_map_reaches_every_message() {
        let notice = Notice::new(7, "s")
            .action("a", 1)
            .action("b", 2)
            .on_press(3)
            .on_dismiss(4)
            .expires(std::time::Duration::from_secs(5), 5)
            .reply(
                Reply::new("p", "v", |text: String| text.len() as i32)
                    .on_submit(6)
                    .on_cancel(7),
            )
            .map(&|n: i32| n * 10);
        assert_eq!(notice.key(), 7);
        let parts = notice.into_parts();
        let actions: Vec<_> = parts.actions.into_iter().map(|(_, m)| m).collect();
        assert_eq!(actions, [10, 20]);
        assert_eq!(parts.on_press, Some(30));
        assert_eq!(parts.on_dismiss, Some(40));
        assert_eq!(parts.expires.map(|(_, m)| m), Some(50));
        let reply = parts.reply.unwrap();
        assert_eq!((reply.on_input)("abc".into()), 30);
        assert_eq!((reply.on_submit, reply.on_cancel), (Some(60), Some(70)));
    }

    #[test]
    fn modifiers_only_touch_their_nodes() {
        let node: Node<i32> = label("a").trailing(label("b")).on_press(1).selected(true);
        assert!(matches!(node.into_kind(), Kind::Label { .. }));
        let node: Node<i32> = button(label("a"), 1).on_press(2).prominent();
        assert!(matches!(
            node.into_kind(),
            Kind::Button {
                on_press: 1,
                prominent: true,
                ..
            }
        ));
    }

    #[test]
    fn tone_reaches_details_and_row_icons() {
        let node: Node<()> = column([
            detail("n", label("v")),
            list_item("t").leading(icon(Icon::Lock)),
        ])
        .tone(Tone::Good);
        let Kind::Column(children) = node.into_kind() else {
            unreachable!()
        };
        let mut children = children.into_iter().map(Node::into_kind);
        let Some(Kind::Detail { value, .. }) = children.next() else {
            unreachable!()
        };
        assert!(matches!(
            value.into_kind(),
            Kind::Label {
                tone: Some(Tone::Good),
                ..
            }
        ));
        let Some(Kind::ListItem {
            leading: Some(leading),
            ..
        }) = children.next()
        else {
            unreachable!()
        };
        assert!(matches!(
            leading.into_kind(),
            Kind::Icon {
                tone: Some(Tone::Good),
                ..
            }
        ));
    }
}