mitsuami-core 2.4.0

Node tree, layout, styles, units, a11y model and backend contract for mitsuami
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
//! What the core tells backends to create, and the properties they carry.

use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;

use crate::any_value::Opaque;
use crate::custom::CustomProps;
use crate::draw::{Color, DisplayList};
use crate::geometry::{Point, Rect, Size};
use crate::services::{MenuEntry, Shortcut};

/// Stable identity of a node for the lifetime of a [`Ui`](crate::Ui).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId(pub(crate) u32);

impl NodeId {
    pub fn raw(self) -> u32 {
        self.0
    }

    /// For backends and tools that need to rebuild ids, e.g. when replaying a
    /// command log.
    pub fn from_raw(raw: u32) -> NodeId {
        NodeId(raw)
    }
}

impl fmt::Display for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "#{}", self.0)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WidgetKind {
    Window,
    /// A layout host: a plain native view that we position children in.
    Container,
    /// A host for one item of its window's toolbar, the bar across the top
    /// that shows the window's title (the unified NSToolbar, GTK's header
    /// bar, a CommandBar on WinUI, Kirigami's page toolbar). A native child
    /// of the window, after its content. The core lays out what's in it at
    /// its natural size; the platform places it, at the bar's trailing end.
    ToolbarItem,
    /// A window's sidebar: the list down its leading side that picks what
    /// the window shows (a source list in an NSSplitViewController, a
    /// libadwaita navigation split view, NavigationView's pane on WinUI, a
    /// first column in Kirigami's page row). A native child of the window,
    /// after its content and toolbar items. Its items are data
    /// ([`Prop::Sections`]), the chosen one [`Prop::SelectedIndex`]; the
    /// platform draws, places and sizes it, and the window's content is
    /// what's beside it.
    Sidebar,
    /// Core-only grouping used by control flow (`Show`, `For`). Never sent to
    /// backends; its children are spliced into the nearest native ancestor.
    Fragment,
    Text,
    Button,
    /// A native button that stays pressed until it's clicked again (an
    /// `NSButton` of the push-on-push-off type, gtk::ToggleButton,
    /// ToggleButton, a checkable QQC2.Button). A `Button`'s caption, icon
    /// and style, and a `Checkbox`'s [`Prop::Checked`], reported as
    /// `Changed(Bool)`.
    ToggleButton,
    /// A native button that opens a menu of actions (a pull-down
    /// NSPopUpButton, gtk::MenuButton, DropDownButton, a QQC2.Button that
    /// opens a QQC2.Menu). Its caption, icon and style are a `Button`'s;
    /// its menu is [`Prop::Menu`], and the item chosen comes as
    /// [`UiEvent::MenuItem`](crate::UiEvent::MenuItem).
    MenuButton,
    /// A native button with a menu of other actions beside its own (an
    /// `NSComboButton` of the split style, WinUI's SplitButton,
    /// adw::SplitButton; Kirigami has none, so a QQC2.Button with an arrow
    /// QQC2.Button joined to it, as KDE apps pair them). Its caption, icon
    /// and style are a `Button`'s, and it reports a click as one does; its
    /// menu is [`Prop::Menu`], whose item chosen comes as
    /// [`UiEvent::MenuItem`](crate::UiEvent::MenuItem).
    SplitButton,
    TextInput,
    /// A native password field (NSSecureTextField, PasswordBox,
    /// gtk::PasswordEntry, Kirigami.PasswordField): a `TextInput` whose
    /// text is hidden, as each platform hides it.
    PasswordInput,
    /// A native search field (NSSearchField, gtk::SearchEntry, an
    /// AutoSuggestBox with the find icon, Kirigami.SearchField): a
    /// `TextInput` with the platform's search icon and clear button, which
    /// asks for a search ([`UiEvent::Search`](crate::UiEvent::Search)) as
    /// the platform does.
    SearchInput,
    /// A native field for text over many lines (an NSTextView in an
    /// NSScrollView, a TextBox that accepts Return, a gtk::TextView in a
    /// gtk::ScrolledWindow, a QQC2.TextArea in a QQC2.ScrollView). Its
    /// lines wrap, Return starts a new one, and it scrolls past
    /// [`Prop::Lines`], its natural height.
    TextArea,
    Checkbox,
    Switch,
    /// A native pop-up menu of text options (NSPopUpButton, ComboBox,
    /// gtk::DropDown, QQC2.ComboBox). Its options are [`Prop::Options`].
    Select,
    /// Native radio buttons, one for each of [`Prop::Options`], of which
    /// one at most is chosen, [`Prop::SelectedIndex`] (NSButtons of the
    /// radio type, RadioButtons, gtk::CheckButtons in a group,
    /// QQC2.RadioButtons). Down a column, as each platform stacks them.
    RadioGroup,
    /// A native slider (NSSlider, Slider, gtk::Scale, QQC2.Slider): a
    /// [`Prop::Number`] in a [`Prop::Range`], in [`Prop::Step`]s.
    Slider,
    /// A native field for a whole number, with buttons that step it up and
    /// down (NumberBox, gtk::SpinButton, QQC2.SpinBox; on AppKit an
    /// NSTextField with an NSStepper beside it, as AppKit apps pair them):
    /// a [`Prop::Number`] in a [`Prop::Range`], stepped by [`Prop::Step`].
    /// Whole numbers that fit an `i32`, because Qt's spin box holds an
    /// `int`.
    NumberInput,
    /// A native colour well: a button showing a colour, which opens the
    /// platform's own way to pick another (NSColorWell, its colour panel;
    /// GTK's ColorDialogButton; WinUI's ColorPicker in a flyout under a
    /// DropDownButton; on Qt a button opening the ColorDialog, as KDE apps
    /// pair them). Its colour is [`Prop::ColorValue`], opaque; the user's
    /// pick comes as `Changed(Color)`.
    ColorWell,
    /// A native progress bar (NSProgressIndicator, ProgressBar,
    /// gtk::ProgressBar, QQC2.ProgressBar): a [`Prop::Progress`].
    Progress,
    /// A native spinner for work of unknown length (a spinning
    /// NSProgressIndicator, gtk::Spinner, ProgressRing,
    /// QQC2.BusyIndicator). It spins while [`Prop::Running`], and shows
    /// nothing otherwise.
    Spinner,
    /// A native separator line between groups of content (a separator
    /// NSBox, gtk::Separator, Kirigami.Separator; WinUI has none, so a
    /// `Border` in the divider brush, as Fluent apps draw one). It runs as
    /// [`Prop::Orientation`] says and is as thick as the platform draws
    /// it; the layout gives it its length.
    Separator,
    /// A native image view (NSImageView, Image, gtk::Picture, QML Image):
    /// a picture from [`Prop::Image`], at its own size unless the layout
    /// sizes it, fitted as [`Prop::ImageFit`] says.
    Image,
    /// An icon from the platform's own set, by its name there: an SF
    /// Symbol in an NSImageView, a themed icon in a gtk::Image or a
    /// Kirigami.Icon, a Segoe Fluent Icons glyph in a FontIcon on WinUI.
    /// [`Prop::Icon`] names it, at the platform's own size unless
    /// [`Prop::IconSize`] says otherwise.
    Icon,
    /// A file's or folder's own icon, as the platform's file manager shows
    /// it: `NSWorkspace`'s in an NSImageView, GIO's in a gtk::Image, its
    /// MIME type's in a Kirigami.Icon, the shell's in a XAML Image.
    /// [`Prop::File`] names it; it's a square as big as the platform's
    /// small icons unless [`Prop::IconSize`] says otherwise. With
    /// [`Prop::Thumbnail`], a preview of what's in the file where the
    /// platform makes one; with [`Prop::FileLookup`], a type's icon from
    /// the name alone.
    FileIcon,
    /// A native surface the app presents to with its own GPU API, off the
    /// UI thread (an `NSView` backed by a `CAMetalLayer`, a Wayland
    /// subsurface, a child window). The backend reports it as
    /// `SurfaceReady`, then its size in pixels as `SurfaceResized`; with
    /// [`Prop::TakesInput`], its keys and pointer as `SurfaceInput`, and
    /// with [`Prop::TextInput`] what its keys type.
    GpuSurface,
    /// A native scroll container. It has exactly one native child, the
    /// content, which the core lays out and may be larger than the viewport.
    ScrollView,
    /// A native list control (NSTableView, ListView, gtk::ListView, QML
    /// ListView). Its data is [`Prop::Rows`]. The platform decides which rows
    /// exist (`RowShown`, `RowHidden`); its native children are the hosts of
    /// the rows the core mounted for those (`Container`s with a
    /// [`Prop::Row`]), in row order. It scrolls like a `ScrollView`.
    List,
    /// A native table: a `List` whose rows are cells under column headers
    /// (NSTableView with columns and a header, gtk::ColumnView, a QML
    /// TableView under a HorizontalHeaderView; WinUI has none, so a
    /// ListView under a header of column buttons, as Fluent apps build
    /// one). Its columns are [`Prop::Columns`], sorted as [`Prop::Sort`]
    /// says. Its data, selection and scrolling are a `List`'s; its native
    /// children are the hosts of the cells the core mounted for the rows it
    /// shows (`Container`s with a [`Prop::Cell`]), in row order, then
    /// column order. The platform sizes its columns, and the user resizes
    /// them: it reports the width each column gives its cells
    /// (`ColumnWidths`).
    Table,
    /// A native tree: a `List` whose rows nest, opened and closed by a
    /// disclosure the platform draws (NSOutlineView, a gtk::ListView over a
    /// gtk::TreeListModel with gtk::TreeExpanders, a QML TreeView, WinUI's
    /// TreeView). Its data is [`Prop::TreeRows`], the rows that show; its
    /// selection, scrolling and native children are a `List`'s. The user
    /// opens and closes rows (`RowExpanded`), and the platform says how
    /// far it indents their content (`TreeIndent`).
    Tree,
    /// A native tab view: pages, one shown at a time, and a strip of their
    /// titles to pick one (NSTabView, libadwaita's inline view switcher or
    /// a gtk::Notebook, a SelectorBar over its pages on WinUI, Kirigami's
    /// NavigationTabBar or a QQC2.TabBar). Its native
    /// children are its pages' hosts (`Container`s), in order, titled by
    /// [`Prop::TabTitles`]; the shown one is [`Prop::SelectedIndex`].
    /// Every page stays mounted. The core lays out each page at the size
    /// inside the tab strip and border ([`PlatformMetrics::tab_insets`](crate::PlatformMetrics)),
    /// all in the same place, so the view is as big as its biggest page;
    /// the platform places them and shows the chosen one.
    Tabs,
    /// Native document tabs: a strip of tabs with no pages, for documents
    /// the app shows in one place of its own (a terminal's sessions drawn
    /// on one surface). WinUI's TabView with items without content,
    /// libadwaita's AdwTabBar, a QQC2.TabBar with close buttons, and on
    /// AppKit a strip of the backend's, made as the system's tab bar. Titled by [`Prop::TabTitles`], the chosen
    /// one [`Prop::SelectedIndex`]; the user closes them
    /// ([`Prop::TabsClosable`]), moves them ([`Prop::TabsReorderable`]) and
    /// asks for a new one ([`Prop::NewTabButton`]), where the app lets
    /// them. Measured by the backend; empty where the tabs are the
    /// window's ([`DocumentTabsStyle::Window`], [`DocumentTabsStyle::TitleRow`]).
    DocumentTabs,
    /// A native box around related content, under an optional heading
    /// ([`Prop::Title`]): an NSBox, libadwaita's card under a heading, a
    /// Fluent card under a heading on WinUI, a QQC2.GroupBox. The core lays
    /// out its children as a container's, inside
    /// [`PlatformMetrics::group_insets`](crate::PlatformMetrics) (or the
    /// titled ones), and it's at least as wide as its heading, which
    /// backends measure. Backends draw the box behind the children, which
    /// are its native children.
    Group,
    /// Two panes with a divider between them that the user drags: side by
    /// side, or with `Orientation::Vertical` one over the other. Its two
    /// children are the panes. The core lays them out: the first as long
    /// along the split as its `Number`, then the platform's divider
    /// ([`PlatformMetrics::split_divider`](crate::PlatformMetrics)), then
    /// the second, which takes what's left, so the first keeps its size as
    /// the split grows. Each pane is at least its style's least size
    /// ([`Prop::PaneMinimums`]). The platform draws the divider and reports
    /// where the user drags it as `Changed(Number)`. A hidden pane
    /// collapses, with the divider, and the other takes the whole split
    /// ([`Prop::PanesShown`]); the position is kept for when it's back.
    Split,
    /// A platform's popover, attached to its parent (a container) while
    /// [`Prop::PopoverShown`]: an NSPopover, a gtk::Popover, a XAML Flyout,
    /// a QQC2.Popup. It's out of its parent's layout: the core lays out its
    /// children at their natural size, as a toolbar item's, and the
    /// platform places it by its parent, where it fits. A click outside or
    /// Escape dismisses it, as the platform's do: the backend reports
    /// `PopoverShownChanged(false)`, which the core absorbs.
    Popover,
    /// A custom widget (see [`CustomWidget`](crate::CustomWidget)), named
    /// after it. Its props travel as [`Prop::Custom`].
    Custom(&'static str),
    /// A raw native view supplied by app code. Its factory and updates
    /// travel as [`Prop::Native`].
    Native,
}

impl WidgetKind {
    pub fn is_native(self) -> bool {
        self != WidgetKind::Fragment
    }

    /// Containers lay out children; everything else is measured by the backend.
    pub fn is_container(self) -> bool {
        matches!(
            self,
            WidgetKind::Window
                | WidgetKind::Container
                | WidgetKind::ToolbarItem
                | WidgetKind::ScrollView
                | WidgetKind::Tabs
                | WidgetKind::Group
                | WidgetKind::Split
                | WidgetKind::Popover
        )
    }

    /// Scrolls its content: `ScrollTo` and `Scrolled` apply.
    pub fn scrolls(self) -> bool {
        matches!(self, WidgetKind::ScrollView | WidgetKind::List | WidgetKind::Table | WidgetKind::Tree)
    }

    /// Has rows the platform realises: a `List`, a `Table` or a `Tree`.
    pub fn has_rows(self) -> bool {
        matches!(self, WidgetKind::List | WidgetKind::Table | WidgetKind::Tree)
    }

    pub fn name(self) -> &'static str {
        match self {
            WidgetKind::Window => "Window",
            WidgetKind::Container => "Container",
            WidgetKind::ToolbarItem => "ToolbarItem",
            WidgetKind::Sidebar => "Sidebar",
            WidgetKind::ScrollView => "ScrollView",
            WidgetKind::List => "List",
            WidgetKind::Table => "Table",
            WidgetKind::Tree => "Tree",
            WidgetKind::Tabs => "Tabs",
            WidgetKind::DocumentTabs => "DocumentTabs",
            WidgetKind::Group => "Group",
            WidgetKind::Popover => "Popover",
            WidgetKind::Split => "Split",
            WidgetKind::Fragment => "Fragment",
            WidgetKind::Text => "Text",
            WidgetKind::Button => "Button",
            WidgetKind::ToggleButton => "ToggleButton",
            WidgetKind::MenuButton => "MenuButton",
            WidgetKind::SplitButton => "SplitButton",
            WidgetKind::TextInput => "TextInput",
            WidgetKind::PasswordInput => "PasswordInput",
            WidgetKind::SearchInput => "SearchInput",
            WidgetKind::TextArea => "TextArea",
            WidgetKind::Checkbox => "Checkbox",
            WidgetKind::Switch => "Switch",
            WidgetKind::Select => "Select",
            WidgetKind::RadioGroup => "RadioGroup",
            WidgetKind::Slider => "Slider",
            WidgetKind::NumberInput => "NumberInput",
            WidgetKind::ColorWell => "ColorWell",
            WidgetKind::Progress => "Progress",
            WidgetKind::Spinner => "Spinner",
            WidgetKind::Separator => "Separator",
            WidgetKind::Image => "Image",
            WidgetKind::Icon => "Icon",
            WidgetKind::FileIcon => "FileIcon",
            WidgetKind::GpuSurface => "GpuSurface",
            WidgetKind::Custom(name) => name,
            WidgetKind::Native => "Native",
        }
    }
}

/// Semantic text styles, mapped to each platform's type ramp.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextStyle {
    LargeTitle,
    Title,
    Headline,
    #[default]
    Body,
    Callout,
    Caption,
    Monospace,
}

/// How heavy a `Text`'s font is, in place of its text style's weight.
/// A platform whose font lacks one uses the nearest it has.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FontWeight {
    #[default]
    Regular,
    Medium,
    Semibold,
    Bold,
}

/// Where a `Text`'s lines go across its frame, in its reading direction:
/// `Start` is the left in left-to-right text, the right in right-to-left.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextAlign {
    #[default]
    Start,
    Center,
    End,
}

/// Where a `Text` cut off at its line limit puts its ellipsis: in place
/// of its start, its middle (a path's folders, keeping its file name) or
/// its end. Start and end are the text's, so in right-to-left text the
/// start is on the right. Platforms that can't put one there cut off the
/// end, as their labels do.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Truncation {
    Start,
    Middle,
    #[default]
    End,
}

/// Where a `FileIcon` gets its icon. From disk, the platform reads the
/// file or folder for its own icon; by name, nothing is read, as file
/// managers show files that aren't on disk (a download, an archive's
/// contents, a file only in an old revision).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FileLookup {
    /// The file or folder at the path: an app's own icon, a folder's
    /// custom one, a document's by its type.
    #[default]
    Disk,
    /// A file of the type the path's name says (its extension, or the
    /// whole name where the platform knows one, `Makefile`).
    FileName,
    /// A plain folder.
    Folder,
}

/// A [`TextAlign`] the core has resolved against the text's direction, as
/// backends get it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum HorizontalAlign {
    #[default]
    Left,
    Center,
    Right,
}

/// Which way a native widget lays itself out, as backends get it: the
/// core has resolved the node's direction (its own, its parent's, or the
/// app's language's).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LayoutDirection {
    #[default]
    LeftToRight,
    RightToLeft,
}

/// What a `TextInput` is for, which the platform uses as it uses one: to
/// pick an on-screen keyboard, to offer autofill, to check what's typed.
/// Only the purposes every platform has.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum InputPurpose {
    /// Any text.
    #[default]
    Text,
    Email,
    Url,
    /// A telephone number.
    Phone,
}

/// What a button does in its window or dialog, which each platform shows
/// and handles its own way. Platforms without an equivalent ignore it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ButtonRole {
    /// An ordinary button.
    #[default]
    Normal,
    /// The action Return confirms: the default button on AppKit (Return
    /// clicks it), the suggested action on GTK, the default button on Qt, the
    /// accent button on WinUI. One per window or dialog.
    Default,
    /// The action Escape takes: the cancel button on AppKit (Escape clicks
    /// it). The others show it as a normal button.
    Cancel,
    /// An action that destroys data: GTK's destructive action; AppKit marks
    /// it so the system can warn. Qt and WinUI have no such style.
    Destructive,
}

/// Where a window's header (`Prop::Header`) meets what scrolls under it,
/// where the platform blurs it there (AppKit's scroll edge effect, macOS
/// 26.1 and later). The others have no such edge, and ignore it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum HeaderEdge {
    /// The platform's own: soft on macOS 26.
    #[default]
    Automatic,
    /// What scrolls under it fades into the blur.
    Soft,
    /// The header ends at a hard line, opaque down to it, as Finder's and
    /// Mail's bars on a busy list.
    Hard,
}

/// How a `Tabs` shows its tabs, where the platform has more than one way
/// (GNOME and KDE). The others show theirs, and ignore it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TabsStyle {
    /// The platform's own: navigation tabs on GNOME and KDE.
    #[default]
    Automatic,
    /// A tab bar over the pages: GTK's `gtk::Notebook`, Qt's
    /// `QQC2.TabBar`.
    TabBar,
    /// Navigation tabs above the pages: libadwaita's inline view switcher
    /// (a tab bar before libadwaita 1.7), Kirigami's `NavigationTabBar`.
    Navigation,
}

/// Where `DocumentTabs` show their tabs: in the window's own chrome, or
/// in the content where they're declared.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum DocumentTabsStyle {
    /// The platform's own: the window's on macOS and Windows (in the title
    /// bar, as Safari, Xcode and Terminal have them), a strip in the
    /// content on GNOME and KDE (as Console and Konsole).
    #[default]
    Automatic,
    /// A strip in the content, where they're declared, on every platform:
    /// on macOS one the backend builds, as Safari's is.
    Strip,
    /// The window's own: a strip in AppKit's title bar, under the title and
    /// toolbar, WinUI's tab view in the title bar. GTK and Qt have none,
    /// so a strip.
    Window,
    /// In the title's own row, beside the window's buttons and toolbar
    /// items, the title hidden: Safari's compact tabs on macOS, and on
    /// GNOME libadwaita's tab bar in the header bar's title's place.
    /// WinUI's tabs in the title bar already are; Qt has none, so a strip.
    TitleRow,
}

/// How a button is drawn, mapped to each platform's native look.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ButtonStyle {
    /// The same as `Bordered`, on every platform.
    #[default]
    Automatic,
    /// The platform's push button, with its bezel or frame.
    Bordered,
    /// No bezel or frame until hovered, where the platform does that: for
    /// toolbars, and buttons that sit among text.
    Borderless,
    /// Filled with the accent colour, as the platform marks the action it
    /// suggests among others (AppKit's primary tint prominence, GTK's
    /// `suggested-action`, WinUI's accent style), without being the
    /// window's default button: Return doesn't press it. Buttons and menu
    /// and split buttons; on others, `Bordered`. Breeze has no such style
    /// (only its default button is tinted), nor AppKit's combo button, so
    /// those stay bordered.
    Prominent,
}

/// A suggestion of a `SearchInput`: what it says, and a second line in the
/// secondary style (a file's folder, an author's email).
#[derive(Clone, Debug, PartialEq)]
pub struct Suggestion {
    pub title: String,
    pub detail: Option<String>,
}

/// What an `Image` shows.
#[derive(Clone, Debug, PartialEq)]
pub enum ImageSource {
    /// An image file, decoded by the platform: PNG and JPEG everywhere,
    /// other formats where the platform reads them. It's read when the
    /// source is set; a file that changes under the same path isn't read
    /// again.
    File(PathBuf),
    /// Pixels the app has in memory.
    Pixels(Pixels),
}

/// An image in memory: rows of straight (not premultiplied) RGBA8, top
/// row first, drawn at `scale` pixels to a point, so an image made at the
/// window's scale factor is shown pixel for pixel.
#[derive(Clone, PartialEq)]
pub struct Pixels {
    width: u32,
    height: u32,
    scale: f32,
    rgba: Arc<[u8]>,
}

/// Its size and scale, not its bytes.
impl fmt::Debug for Pixels {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Pixels({}×{} @{}x)", self.width, self.height, self.scale)
    }
}

impl Pixels {
    /// Panics unless `rgba` holds `width × height` pixels.
    pub fn new(width: u32, height: u32, rgba: impl Into<Arc<[u8]>>) -> Pixels {
        let rgba = rgba.into();
        // Checked: a size that wraps could pass with too few bytes, which
        // backends hand to the platform as the whole image.
        let len = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(4));
        assert_eq!(Some(rgba.len()), len, "{width}×{height} RGBA8 pixels");
        Pixels { width, height, scale: 1.0, rgba }
    }

    /// Pixels to a point; 1 by default.
    pub fn scale(mut self, scale: f32) -> Pixels {
        assert!(scale > 0.0, "a scale above 0");
        self.scale = scale;
        self
    }

    pub fn width(&self) -> u32 {
        self.width
    }

    pub fn height(&self) -> u32 {
        self.height
    }

    pub fn scale_factor(&self) -> f32 {
        self.scale
    }

    pub fn rgba(&self) -> &[u8] {
        &self.rgba
    }

    /// Its size in points.
    pub fn size(&self) -> crate::Size {
        crate::Size::new(self.width as f32 / self.scale, self.height as f32 / self.scale)
    }
}

/// How an `Image` fills a frame the layout makes a different size from
/// it. Only the fits every platform's image view has; without one, each
/// fits as it does by default.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageFit {
    /// As large as fits, keeping its proportions (NSImageView
    /// proportionally up or down, GTK `Contain`, Qt `PreserveAspectFit`,
    /// XAML `Uniform`).
    Contain,
    /// The whole frame, proportions or not (axes independently, `Fill`,
    /// `Stretch`, `Fill`).
    Stretch,
}

/// The pointer's cursor over a `GpuSurface`, while it isn't locked.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Cursor {
    /// The platform's own: the arrow.
    #[default]
    Default,
    /// None: the pointer still moves, unseen (a machine that draws its own).
    Hidden,
    /// An image of the app's, e.g. the one a machine gives its pointer,
    /// shown at its scale. `hotspot`: the point that points, in points from
    /// its top left.
    Image { pixels: Pixels, hotspot: Point },
    /// One of the platform's own, by what it means. A platform with none
    /// for it shows its arrow.
    System(SystemCursor),
}

/// The platform cursors a `Cursor::System` names: the ones the platforms
/// share, as CSS names them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SystemCursor {
    /// The text cursor, an I-beam.
    Text,
    /// Busy: nothing can be done (the hourglass, the spinner).
    Wait,
    /// Busy, but it can still be used (the arrow with a spinner).
    Progress,
    /// A link: the pointing hand.
    Pointer,
    Crosshair,
    NotAllowed,
    Help,
    /// Something can be moved: arrows four ways.
    Move,
    /// Resizing up and down, left and right, and along the diagonals.
    ResizeNorthSouth,
    ResizeEastWest,
    ResizeNorthWestSouthEast,
    ResizeNorthEastSouthWest,
}

impl SystemCursor {
    /// Its CSS name (`cursor:`), which GTK and freedesktop cursor themes
    /// use too.
    pub fn css_name(self) -> &'static str {
        match self {
            SystemCursor::Text => "text",
            SystemCursor::Wait => "wait",
            SystemCursor::Progress => "progress",
            SystemCursor::Pointer => "pointer",
            SystemCursor::Crosshair => "crosshair",
            SystemCursor::NotAllowed => "not-allowed",
            SystemCursor::Help => "help",
            SystemCursor::Move => "move",
            SystemCursor::ResizeNorthSouth => "ns-resize",
            SystemCursor::ResizeEastWest => "ew-resize",
            SystemCursor::ResizeNorthWestSouthEast => "nwse-resize",
            SystemCursor::ResizeNorthEastSouthWest => "nesw-resize",
        }
    }
}

/// What a modal `Window` blocks while it's open, shown each platform's way.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Modality {
    /// The window it belongs to (the one it's declared in): a sheet on
    /// that window on macOS, Qt's `WindowModal`, an owned `IsModal` window
    /// on WinUI. GTK's modal windows block the whole app.
    Window,
    /// Every other window of the app: a window in AppKit's modal loop,
    /// Qt's `ApplicationModal`, a modal window on GTK, and on WinUI an
    /// owned `IsModal` window that also disables the app's other windows.
    Application,
}

/// The window whose content is being built: provided in each window's
/// scope, so views can find the window they're in (a modal `Window`
/// belongs to it, a `Toolbar`'s items go in its toolbar).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CurrentWindow(pub NodeId);

/// Which files a node takes when they're dropped on it: files with these
/// extensions (any file without a list), and folders if `folders`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct FileDrop {
    /// Without the dot, compared ignoring case. `None`: any file.
    pub extensions: Option<Vec<String>>,
    pub folders: bool,
}

impl FileDrop {
    /// Any file, no folders.
    pub fn files() -> FileDrop {
        FileDrop { extensions: None, folders: false }
    }

    /// Files with these extensions (`"iso"`, not `".iso"`), no folders.
    pub fn extensions<S: Into<String>>(extensions: impl IntoIterator<Item = S>) -> FileDrop {
        FileDrop { extensions: Some(extensions.into_iter().map(Into::into).collect()), folders: false }
    }

    /// Folders only.
    pub fn folders() -> FileDrop {
        FileDrop { extensions: Some(Vec::new()), folders: true }
    }

    /// Folders too.
    pub fn and_folders(mut self) -> FileDrop {
        self.folders = true;
        self
    }

    /// Whether it takes this file or folder, as it is on disk.
    pub fn accepts(&self, path: &std::path::Path) -> bool {
        if path.is_dir() {
            return self.folders;
        }
        match &self.extensions {
            None => true,
            Some(extensions) => path
                .extension()
                .and_then(|e| e.to_str())
                .is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e))),
        }
    }

    /// What it takes of these, in order.
    pub fn accepted(&self, paths: &[PathBuf]) -> Vec<PathBuf> {
        paths.iter().filter(|p| self.accepts(p)).cloned().collect()
    }
}

/// Which way a `Slider` or a `Separator` runs. Every platform has vertical
/// sliders; larger values are up on all of them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Orientation {
    #[default]
    Horizontal,
    Vertical,
}

impl Orientation {
    pub fn vertical(self) -> bool {
        self == Orientation::Vertical
    }
}

/// Scrolling directions of a `ScrollView`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ScrollAxes {
    #[default]
    Vertical,
    Horizontal,
    Both,
}

impl ScrollAxes {
    pub fn horizontal(self) -> bool {
        matches!(self, ScrollAxes::Horizontal | ScrollAxes::Both)
    }

    pub fn vertical(self) -> bool {
        matches!(self, ScrollAxes::Vertical | ScrollAxes::Both)
    }
}

/// Where rows dragged within a list can be dropped (`List::on_move`): onto
/// a row (into a group, say), between rows (to reorder them), or both. A
/// drop on the list's empty part is at its end, either way.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RowMoves {
    pub onto_rows: bool,
    pub between_rows: bool,
}

impl RowMoves {
    pub fn onto_rows() -> RowMoves {
        RowMoves { onto_rows: true, between_rows: false }
    }

    pub fn between_rows() -> RowMoves {
        RowMoves { onto_rows: false, between_rows: true }
    }

    pub fn and_between_rows(self) -> RowMoves {
        RowMoves { between_rows: true, ..self }
    }

    pub fn and_onto_rows(self) -> RowMoves {
        RowMoves { onto_rows: true, ..self }
    }

    /// Where a drop the platform proposes lands, by what the list takes:
    /// onto a row where only between rows is taken is before it, and
    /// between rows where only onto them is taken is onto the row there.
    /// Rows aren't dropped onto one of themselves: `None`. Every backend
    /// asks this while a drag is over its list, and shows what it answers.
    pub fn target(&self, dragged: &[RowKey], proposed: RowDrop<RowKey>) -> Option<RowDrop<RowKey>> {
        let target = match proposed {
            RowDrop::On(row) if !self.onto_rows => RowDrop::Before(row),
            RowDrop::Before(row) if !self.between_rows => RowDrop::On(row),
            other => other,
        };
        match target {
            RowDrop::On(row) if dragged.contains(&row) => None,
            _ if !self.onto_rows && !self.between_rows => None,
            target => Some(target),
        }
    }

    /// `target` in a `Tree`, whose rows nest (`row` gives a row's place, as
    /// `TreeRows` says): onto a row is into it, so only a row that opens
    /// takes rows onto it, and before one is at its place among its
    /// parent's rows. Nothing lands while the pointer is over a dragged row
    /// (`over`, the row under it), or anywhere inside one: the rows would
    /// stay where they are, or a folder would go inside itself.
    pub fn tree_target(
        &self,
        dragged: &[RowKey],
        over: Option<RowKey>,
        proposed: RowDrop<RowKey>,
        row: impl Fn(RowKey) -> Option<crate::TreeRow>,
    ) -> Option<RowDrop<RowKey>> {
        let inside_dragged = |key: RowKey| {
            let mut at = Some(key);
            while let Some(r) = at {
                if dragged.contains(&r) {
                    return true;
                }
                at = row(r).and_then(|r| r.parent);
            }
            false
        };
        if over.is_some_and(inside_dragged) {
            return None;
        }
        let target = self.target(dragged, proposed)?;
        match target {
            RowDrop::On(r) if !row(r).is_some_and(|r| r.expandable) => None,
            RowDrop::On(r) | RowDrop::Before(r) if inside_dragged(r) => None,
            target => Some(target),
        }
    }

    /// What the pointer, `x` across the tree (from its rows' left edge, if
    /// known) and `y` of `height` down the row `key`, proposes in a `Tree`
    /// (`row` gives a row's place, as `TreeRows` says). Over a row that
    /// opens, its top quarter is before it, its bottom quarter after it,
    /// and the middle onto it; over a row that doesn't, its top half is
    /// before it and its bottom half after it.
    ///
    /// After an open folder is before its first row. After another row,
    /// the levels from the row's own down to the next row's (`next`) are
    /// all places: at the next row's level, before it; at a deeper one, the
    /// end of the folder at that level (onto it, where a folder's last rows
    /// put rows). `x` picks the level, as outlines pick it: the level whose
    /// content starts nearest it, by `indent`; without it, the row's own.
    /// Past the last top row, at the top level, the end. Backends that
    /// propose by the pointer ask this, so every tree proposes alike, and
    /// show an end-of-folder drop as a line under the row, at the level.
    pub fn tree_proposal(
        key: RowKey,
        x: Option<f32>,
        y: f32,
        height: f32,
        indent: crate::TreeIndent,
        next: Option<RowKey>,
        row: impl Fn(RowKey) -> Option<crate::TreeRow>,
    ) -> RowDrop<RowKey> {
        let Some(me) = row(key) else { return RowDrop::End };
        let next_row = next.and_then(&row);
        let after = || {
            if let (Some(next), Some(n)) = (next, next_row)
                && n.parent == Some(key)
            {
                return RowDrop::Before(next);
            }
            let shallowest = next_row.map_or(0, |n| n.depth).min(me.depth);
            let level = match x {
                Some(x) if indent.per_level > 0.0 => {
                    let level = ((x - indent.start) / indent.per_level + 0.5).floor();
                    (level.max(0.0) as u32).clamp(shallowest, me.depth)
                }
                _ => me.depth,
            };
            if let (Some(next), Some(n)) = (next, next_row)
                && level == n.depth
            {
                return RowDrop::Before(next);
            }
            // The row's folder at that level: its own, or one it's in.
            let mut at = me;
            while at.depth > level {
                match at.parent.and_then(&row) {
                    Some(parent) => at = parent,
                    None => break,
                }
            }
            at.parent.map_or(RowDrop::End, RowDrop::On)
        };
        match me.expandable {
            true if y < height / 4.0 => RowDrop::Before(key),
            true if y > height * 3.0 / 4.0 => after(),
            true => RowDrop::On(key),
            false if y < height / 2.0 => RowDrop::Before(key),
            false => after(),
        }
    }
}

/// Where rows dragged within a list were dropped: onto a row, before one,
/// or at the end (the list's empty part).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RowDrop<K> {
    On(K),
    Before(K),
    End,
}

impl<K> RowDrop<K> {
    pub fn map<J>(self, f: impl FnOnce(K) -> J) -> RowDrop<J> {
        match self {
            RowDrop::On(k) => RowDrop::On(f(k)),
            RowDrop::Before(k) => RowDrop::Before(f(k)),
            RowDrop::End => RowDrop::End,
        }
    }
}

/// Identity of a row of a `List`, stable while its item's key stays in the
/// data. Assigned by the core.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RowKey(pub u64);

/// A row of a `Tree` that shows, as backends get it: its place in the
/// tree, and whether it opens.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TreeRow {
    pub row: RowKey,
    /// The row it's in, `None` at the top. It comes before this row, which
    /// it's open to show.
    pub parent: Option<RowKey>,
    /// 0 at the top, one more than its parent's.
    pub depth: u32,
    /// It opens, children or not (a folder, empty or not yet read): the
    /// platform shows its disclosure.
    pub expandable: bool,
    /// It's open: its children's rows, if it has any, follow it.
    pub expanded: bool,
}

/// How far a `Tree` indents its rows' content, as its platform draws it
/// (`TreeIndent`): a row's content is the rows' width less `start +
/// per_level × depth`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TreeIndent {
    /// Where a top row's content starts: the disclosure's room.
    pub start: f32,
    /// What each level adds.
    pub per_level: f32,
}

impl TreeIndent {
    /// How far the content of a row at `depth` starts.
    pub fn at(self, depth: u32) -> f32 {
        self.start + self.per_level * depth as f32
    }
}

/// A cell of a `Table`: its row, and its column's index.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CellKey {
    pub row: RowKey,
    pub column: usize,
}

/// A column of a `Table`, as backends get it.
#[derive(Clone, Debug, PartialEq)]
pub struct ColumnData {
    /// Its header's title.
    pub title: String,
    /// How wide it starts, in points; `None`: the platform's default. The
    /// user can resize it, as the platform lets them.
    pub width: Option<f32>,
    /// It takes the room the table has past its columns' widths, shared
    /// with the other columns that do, as the platform shares it.
    pub expand: bool,
    /// Its header sorts the table by it when pressed.
    pub sortable: bool,
    /// Its cells fill their row, without the platform's padding: as wide as
    /// the column and as high as the row (a commit graph whose lines join
    /// from row to row). Report its full width in `ColumnWidths`, and the
    /// row's height without it in `RowHeight`.
    pub fills_row: bool,
}

/// Which way a `Table` is sorted.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SortOrder {
    #[default]
    Ascending,
    Descending,
}

impl SortOrder {
    /// The other way round.
    pub fn reversed(self) -> SortOrder {
        match self {
            SortOrder::Ascending => SortOrder::Descending,
            SortOrder::Descending => SortOrder::Ascending,
        }
    }
}

/// The column a `Table` is sorted by, and which way, as its header shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ColumnSort {
    pub column: usize,
    pub order: SortOrder,
}

/// How many rows of a `List` can be selected.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SelectionMode {
    #[default]
    None,
    Single,
    Multiple,
}

/// How a `List` sits in its surroundings, mapped to each platform's native
/// look. Choosing per platform is up to the app, with `platform!`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ListStyle {
    /// The same as `Plain`, on every platform.
    #[default]
    Automatic,
    /// Edge to edge, on the surface around it: sidebars, a window's main
    /// content.
    Plain,
    /// In a bordered box, on the platform's content background: a list
    /// inside a form or a dialog.
    Framed,
}

impl ListStyle {
    pub fn framed(self) -> bool {
        self == ListStyle::Framed
    }
}

/// A group of a `Sidebar`'s items, under a heading if it has a title.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SidebarSectionData {
    pub title: Option<String>,
    pub items: Vec<SidebarItemData>,
}

/// One item of a `Sidebar`: its title, and the name of its icon in the
/// platform's own set (an SF Symbol, a symbolic theme icon, a Segoe
/// Fluent Icons glyph), which platforms without it ignore.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SidebarItemData {
    pub title: String,
    pub icon: Option<String>,
    /// A second line under the title, in the platform's secondary style.
    pub subtitle: Option<String>,
    /// Its context menu (empty: none). The platform shows it its own way,
    /// on the item, and reports the choice as the sidebar's
    /// `ContextMenuItem`; ids are unique across the sidebar's items.
    pub menu: Vec<crate::services::MenuEntry>,
}

/// A property of a native widget. Which ones apply depends on the kind.
#[derive(Clone, Debug, PartialEq)]
pub enum Prop {
    /// A window's title, or a `Group`'s heading (empty: none).
    Title(String),
    /// A window fills its screen, the platform's own way (a Space of its
    /// own on macOS). The user can change it too (the title bar's button,
    /// the window manager's key): the backend reports `FullScreenChanged`,
    /// which the core absorbs.
    FullScreen(bool),
    /// The smallest content size the user can make a window, in points.
    /// A window smaller when it's set grows to it.
    MinSize(Size),
    /// The content sets a window's height, not the user, who resizes only
    /// its width; where the platform can't hold one side (GTK), neither.
    /// The core sets it for a `WindowSize::FollowHeight` window.
    HeightFollowsContent(bool),
    /// A window fills its screen's working area as the platform's maximize
    /// (on macOS, zoom) does, and is back to its own size without. The user
    /// can change it too: the backend reports `MaximizedChanged`, which the
    /// core absorbs. Sent only if the app chose.
    Maximized(bool),
    /// The user can resize a window. Without, only the app sets its size;
    /// sent only if the app chose.
    Resizable(bool),
    /// Text content of a `Text`.
    Text(String),
    /// How many lines a `Text` shows at most, the last one cut off with an
    /// ellipsis, as the platform draws one. `None`: all of them.
    MaxLines(Option<u32>),
    /// Where a `Text` cut off at its line limit puts its ellipsis. AppKit,
    /// Qt and WinUI cut off a single line's start or middle only. Sent
    /// only if the app chose.
    Truncation(Truncation),
    /// A `Text`'s or `Icon`'s colour, or the icon's on a `Button` or
    /// `ToggleButton` (its caption keeps the platform's). Semantic colours
    /// follow the appearance (dark mode, high contrast, the accent colour);
    /// `Rgba` is fixed. Icons in full colour keep their own; symbolic ones
    /// take it. Sent only if the app chose.
    TextColor(Color),
    /// A `Text`'s weight, in place of its text style's.
    FontWeight(FontWeight),
    /// A `Text` in italics.
    Italic(bool),
    /// Where a `Text`'s lines go across its frame. The core resolves the
    /// app's `TextAlign` against the text's direction, so it's left or
    /// right here.
    TextAlign(HorizontalAlign),
    /// Which way a widget lays itself out and draws: a checkbox's box on
    /// the right of its caption, a slider's minimum on the right, a text
    /// field's text starting on the right. The core resolves it for every
    /// native node, and sends it to those that are right to left, and to
    /// every node of an app whose language is (never to an app that is
    /// only left to right). Frames are already mirrored: containers don't
    /// mirror what they hold.
    LayoutDirection(LayoutDirection),
    /// A `Text`'s text can be selected and copied by the user. Sent when
    /// the text is created, and never changed: Qt's selectable label is
    /// another item.
    Selectable(bool),
    /// Caption of a `Button`, `ToggleButton`, `MenuButton`, `SplitButton`,
    /// `Checkbox` or `Switch`; accessible name of a `Switch`, `Select`, `RadioGroup`,
    /// `Slider`, `NumberInput`, `Progress`, `Image`, `Icon` or `GpuSurface`,
    /// and of a button that shows only its icon.
    Label(String),
    /// Current text of a `TextInput`, `PasswordInput`, `SearchInput` or
    /// `TextArea`; a text area's lines end in `\n`.
    Value(String),
    /// What a text field shows while it's empty. Text areas show it where
    /// the platform's have one (Qt, WinUI).
    Placeholder(String),
    /// What's wrong with a `TextInput`'s, `PasswordInput`'s or
    /// `TextArea`'s text, or `None`: the platform marks the field where it
    /// has a way to (GTK's `error` style), and assistive technology reads
    /// it as invalid, with the message as its description. The app shows
    /// the message, as apps on every platform place their own.
    Error(Option<String>),
    /// A `TextInput` or `TextArea` shows its text, which can be selected
    /// and copied, but not edited: by typing, or by assistive technology.
    ReadOnly(bool),
    /// How many lines of text a `TextArea` is tall at its natural size, in
    /// the platform's font and line spacing; it scrolls past them. The
    /// layout can still make it taller or shorter.
    Lines(u32),
    /// A `TextArea`'s lines wrap to its width. Without, a line is as long
    /// as its text, and the area scrolls sideways. Sent only if the app
    /// chose.
    LineWrap(bool),
    /// A `TextArea` keeps its end in view as the app sets its text, while
    /// it's there (or the area was empty): a log that follows its output,
    /// as Terminal and Console do. Scrolled up, it stays put. Turned on, it
    /// shows its end. Sent only if the app chose.
    FollowsEnd(bool),
    /// What a `TextInput` is for; sent only if the app chose.
    InputPurpose(InputPurpose),
    /// Checked state of a `Checkbox`, `Switch` or `ToggleButton`.
    Checked(bool),
    /// A `Checkbox` shows the mixed state (some of what it stands for is
    /// checked), whatever `Checked` says. A click leaves it: where it lands
    /// is the platform's call, and the core absorbs it as `Mixed(false)`.
    Mixed(bool),
    Enabled(bool),
    TextStyle(TextStyle),
    ButtonRole(ButtonRole),
    ButtonStyle(ButtonStyle),
    /// A `Select`'s or `RadioGroup`'s options, in order.
    Options(Vec<String>),
    /// Which option of a `Select` is chosen: always one, unless it has no
    /// options. Which option of a `RadioGroup` is: `None` for none. Which item of a `Sidebar` is, counting across its sections:
    /// `None` for none. Which page of a `Tabs` is shown, and which tab of
    /// `DocumentTabs` is chosen: always one, unless it has none.
    SelectedIndex(Option<usize>),
    /// A `Slider`'s or `NumberInput`'s value, within its range. The core
    /// sends it after the range, which may have clamped it. A `Split`'s
    /// first pane's size along it, in points, which the core keeps within
    /// the panes' least sizes.
    Number(f64),
    /// A `ColorWell`'s colour: an opaque [`Color::Rgba`] (semantic
    /// colours and alpha aren't a colour well's).
    ColorValue(Color),
    /// The values a `Slider` or `NumberInput` can take.
    Range {
        min: f64,
        max: f64,
    },
    /// A `Slider`'s step, used as the platform uses one: to snap to, where
    /// its sliders snap, and to move by from the keyboard. What a
    /// `NumberInput`'s buttons and arrow keys add or take away. `None`: the
    /// platform's default.
    Step(Option<f64>),
    /// A `NumberInput` stepped past one end of its range goes on from the
    /// other. Sent only if the app chose: without, it's the platform's
    /// (AppKit's stepper wraps, the others stop).
    WrapAround(bool),
    /// Which way a `Slider` or a `Separator` runs; a `Split`'s panes are
    /// side by side when it's horizontal.
    Orientation(Orientation),
    /// A `Split`'s panes' least sizes along it, first then second, from
    /// their styles' least width (or height): the platform stops the
    /// divider there. Computed by the core.
    PaneMinimums([f32; 2]),
    /// Which of a `Split`'s panes show, first then second: the divider
    /// shows only between two. Computed by the core from the panes'
    /// visibility.
    PanesShown([bool; 2]),
    /// Text the platform shows when the pointer rests on the widget, as
    /// its tooltip, and assistive technology reads as its description.
    /// Any widget or container can have one; empty: none.
    Tooltip(String),
    /// The menu the platform shows its own way on a right-click, a long
    /// press or the menu key: items, separators and submenus. Any widget
    /// or container can have one; empty: none. The node reports the item
    /// chosen as [`UiEvent::ContextMenuItem`](crate::UiEvent::ContextMenuItem).
    ContextMenu(Vec<MenuEntry>),
    /// The node's context menu is built as the platform opens it: the
    /// platform calls it, from its own moment before a menu shows, and
    /// shows what it returns, which is also the node's `ContextMenu`
    /// from then on. `None`: the menu is `ContextMenu` alone.
    ContextMenuOnOpen(Option<crate::services::MenuOnOpen>),
    /// A `MenuButton`'s or `SplitButton`'s menu: items, separators and
    /// submenus, built as a context menu's. The node reports the item chosen as
    /// [`UiEvent::MenuItem`](crate::UiEvent::MenuItem).
    Menu(Vec<MenuEntry>),
    /// A `MenuButton`'s menu is built as the platform opens it, as
    /// [`ContextMenuOnOpen`](Prop::ContextMenuOnOpen) builds a context
    /// menu: what it returns is shown, and is the node's `Menu` from then
    /// on. `None`: the menu is `Menu` alone.
    MenuOnOpen(Option<crate::services::MenuOnOpen>),
    /// A window is modal, belonging to `owner` (the window it was declared
    /// in, if any). Sent once, before the window is shown.
    Modal {
        owner: Option<NodeId>,
        modality: Modality,
    },
    /// What an `Image` shows.
    Image(ImageSource),
    /// How an `Image` fills its frame; sent only if the app chose.
    ImageFit(ImageFit),
    /// What an `Icon` shows, or the icon a `Button`, `ToggleButton`,
    /// `MenuButton` or `SplitButton` shows before its caption: a name in
    /// the platform's own set (an SF Symbol, a themed
    /// icon's name, a Segoe Fluent Icons glyph). Empty: none. A name the
    /// set doesn't have shows as the platform shows one: nothing, or its
    /// missing-icon icon.
    Icon(String),
    /// The app's own icon, in place of a named one ([`Prop::Icon`]), for
    /// the same widgets: drawn as the platform draws its symbolic icons.
    /// `None`: the named one, if any.
    VectorIcon(Option<crate::VectorIcon>),
    /// How big an `Icon` is, in points, used as the platform sizes icons:
    /// an SF Symbol's point size (as a font's), the side of a square
    /// elsewhere; a `FileIcon`'s square's side everywhere. Sent only if the
    /// app chose.
    IconSize(f32),
    /// The file or folder a `FileIcon` shows the icon of. It's read when
    /// set, as an image file is.
    File(PathBuf),
    /// A `FileIcon` shows a preview of what's in the file (a picture's,
    /// a document's first page) in place of its icon, where the platform
    /// makes one; its icon until then, and where it makes none.
    Thumbnail(bool),
    /// Where a `FileIcon` gets its icon: the file on disk, or only its
    /// name. By name, `Thumbnail` is ignored.
    FileLookup(FileLookup),
    /// A button shows its icon without its caption, which stays its
    /// accessible name. Without an icon it shows its caption.
    IconOnly(bool),
    /// Whether a `Spinner` spins. Stopped, it shows nothing but keeps its
    /// place.
    Running(bool),
    /// How far along a `Progress` is, from 0 to 1. `None`: not known (an
    /// indeterminate, animated bar).
    Progress(Option<f64>),
    /// Which axes a `ScrollView` scrolls.
    ScrollAxes(ScrollAxes),
    /// Whether a `ScrollView` shows scroll bars, as the platform shows them.
    /// Without, it still scrolls, by wheel, trackpad and touch.
    ScrollBars(bool),
    /// A `Tabs`' page titles, in page order; `DocumentTabs`' titles, in
    /// order.
    TabTitles(Vec<String>),
    /// A `Tabs`' tab icons, in page order: names in the platform's own set,
    /// as `Icon`'s; empty for none. Sent only if a tab has one.
    TabIcons(Vec<String>),
    /// How a `Tabs` shows its tabs. Sent only if the app chose.
    TabsStyle(TabsStyle),
    /// `DocumentTabs`' tabs have the platform's close buttons (and its
    /// middle click, where it has one), which report
    /// `TabCloseRequested`; the app closes the tab. Sent only if the app
    /// asked (`on_close`).
    TabsClosable(bool),
    /// The user can drag `DocumentTabs`' tabs to another place among them
    /// (and move them from the keyboard, where the platform can), which
    /// reports `TabMoved`; the core absorbs it. Sent only if the app asked
    /// (`on_move`).
    TabsReorderable(bool),
    /// `DocumentTabs` have the platform's new-tab button, which reports
    /// `NewTabRequested`. Sent only if the app asked (`on_new`).
    NewTabButton(bool),
    /// Where `DocumentTabs` show their tabs. Sent only if the app chose.
    DocumentTabsStyle(DocumentTabsStyle),
    /// A `Sidebar`'s items, in sections, in order.
    Sections(Vec<SidebarSectionData>),
    /// A `Sidebar` is shown beside the window's content, or hidden, as the
    /// platform shows and hides one. The user can change it too: the
    /// backend reports `SidebarShownChanged`, which the core absorbs. Sent
    /// only if the app chose.
    SidebarShown(bool),
    /// A `Popover` is shown by its parent, or not. The user dismisses one
    /// too (a click outside, Escape): the backend reports
    /// `PopoverShownChanged(false)`, which the core absorbs.
    PopoverShown(bool),
    /// What a `SearchInput` suggests for its text, in a list under it while
    /// the user types, as each platform shows a field's suggestions (an
    /// `AutoSuggestBox`'s list, a list in a window that doesn't take the
    /// keyboard on AppKit, a popover that doesn't on GTK, a popup that
    /// doesn't on Qt). The field keeps the keyboard: the arrows move
    /// through the list, Return picks, Escape hides it. Empty: none.
    Suggestions(Vec<Suggestion>),
    /// A `SearchInput` searches on Return (and when cleared), not as the
    /// user types: each platform's setting for searches that take a while
    /// (AppKit's `sendsWholeSearchString`, GTK's `activate` alone, WinUI's
    /// `QuerySubmitted` alone, Kirigami's `autoAccept` off). Sent only if
    /// the app chose.
    SearchOnReturn(bool),
    /// A `Container` at the top of its window's content is the window's
    /// header, the part that stays while what's under it scrolls: on
    /// AppKit it goes in the title bar, under the title and toolbar, in
    /// their glass (a bottom `NSTitlebarAccessoryViewController`), and the
    /// scroll view right under it runs up under the bar, blurred at its
    /// edge, as Safari's and Mail's bars have it. The others have no such
    /// bar and leave it where it is, at the content's top; so does AppKit
    /// for one that isn't there, or beside a sidebar. Sent only if the app
    /// chose.
    Header(bool),
    /// How a header meets what scrolls under it. Sent only if the app
    /// chose.
    HeaderEdge(HeaderEdge),
    /// A container that's a pane down its window's side that navigates
    /// (the rail that picks a Git client's pages, a mail app's folders) when the app builds
    /// one itself rather than with `Sidebar`. On WinUI, under tabs in the
    /// title bar, it's Mica Alt's commanding layer, as a header is; the
    /// others leave it as it is. Sent only if the app chose.
    SidebarPane(bool),
    /// A container the pointer passes through, with everything in it, to
    /// what's under it: a hint laid over a control. Sent only if the app
    /// chose.
    ClickThrough(bool),
    /// A `List`'s rows, in order.
    Rows(Vec<RowKey>),
    /// A `Tree`'s rows that show, in order: a row, then its open
    /// children's rows. Children of closed rows aren't sent.
    TreeRows(Vec<TreeRow>),
    /// A `Tree`'s rows whose children are being read (a folder on a
    /// network share opening), of the rows that show: the platform shows
    /// its spinner where the row's disclosure is. Sent only if the app
    /// said which rows load.
    TreeLoading(Vec<RowKey>),
    /// How high a `List`'s rows are likely to be, for platforms that must
    /// size rows before they're shown.
    EstimatedRowHeight(f32),
    /// Which row of its `List` a row host shows.
    Row(RowKey),
    /// A `Table`'s columns, in order.
    Columns(Vec<ColumnData>),
    /// The column a `Table` is sorted by, which its header shows. The user
    /// pressing a sortable column's header sorts it as the platform does:
    /// the backend reports `Changed(Sort)`, which the core absorbs.
    Sort(Option<ColumnSort>),
    /// Which cell of its `Table` a cell host shows.
    Cell(CellKey),
    SelectionMode(SelectionMode),
    ListStyle(ListStyle),
    /// The selected rows of a `List`.
    Selected(Vec<RowKey>),
    /// A custom widget's props, with its renders.
    Custom(CustomProps),
    /// What a drawn custom widget shows. Computed by the core after layout,
    /// so it arrives with the frames.
    Drawing(DisplayList),
    /// A `Native` node's factory (on create), then its updates: payloads in
    /// the backend's own form.
    Native(Opaque),
    /// A `GpuSurface` takes keys and the pointer, and reports them as
    /// `SurfaceInput`: it takes focus from a click and from Tab.
    TakesInput(bool),
    /// A `GpuSurface` holds the pointer: the cursor is hidden and stays
    /// put, and its moves are reported as `SurfaceInput::Motion`. Only
    /// while its window is the active one; the backend reports
    /// `PointerLockEnded` when that stops, or it can't lock.
    PointerLock(bool),
    /// A `GpuSurface` takes every key while it has focus, the system's
    /// shortcuts and the app's own too, as far as the platform lets an
    /// app. Setting it focuses the surface; the backend reports
    /// `KeyboardGrabEnded` when the surface or its window loses focus, or
    /// it can't grab.
    KeyboardGrab(bool),
    /// The pointer's cursor over a `GpuSurface`.
    Cursor(Cursor),
    /// A `GpuSurface` that takes input takes text too, as a text field
    /// does: its keys report what they type, and the platform's input
    /// methods are on while it has focus, committing as
    /// `SurfaceInput::Text`.
    TextInput(bool),
    /// Whether the platform's input methods are on while a `GpuSurface`
    /// takes text (they are unless this says otherwise). Off, its keys
    /// still report what they type, dead keys and AltGr composed in, but
    /// nothing composes: for a modal editor whose keys are commands
    /// outside its insert mode, as a terminal's are.
    InputMethod(bool),
    /// Where the caret is on a `GpuSurface` that takes text, in points from
    /// its top left: the input method's candidate window opens by it.
    TextCursor(Option<Rect>),
    /// A `GpuSurface` lets the window's backdrop show where what the app
    /// presents isn't opaque: the material the platform puts behind a
    /// translucent window (AppKit's behind-window vibrancy, WinUI's Mica,
    /// which its windows always have), or the window's own background where
    /// there's none. The app still presents with alpha.
    Transparent(bool),
    /// A `Container` or `Group` takes the files and folders this says
    /// when they're dragged from the platform's file manager and dropped
    /// on it; `None`: none. While acceptable files are over it, the
    /// platform shows it'll copy them, and the node reports
    /// `DropHover(true)`, then `DropHover(false)`; a drop reports the ones
    /// it takes as `FilesDropped`.
    FileDrop(Option<FileDrop>),
    /// A `Container` or `Group` reports the pointer coming over it, or
    /// over anything inside it, and leaving, as
    /// [`UiEvent::Hover`](crate::UiEvent::Hover). Sent only if the app
    /// asked (`on_hover`).
    Hover(bool),
    /// A `Container` or `Group` reports a double click on it, or on
    /// anything inside it that isn't a control (a label, an icon), as
    /// [`UiEvent::DoubleClick`](crate::UiEvent::DoubleClick). Sent only if
    /// the app asked (`on_double_click`).
    DoubleClick(bool),
    /// A `Container` or `Group` reports a click on it, or on anything
    /// inside it that isn't a control, as [`UiEvent::Click`](crate::UiEvent::Click),
    /// as a header that opens its section. Sent only if the app asked
    /// (`on_click`).
    Click(bool),
    /// A `List`'s or `Table`'s rows' files: dragging a row carries its
    /// file out of the app (to the file manager, another app, a folder),
    /// and dragging a selected row carries every selected row's, as the
    /// platform drags a selection. The drag offers to copy. Rows without a
    /// file don't drag. Sent before the rows, and only if the app gave
    /// them.
    RowFiles(Vec<(RowKey, PathBuf)>),
    /// A `List`'s rows can be dragged within it, and dropped where it
    /// says (`List::on_move`); it reports `RowsMoved`. Sent only if the app
    /// gave it.
    RowMoves(RowMoves),
    /// The keys a `Container`, `Group`, `List` or `Table` takes while it,
    /// or a control inside it, has keyboard focus, and the focused control
    /// doesn't use them itself: they go up from the focused control, as the
    /// platform sends keys it doesn't use, to the nearest node that takes
    /// them, which reports [`UiEvent::Key`](crate::UiEvent::Key). On a
    /// `TextInput` or `SearchInput`, the keys it takes before its own use
    /// of them (the arrows, Return, Escape): a field that moves through a
    /// list beside it, as Xcode's Open Quickly. A search field's
    /// suggestions still take theirs first. Sent only if the app gave some.
    Keys(Vec<Shortcut>),
    /// Raw platform settings for a built-in widget (see
    /// [`Tweak`](crate::Tweak)), in the backend's own form. Applied after
    /// the widget's other props, and again whenever they change.
    Tweak(Opaque),
}

impl Prop {
    /// Two props with the same key replace each other.
    pub fn key(&self) -> std::mem::Discriminant<Prop> {
        std::mem::discriminant(self)
    }

    /// Whether changing this prop can change the intrinsic size of a widget
    /// of this kind.
    pub fn affects_measure(&self, kind: WidgetKind) -> bool {
        // A spin box can be as wide as its range's longest number (GTK) or
        // its text (Qt).
        if kind == WidgetKind::NumberInput && matches!(self, Prop::Range { .. } | Prop::Number(_)) {
            return true;
        }
        // A pull-down can be as wide as its widest item (AppKit).
        if kind == WidgetKind::MenuButton && matches!(self, Prop::Menu(_)) {
            return true;
        }
        if kind == WidgetKind::TextArea && matches!(self, Prop::Lines(_)) {
            return true;
        }
        // A strip is as wide as its tabs and its new-tab button, and is the
        // window's or the content's.
        if kind == WidgetKind::DocumentTabs
            && matches!(
                self,
                Prop::TabTitles(_) | Prop::TabsClosable(_) | Prop::NewTabButton(_) | Prop::DocumentTabsStyle(_)
            )
        {
            return true;
        }
        matches!(
            self,
            Prop::Text(_)
                | Prop::MaxLines(_)
                | Prop::Truncation(_)
                | Prop::FontWeight(_)
                | Prop::Italic(_)
                | Prop::Label(_)
                | Prop::Placeholder(_)
                | Prop::Options(_)
                | Prop::SelectedIndex(_)
                | Prop::TextStyle(_)
                | Prop::ButtonRole(_)
                | Prop::ButtonStyle(_)
                | Prop::Orientation(_)
                | Prop::Image(_)
                | Prop::Icon(_)
                | Prop::VectorIcon(_)
                | Prop::IconSize(_)
                | Prop::IconOnly(_)
                | Prop::Custom(_)
                | Prop::Native(_)
                | Prop::Tweak(_)
        )
    }
}

/// Where the item at `index` of a list is after the one at `from` moved to
/// `to`: `DocumentTabs`' chosen tab after `TabMoved`.
pub fn moved_index(index: usize, from: usize, to: usize) -> usize {
    if index == from {
        to
    } else if from < index && index <= to {
        index - 1
    } else if to <= index && index < from {
        index + 1
    } else {
        index
    }
}

/// Finds a prop by pattern in a prop list.
#[macro_export]
macro_rules! find_prop {
    ($props:expr, $variant:ident) => {
        $props.iter().find_map(|p| match p {
            $crate::Prop::$variant(v) => Some(v.clone()),
            _ => None,
        })
    };
}

macro_rules! static_value {
    ($($t:ty),*) => {$(
        impl mitsuami_reactive::IntoValue<$t> for $t {
            fn into_value(self) -> mitsuami_reactive::Value<$t> {
                mitsuami_reactive::Value::Static(self)
            }
        }
    )*};
}

static_value!(
    FileDrop,
    TextStyle,
    FontWeight,
    TextAlign,
    Truncation,
    FileLookup,
    crate::draw::Color,
    ButtonRole,
    ButtonStyle,
    TabsStyle,
    HeaderEdge,
    DocumentTabsStyle,
    Orientation,
    ScrollAxes,
    SelectionMode,
    SortOrder,
    ListStyle,
    InputPurpose,
    ImageSource,
    Pixels,
    ImageFit,
    Modality,
    Cursor,
    Size,
    crate::VectorIcon
);