smudge-core 0.2.0

Widget tree, reactive bindings, layout, paint and damage tracking for the Smudge GUI library
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
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
//! Elements: the builder that describes one node, and the bindings that keep
//! its properties current.
//!
//! An element holds a widget, a style, the bindings that update parts of that
//! style, and its children. Building one touches no tree: mounting creates the
//! nodes and installs one render effect per binding inside the node's owner.
//!
//! A binding never writes to the tree itself. Its effect reads the value and
//! pushes an update onto the shared update queue, and the frame applies the
//! queued updates before it lays anything out. That is what keeps every write
//! to the tree in one place and in one order.
//!
//! Every builder takes either a plain value or a closure. A plain value is
//! written when the element is built and costs nothing afterwards. A closure
//! becomes a binding: it is read when the node mounts and again whenever a
//! signal it reads changes, and it updates that one property without rebuilding
//! the element or its children.
//!
//! ```
//! use smudge_core::geometry::Color;
//! use smudge_core::reactive::{self, prelude::*};
//! use smudge_core::style::px;
//! use smudge_core::widget::panel;
//!
//! let (on, _set_on) = reactive::signal_local(false);
//! let card = panel()
//!     .width(px(120.0))
//!     .height(px(40.0))
//!     .corner_radius(6.0)
//!     .background(move || {
//!         if on.get() {
//!             Color::rgb(220, 60, 60).into()
//!         } else {
//!             Color::rgb(60, 60, 220).into()
//!         }
//!     })
//!     .child(panel().width(px(20.0)).height(px(20.0)).background(Color::WHITE));
//! ```

use std::any::TypeId;
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::hash::Hash;
use std::rc::Rc;

use crate::geometry::{Color, Point, Size};
use crate::input::{Handled, KeyEvent};
use crate::paint::PaintOp;
use crate::reactive::{Owner, RenderEffect, RwSignal};
use crate::semantics::Role;
use crate::style::{
    Align, Direction, Edges, Justify, LayoutProps, Length, Overflow, PaintProps, Position, Style,
};
use crate::theme::{ColorToken, ColorValue, RadiusToken, RadiusValue};
use crate::tree::interaction::Handlers;
use crate::tree::{Dirty, WidgetId, WidgetTree};
use crate::variants::{PatchBuilder, StylePatch, Variants};
use crate::widget::{PaintCx, Widget};

/// One change to the widget tree, applied by the frame's apply step.
pub(crate) type Update = Box<dyn FnOnce(&mut WidgetTree)>;

/// The style that an element applies to every child as it is added.
type ChildStyling = Rc<dyn Fn(&mut Style)>;

/// The updates that are waiting to be applied.
///
/// Every binding shares one queue, so a frame applies the effects of all of
/// them in the order the effects were queued.
#[derive(Clone, Default)]
pub(crate) struct UpdateQueue(Rc<RefCell<VecDeque<Update>>>);

impl UpdateQueue {
    /// Queues `update` to run in the next apply step.
    pub(crate) fn push(&self, update: Update) {
        self.0.borrow_mut().push_back(update);
    }

    /// Applies every queued update to `tree`, in the order they were queued,
    /// and returns whether any ran.
    ///
    /// An update may queue another update, as mounting a child does when its
    /// bindings run. Those run after the updates that were already waiting, in
    /// the same call, so one call settles everything the queue holds.
    pub(crate) fn apply(&self, tree: &mut WidgetTree) -> bool {
        let mut applied = false;
        loop {
            let next = self.0.borrow_mut().pop_front();
            let Some(update) = next else {
                return applied;
            };
            applied = true;
            update(tree);
        }
    }
}

/// A property that is either fixed or computed from signals.
///
/// [`Value::Static`] is written once, when the element is built. [`Value::Dynamic`]
/// becomes a binding: the closure is read when the node mounts and again
/// whenever a signal it reads changes.
///
/// A value converts into this type, so a builder method can take either one.
#[derive(Clone)]
pub enum Value<T> {
    /// A value that never changes.
    Static(T),
    /// A closure that reads the value from signals.
    Dynamic(Rc<dyn Fn() -> T>),
}

/// Implements the conversion from a plain value for every property type.
macro_rules! static_values {
    ($($property:ty),* $(,)?) => {
        $(
            impl From<$property> for Value<$property> {
                fn from(value: $property) -> Value<$property> {
                    Value::Static(value)
                }
            }
        )*
    };
}

static_values!(
    ColorValue,
    RadiusValue,
    Length,
    Size,
    Edges<Length>,
    f32,
    bool,
    Direction,
    Align,
    Justify,
    Overflow,
    Point,
);

impl From<crate::window::Cursor> for Value<Option<crate::window::Cursor>> {
    fn from(cursor: crate::window::Cursor) -> Value<Option<crate::window::Cursor>> {
        Value::Static(Some(cursor))
    }
}

impl From<Option<crate::window::Cursor>> for Value<Option<crate::window::Cursor>> {
    fn from(cursor: Option<crate::window::Cursor>) -> Value<Option<crate::window::Cursor>> {
        Value::Static(cursor)
    }
}

impl From<Option<u32>> for Value<Option<u32>> {
    fn from(value: Option<u32>) -> Value<Option<u32>> {
        Value::Static(value)
    }
}

impl From<u32> for Value<u32> {
    fn from(value: u32) -> Value<u32> {
        Value::Static(value)
    }
}

impl From<String> for Value<String> {
    fn from(text: String) -> Value<String> {
        Value::Static(text)
    }
}

impl From<&str> for Value<String> {
    fn from(text: &str) -> Value<String> {
        Value::Static(text.to_owned())
    }
}

impl From<Color> for Value<ColorValue> {
    fn from(color: Color) -> Value<ColorValue> {
        Value::Static(color.into())
    }
}

impl From<ColorToken> for Value<ColorValue> {
    fn from(token: ColorToken) -> Value<ColorValue> {
        Value::Static(token.into())
    }
}

impl From<f32> for Value<RadiusValue> {
    fn from(radius: f32) -> Value<RadiusValue> {
        Value::Static(radius.into())
    }
}

impl From<RadiusToken> for Value<RadiusValue> {
    fn from(token: RadiusToken) -> Value<RadiusValue> {
        Value::Static(token.into())
    }
}

impl<F: Fn() -> T + 'static, T: 'static> From<F> for Value<T> {
    fn from(get: F) -> Value<T> {
        Value::Dynamic(Rc::new(get))
    }
}

/// Installs a binding's effect inside a node's owner and returns its handle.
type Install = Box<dyn FnOnce(WidgetId, &UpdateQueue) -> RenderEffect>;

/// One property of one node that a render effect keeps up to date.
struct Binding {
    /// Creates the effect inside the node's owner and returns its handle.
    ///
    /// The effect runs once immediately and queues an update every time it
    /// runs.
    install: Install,
    /// The property the binding writes, when it writes one the element's
    /// builders can set again.
    key: Option<Key>,
}

/// What a binding writes, so a later write of the same thing can replace an
/// earlier binding of it.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Key {
    /// A property of the node's style or state.
    Style(Prop),
    /// A property of the node's widget, named by the marker type given to
    /// [`Element::bind`].
    Widget(TypeId),
}

/// A property an element's builders write, so a later write of the same
/// property can replace an earlier binding of it.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Prop {
    Width,
    Height,
    MinWidth,
    MinHeight,
    MaxWidth,
    MaxHeight,
    Padding,
    Margin,
    Gap,
    Direction,
    Wrap,
    Grow,
    Shrink,
    Basis,
    AlignItems,
    JustifyContent,
    Inset,
    BorderWidth,
    Overflow,
    Hidden,
    Background,
    BorderColor,
    TextColor,
    Radius,
    ScrollOffset,
    Disabled,
    Cursor,
    Pin,
}

impl Binding {
    /// A binding that writes one layout property.
    fn layout<T: 'static>(
        prop: Prop,
        get: Rc<dyn Fn() -> T>,
        write: fn(&mut LayoutProps, T),
    ) -> Binding {
        Binding {
            key: Some(Key::Style(prop)),
            install: Box::new(move |id, queue| {
                let queue = queue.clone();
                RenderEffect::new(move || {
                    let value = get();
                    let queue = queue.clone();
                    queue.push(Box::new(move |tree| {
                        tree.apply_layout(id, move |layout| write(layout, value));
                    }));
                })
            }),
        }
    }

    /// A binding that writes one paint property.
    fn paint<T: 'static>(
        prop: Prop,
        get: Rc<dyn Fn() -> T>,
        write: fn(&mut PaintProps, T),
    ) -> Binding {
        Binding {
            key: Some(Key::Style(prop)),
            install: Box::new(move |id, queue| {
                let queue = queue.clone();
                RenderEffect::new(move || {
                    let value = get();
                    let queue = queue.clone();
                    queue.push(Box::new(move |tree| {
                        tree.apply_paint(id, move |paint| write(paint, value));
                    }));
                })
            }),
        }
    }

    /// A binding that writes the node's disabled bit.
    fn disabled(get: Rc<dyn Fn() -> bool>) -> Binding {
        Binding {
            key: Some(Key::Style(Prop::Disabled)),
            install: Box::new(move |id, queue| {
                let queue = queue.clone();
                RenderEffect::new(move || {
                    let value = get();
                    let queue = queue.clone();
                    queue.push(Box::new(move |tree| {
                        tree.set_disabled(id, value);
                    }));
                })
            }),
        }
    }

    /// A binding that writes the node's accessible label.
    fn a11y_label(get: Rc<dyn Fn() -> String>) -> Binding {
        Binding {
            key: None,
            install: Box::new(move |id, queue| {
                let queue = queue.clone();
                RenderEffect::new(move || {
                    let value = get();
                    let queue = queue.clone();
                    queue.push(Box::new(move |tree| {
                        tree.set_a11y_label(id, Some(value));
                    }));
                })
            }),
        }
    }

    /// A binding that writes the node's scroll offset.
    ///
    /// The write moves the node's flowing descendants without running the
    /// layout engine, which is what a scroll view does on every wheel tick.
    fn scroll_offset(get: Rc<dyn Fn() -> Point>) -> Binding {
        Binding {
            key: Some(Key::Style(Prop::ScrollOffset)),
            install: Box::new(move |id, queue| {
                let queue = queue.clone();
                RenderEffect::new(move || {
                    let value = get();
                    let queue = queue.clone();
                    queue.push(Box::new(move |tree| {
                        tree.set_scroll_offset(id, value);
                    }));
                })
            }),
        }
    }

    /// A binding that writes which flowing child the node pins, and where.
    fn pin_child(get: Rc<dyn Fn() -> Option<(usize, f32)>>) -> Binding {
        Binding {
            key: Some(Key::Style(Prop::Pin)),
            install: Box::new(move |id, queue| {
                let queue = queue.clone();
                RenderEffect::new(move || {
                    let value = get();
                    let queue = queue.clone();
                    queue.push(Box::new(move |tree| {
                        tree.set_pin(id, value);
                    }));
                })
            }),
        }
    }

    /// A binding that writes the node's cursor.
    fn cursor(get: Rc<dyn Fn() -> Option<crate::window::Cursor>>) -> Binding {
        Binding {
            key: Some(Key::Style(Prop::Cursor)),
            install: Box::new(move |id, queue| {
                let queue = queue.clone();
                RenderEffect::new(move || {
                    let value = get();
                    let queue = queue.clone();
                    queue.push(Box::new(move |tree| {
                        tree.set_cursor(id, value);
                    }));
                })
            }),
        }
    }

    /// A binding that writes one property of the node's widget.
    ///
    /// The apply function reports how much of the node its write invalidated,
    /// and the node is marked with that. A write that changes what the widget
    /// measures returns [`Dirty::Layout`], which also invalidates the size the
    /// layout engine cached for the node.
    fn widget<W: Widget, T: 'static>(
        key: Key,
        get: Rc<dyn Fn() -> T>,
        apply: fn(&mut W, T) -> Dirty,
    ) -> Binding {
        Binding {
            key: Some(key),
            install: Box::new(move |id, queue| {
                let queue = queue.clone();
                RenderEffect::new(move || {
                    let value = get();
                    let queue = queue.clone();
                    queue.push(Box::new(move |tree| {
                        let dirty = match tree.widget_mut::<W>(id) {
                            Some(widget) => apply(widget, value),
                            None => return,
                        };
                        tree.mark(id, dirty);
                    }));
                })
            }),
        }
    }
}

/// A node under construction: its widget, its style, its pending bindings and
/// its children.
///
/// Build one with a widget constructor such as [`panel`](crate::widget::panel),
/// chain the builder methods, and hand it to a parent with [`Element::child`]
/// or to [`show`].
///
/// A builder takes either a plain value, which is written into the style
/// immediately, or a closure, which becomes a binding that is read at mount and
/// again whenever a signal it reads changes.
pub struct Element<W: Widget> {
    /// The widget the node will own.
    widget: W,
    /// The style the node starts with.
    style: Style,
    /// Bindings installed when the node mounts.
    bindings: Vec<Binding>,
    /// The style patches per interaction state, when a variant builder ran.
    variants: Option<Variants>,
    /// The input handlers the node will own.
    handlers: Handlers,
    /// Whether the node starts disabled.
    disabled: bool,
    /// The cursor the node sets for the pointer over it, when its element
    /// set a static one.
    cursor: Option<crate::window::Cursor>,
    /// Whether the node can take the keyboard focus.
    focusable: bool,
    /// Whether the node requests the focus on the first frame after it is
    /// laid out.
    autofocus: bool,
    /// Whether the node keeps Tab movement inside its subtree while it is
    /// mounted.
    trap_focus: bool,
    /// The signal that pins the node's scroll offset to the end of its
    /// content while it reads `true`.
    follow_end: Option<RwSignal<bool>>,
    /// The role the accessibility projection reports, when an element set
    /// one.
    a11y_role: Option<Role>,
    /// The accessible label an element set, when it set one.
    a11y_label: Option<Value<String>>,
    /// The scroll offset written to the node when it mounts.
    scroll_offset: Point,
    /// Applied to the style of every child as it is added.
    child_styling: Option<ChildStyling>,
    /// The children, in paint order.
    children: Vec<AnyElement>,
}

impl<W: Widget> Element<W> {
    /// Creates an element for `widget` with the default style.
    ///
    /// ```
    /// use smudge_core::element::Element;
    /// use smudge_core::widget::Panel;
    ///
    /// let element = Element::new(Panel);
    /// ```
    pub fn new(widget: W) -> Element<W> {
        Element {
            widget,
            style: Style::default(),
            bindings: Vec::new(),
            variants: None,
            handlers: Handlers::default(),
            disabled: false,
            cursor: None,
            focusable: false,
            autofocus: false,
            trap_focus: false,
            follow_end: None,
            a11y_role: None,
            a11y_label: None,
            scroll_offset: Point::default(),
            child_styling: None,
            children: Vec::new(),
        }
    }

    /// Appends `child` after the children the element already has.
    ///
    /// When [`Element::style_children`] set a style for the children, it is
    /// applied to this one.
    pub fn child(mut self, child: impl IntoElement) -> Self {
        let mut child = child.into_any();
        if let Some(style) = &self.child_styling {
            style(&mut child.style);
        }
        self.children.push(child);
        self
    }

    /// Appends every child of `children`, in order.
    ///
    /// When [`Element::style_children`] set a style for the children, it is
    /// applied to each one.
    pub fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
        self.children.extend(children.into_iter().map(|child| {
            let mut child = child.into_any();
            if let Some(style) = &self.child_styling {
                style(&mut child.style);
            }
            child
        }));
        self
    }

    /// Applies `style` to every direct child of this element: to the children
    /// added so far, at once, and to every child added afterwards as it is
    /// added.
    ///
    /// The children of a child keep their own style, and a child that mounts
    /// later through [`show`] mounts under a slot, so it is styled only
    /// through that slot. A binding on the same field of a child applies when
    /// the child mounts, after this style, so the binding wins.
    ///
    /// This is how a container decides how its children sit: a stack applies
    /// the absolute position that makes children overlap, for example.
    ///
    /// ```
    /// use smudge_core::element::Element;
    /// use smudge_core::widget::Panel;
    ///
    /// let layers = Element::new(Panel).style_children(|style| {
    ///     style.paint.corner_radius = 4.0.into();
    /// });
    /// ```
    pub fn style_children(mut self, style: impl Fn(&mut Style) + 'static) -> Self {
        let style = Rc::new(style);
        for child in &mut self.children {
            style(&mut child.style);
        }
        self.child_styling = Some(style);
        self
    }

    /// Writes one layout property, or records a binding for it.
    fn layout_value<T: 'static>(
        mut self,
        prop: Prop,
        value: impl Into<Value<T>>,
        write: fn(&mut LayoutProps, T),
    ) -> Self {
        self.replace_binding(prop);
        match value.into() {
            Value::Static(value) => write(&mut self.style.layout, value),
            Value::Dynamic(get) => self.bindings.push(Binding::layout(prop, get, write)),
        }
        self
    }

    /// Drops the bindings recorded for `prop` so far, because a later write
    /// of the same property, fixed or bound, replaces them: the last builder
    /// call for a property wins, as it does between two fixed values.
    fn replace_binding(&mut self, prop: Prop) {
        self.drop_bindings(Key::Style(prop));
    }

    /// Drops the bindings recorded for `key` so far.
    fn drop_bindings(&mut self, key: Key) {
        self.bindings.retain(|binding| binding.key != Some(key));
    }

    /// Writes one paint property, or records a binding for it.
    fn paint_value<T: 'static>(
        mut self,
        prop: Prop,
        value: impl Into<Value<T>>,
        write: fn(&mut PaintProps, T),
    ) -> Self {
        self.replace_binding(prop);
        match value.into() {
            Value::Static(value) => write(&mut self.style.paint, value),
            Value::Dynamic(get) => self.bindings.push(Binding::paint(prop, get, write)),
        }
        self
    }

    /// Sets the width. This takes part in layout.
    pub fn width(self, width: impl Into<Value<Length>>) -> Self {
        self.layout_value(Prop::Width, width, |layout, width| layout.width = width)
    }

    /// Sets the height. This takes part in layout.
    pub fn height(self, height: impl Into<Value<Length>>) -> Self {
        self.layout_value(Prop::Height, height, |layout, height| {
            layout.height = height
        })
    }

    /// Sets the width and the height, in logical pixels. This takes part in
    /// layout.
    pub fn size(self, size: impl Into<Value<Size>>) -> Self {
        let (width, height): (Value<Length>, Value<Length>) = match size.into() {
            Value::Static(size) => (
                Value::Static(Length::px(size.width)),
                Value::Static(Length::px(size.height)),
            ),
            Value::Dynamic(get) => {
                let get_height = Rc::clone(&get);
                (
                    Value::Dynamic(Rc::new(move || Length::px(get().width))),
                    Value::Dynamic(Rc::new(move || Length::px(get_height().height))),
                )
            }
        };
        self.width(width).height(height)
    }

    /// Sets the lower bound of the width. This takes part in layout.
    pub fn min_width(self, width: impl Into<Value<Length>>) -> Self {
        self.layout_value(Prop::MinWidth, width, |layout, width| {
            layout.min_width = width
        })
    }

    /// Sets the lower bound of the height. This takes part in layout.
    pub fn min_height(self, height: impl Into<Value<Length>>) -> Self {
        self.layout_value(Prop::MinHeight, height, |layout, height| {
            layout.min_height = height
        })
    }

    /// Sets the upper bound of the width. This takes part in layout.
    pub fn max_width(self, width: impl Into<Value<Length>>) -> Self {
        self.layout_value(Prop::MaxWidth, width, |layout, width| {
            layout.max_width = width
        })
    }

    /// Sets the upper bound of the height. This takes part in layout.
    pub fn max_height(self, height: impl Into<Value<Length>>) -> Self {
        self.layout_value(Prop::MaxHeight, height, |layout, height| {
            layout.max_height = height
        })
    }

    /// Sets the same padding on all four sides. This takes part in layout.
    pub fn padding(self, padding: impl Into<Value<Length>>) -> Self {
        self.layout_value(Prop::Padding, padding, |layout, padding| {
            layout.padding = Edges::all(padding);
        })
    }

    /// Sets the horizontal padding from `width` and the vertical padding from
    /// `height`. This takes part in layout.
    pub fn padding_xy(self, padding: impl Into<Value<Size>>) -> Self {
        self.layout_value(Prop::Padding, padding, |layout, padding| {
            layout.padding = Edges::xy(Length::px(padding.width), Length::px(padding.height));
        })
    }

    /// Sets the same margin on all four sides. This takes part in layout.
    pub fn margin(self, margin: impl Into<Value<Length>>) -> Self {
        self.layout_value(Prop::Margin, margin, |layout, margin| {
            layout.margin = Edges::all(margin);
        })
    }

    /// Sets the space between adjacent children. This takes part in layout.
    pub fn gap(self, gap: impl Into<Value<Size>>) -> Self {
        self.layout_value(Prop::Gap, gap, |layout, gap| layout.gap = gap)
    }

    /// Sets the main axis of the children's flex layout. This takes part in
    /// layout.
    pub fn direction(self, direction: impl Into<Value<Direction>>) -> Self {
        self.layout_value(Prop::Direction, direction, |layout, direction| {
            layout.direction = direction;
        })
    }

    /// Lays the children out left to right. This takes part in layout.
    pub fn row(mut self) -> Self {
        self.replace_binding(Prop::Direction);
        self.style.layout.direction = Direction::Row;
        self
    }

    /// Lays the children out top to bottom. This takes part in layout.
    pub fn column(mut self) -> Self {
        self.replace_binding(Prop::Direction);
        self.style.layout.direction = Direction::Column;
        self
    }

    /// Lets children that do not fit move to a new line instead of shrinking.
    /// This takes part in layout.
    pub fn wrap(self, wrap: impl Into<Value<bool>>) -> Self {
        self.layout_value(Prop::Wrap, wrap, |layout, wrap| layout.wrap = wrap)
    }

    /// Sets the share of the leftover space on the main axis this node takes.
    /// This takes part in layout.
    pub fn grow(self, grow: impl Into<Value<f32>>) -> Self {
        self.layout_value(Prop::Grow, grow, |layout, grow| layout.grow = grow)
    }

    /// Sets how readily this node gives up space when its siblings overflow.
    /// This takes part in layout.
    pub fn shrink(self, shrink: impl Into<Value<f32>>) -> Self {
        self.layout_value(Prop::Shrink, shrink, |layout, shrink| {
            layout.shrink = shrink
        })
    }

    /// Sets the main axis size the node starts from before growing or
    /// shrinking. This takes part in layout.
    pub fn basis(self, basis: impl Into<Value<Length>>) -> Self {
        self.layout_value(Prop::Basis, basis, |layout, basis| layout.basis = basis)
    }

    /// Sets how the children line up across the main axis. This takes part in
    /// layout.
    pub fn align_items(self, align: impl Into<Value<Align>>) -> Self {
        self.layout_value(Prop::AlignItems, align, |layout, align| {
            layout.align_items = Some(align)
        })
    }

    /// Sets how the children are spread along the main axis. This takes part in
    /// layout.
    pub fn justify_content(self, justify: impl Into<Value<Justify>>) -> Self {
        self.layout_value(Prop::JustifyContent, justify, |layout, justify| {
            layout.justify_content = Some(justify);
        })
    }

    /// Takes the node out of normal flow, so its insets place it against its
    /// containing block and its siblings are laid out as if it were not there.
    /// This takes part in layout.
    pub fn absolute(mut self) -> Self {
        self.style.layout.position = Position::Absolute;
        self
    }

    /// Sets the offsets from the containing block's edges. This takes part in
    /// layout.
    pub fn inset(self, inset: impl Into<Value<Edges<Length>>>) -> Self {
        self.layout_value(Prop::Inset, inset, |layout, inset| layout.inset = inset)
    }

    /// Sets the border width, the same on all four sides. This takes part in
    /// layout, because the border takes space away from the content. The border
    /// is painted in the color set by [`Element::border_color`].
    pub fn border(self, width: impl Into<Value<f32>>) -> Self {
        self.layout_value(Prop::BorderWidth, width, |layout, width| {
            layout.border_width = Edges::all(width);
        })
    }

    /// Clips the children to the node's bounds. This takes part in layout,
    /// because clipping also changes the automatic minimum size of a flex item.
    pub fn clip(self, clip: impl Into<Value<bool>>) -> Self {
        self.layout_value(Prop::Overflow, clip, |layout, clip| {
            layout.overflow = if clip {
                Overflow::Clip
            } else {
                Overflow::Visible
            };
        })
    }

    /// Sets what happens to children that do not fit inside the node. This
    /// takes part in layout: [`Overflow::Scroll`] makes the node a scroll
    /// container, whose automatic minimum size as a flex item is zero, and
    /// [`Element::clip`] is the shorthand for [`Overflow::Clip`].
    pub fn overflow(self, overflow: impl Into<Value<Overflow>>) -> Self {
        self.layout_value(Prop::Overflow, overflow, |layout, overflow| {
            layout.overflow = overflow;
        })
    }

    /// Hides the node and its subtree, or shows them again. This takes part in
    /// layout, because a hidden node is not laid out and paints nothing.
    pub fn hidden(self, hidden: impl Into<Value<bool>>) -> Self {
        self.layout_value(Prop::Hidden, hidden, |layout, hidden| {
            layout.hidden = hidden
        })
    }

    /// Translates the node's flowing children by this offset after layout,
    /// outside the layout engine.
    ///
    /// This is what a scroll view changes when it scrolls: every child that
    /// stays in the flow moves by minus the offset in the window, without
    /// running the layout engine again. The frame damages the areas the
    /// children moved out of and into and wraps them in an offset display
    /// item, so a child that only moved does not paint again. An absolutely
    /// positioned child is left where its insets place it, so chrome drawn
    /// over the content does not scroll away with it.
    ///
    /// The offset can be bound to a signal, like the style builders. It is a
    /// position, not a style: it takes part in no layout comparison, and an
    /// equal offset changes nothing.
    pub fn scroll_offset(mut self, offset: impl Into<Value<Point>>) -> Self {
        self.replace_binding(Prop::ScrollOffset);
        match offset.into() {
            Value::Static(offset) => self.scroll_offset = offset,
            Value::Dynamic(get) => self.bindings.push(Binding::scroll_offset(get)),
        }
        self
    }

    /// Keeps one flowing child at a fixed place inside the node, whatever
    /// the heights of the children before it.
    ///
    /// While `pin` returns `Some((index, y))`, every layout pass ends with
    /// the top of the flowing child at `index` sitting `y` logical pixels
    /// below the top of the node's content box. The children keep their
    /// order and the sizes the pass gave them, so the ones before the pinned
    /// child stack upward from it and the ones after it stack downward,
    /// edge to edge. A child that grows therefore pushes its neighbours away
    /// from the pinned child in the frame it grows, and never overlaps them.
    ///
    /// The pin moves the children the way [`Element::scroll_offset`] does,
    /// outside the layout engine, so do not give the node a scroll offset
    /// too. `None`, an index past the last child, or a pinned child that is
    /// hidden or absolutely positioned leaves the children where they are. A change of the pin alone moves them without a
    /// layout pass.
    ///
    /// ```
    /// use smudge_core::element::Element;
    /// use smudge_core::style::px;
    /// use smudge_core::widget::{Panel, panel};
    ///
    /// // The second row stays 100 pixels down, however tall the first is.
    /// let rows = Element::new(Panel)
    ///     .column()
    ///     .pin_child(|| Some((1, 100.0)))
    ///     .child(panel().height(px(30.0)))
    ///     .child(panel().height(px(30.0)));
    /// ```
    pub fn pin_child(mut self, pin: impl Fn() -> Option<(usize, f32)> + 'static) -> Self {
        self.replace_binding(Prop::Pin);
        self.bindings.push(Binding::pin_child(Rc::new(pin)));
        self
    }

    /// Sets the fill painted behind the node. This repaints the node without
    /// laying it out again.
    ///
    /// The color can be a [`Color`] or a
    /// [`ColorToken`]. A token resolves against the
    /// theme that is current when the node paints.
    pub fn background(self, color: impl Into<Value<ColorValue>>) -> Self {
        self.paint_value(Prop::Background, color, |paint, color| {
            paint.background = Some(color)
        })
    }

    /// Sets the color of the border whose width [`Element::border`] sets. This
    /// repaints the node without laying it out again.
    ///
    /// The color can be a [`Color`] or a
    /// [`ColorToken`]. A token resolves against the
    /// theme that is current when the node paints.
    pub fn border_color(self, color: impl Into<Value<ColorValue>>) -> Self {
        self.paint_value(Prop::BorderColor, color, |paint, color| {
            paint.border_color = Some(color)
        })
    }

    /// Sets the color a widget's text paints with. This repaints the node
    /// without laying it out again.
    ///
    /// Widgets that show text read it; widgets without text ignore it. The
    /// color can be a [`Color`] or a
    /// [`ColorToken`]. A token resolves against the
    /// theme that is current when the node paints.
    pub fn text_color(self, color: impl Into<Value<ColorValue>>) -> Self {
        self.paint_value(Prop::TextColor, color, |paint, color| {
            paint.text_color = Some(color)
        })
    }

    /// Sets the corner radius of the background and the border, the same on all
    /// four corners. An image widget rounds the pixels it paints by the same
    /// radius. This repaints the node without laying it out again.
    ///
    /// The radius can be an [`f32`] or a
    /// [`RadiusToken`]. A token resolves against
    /// the theme that is current when the node paints.
    pub fn corner_radius(self, radius: impl Into<Value<RadiusValue>>) -> Self {
        self.paint_value(Prop::Radius, radius, |paint, radius| {
            paint.corner_radius = radius;
        })
    }

    /// Records a patch built by `build` into one slot of the element's
    /// variants.
    fn variant(
        mut self,
        select: impl FnOnce(&mut Variants) -> &mut Option<StylePatch>,
        build: impl FnOnce(PatchBuilder) -> PatchBuilder,
    ) -> Self {
        let builder = build(PatchBuilder::default());
        let variants = self.variants.get_or_insert_with(Variants::default);
        *select(variants) = Some(builder.patch());
        self
    }

    /// Applies a patch while the node is in the hovered chain, which is the
    /// node under the pointer that can respond and its ancestors.
    ///
    /// The closure records static values into a [`PatchBuilder`]; a reactive
    /// value has no place in a patch, so the patch methods take plain values.
    /// While the pointer is over the node the patch overrides the fields it
    /// sets, and when the pointer leaves, the base style stands again. A node
    /// with a variant is a target for hover and presses even without
    /// handlers, so a styled card reacts to the pointer on its own.
    ///
    /// A change of hover re-resolves the style: a patch that touches only
    /// paint properties repaints the node, one that touches layout
    /// properties lays it out again. Hover also follows a layout that moves
    /// nodes under a resting pointer, except that a layout never takes the
    /// hover away from a node whose hover patch changes its layout: such a
    /// patch can move the node off the pointer, and the node then stays
    /// hovered until the pointer moves, instead of flickering.
    ///
    /// ```
    /// use smudge_core::geometry::Color;
    /// use smudge_core::widget::panel;
    ///
    /// let card = panel()
    ///     .background(Color::rgb(50, 50, 50))
    ///     .hover(|p| p.background(Color::rgb(70, 70, 70)));
    /// ```
    pub fn hover(self, patch: impl FnOnce(PatchBuilder) -> PatchBuilder) -> Self {
        self.variant(|variants| &mut variants.hovered, patch)
    }

    /// Applies a patch while the node holds the keyboard focus and the focus
    /// last moved by keyboard navigation.
    ///
    /// The focus a press moved draws no focus style, so a ring follows Tab and
    /// not a mouse click. Everything else works as
    /// [`hover`](Element::hover) does.
    ///
    /// ```
    /// use smudge_core::geometry::Color;
    /// use smudge_core::style::px;
    /// use smudge_core::widget::panel;
    ///
    /// let field = panel()
    ///     .width(px(120.0))
    ///     .height(px(24.0))
    ///     .focusable()
    ///     .focused(|p| p.border(1.0).border_color(Color::rgb(0, 120, 215)));
    /// ```
    pub fn focused(self, patch: impl FnOnce(PatchBuilder) -> PatchBuilder) -> Self {
        self.variant(|variants| &mut variants.focused, patch)
    }

    /// Applies a patch while a primary press is held on the node.
    ///
    /// Everything works as [`hover`](Element::hover) does; the pressed state
    /// starts when the button goes down on the node and ends when it is
    /// released.
    ///
    /// ```
    /// use smudge_core::geometry::Color;
    /// use smudge_core::widget::panel;
    ///
    /// let button = panel()
    ///     .background(Color::rgb(50, 50, 50))
    ///     .pressed(|p| p.background(Color::rgb(30, 30, 30)));
    /// ```
    pub fn pressed(self, patch: impl FnOnce(PatchBuilder) -> PatchBuilder) -> Self {
        self.variant(|variants| &mut variants.pressed, patch)
    }

    /// Applies a patch while the node is disabled.
    ///
    /// The patch wins over every other state, so a disabled control keeps its
    /// switched-off look while it is hovered or pressed. Everything else
    /// works as [`hover`](Element::hover) does.
    ///
    /// ```
    /// use smudge_core::geometry::Color;
    /// use smudge_core::widget::panel;
    ///
    /// let button = panel()
    ///     .background(Color::rgb(50, 50, 50))
    ///     .disabled_style(|p| p.background(Color::rgb(35, 35, 35)));
    /// ```
    pub fn disabled_style(self, patch: impl FnOnce(PatchBuilder) -> PatchBuilder) -> Self {
        self.variant(|variants| &mut variants.disabled, patch)
    }

    /// Runs `handler` when the primary button is released over the node after
    /// a press that started on it.
    ///
    /// The press is captured: between the press and the release the node keeps
    /// the pointer even when it moves away, and the handler runs only when the
    /// release happens over the node again. A press released elsewhere runs
    /// nothing.
    ///
    /// ```
    /// use std::cell::Cell;
    /// use std::rc::Rc;
    ///
    /// use smudge_core::app::{App, AppConfig, RepaintMode};
    /// use smudge_core::geometry::{Color, Point, Size};
    /// use smudge_core::input::{InputEvent, PointerButton};
    /// use smudge_core::style::px;
    /// use smudge_core::widget::panel;
    ///
    /// let presses = Rc::new(Cell::new(0u32));
    /// let counted = Rc::clone(&presses);
    /// let mut app = App::new(
    ///     AppConfig {
    ///         viewport: Size {
    ///             width: 100.0,
    ///             height: 60.0,
    ///         },
    ///         scale: 1.0,
    ///         clear_color: Color::WHITE,
    ///         repaint: RepaintMode::Damage,
    ///     },
    ///     move || {
    ///         panel().width(px(40.0)).height(px(20.0)).on_press(move || {
    ///             counted.set(counted.get() + 1);
    ///         })
    ///     },
    /// );
    /// app.frame();
    ///
    /// let corner = Point { x: 10.0, y: 5.0 };
    /// app.handle_event(InputEvent::PointerMoved { position: corner });
    /// app.handle_event(InputEvent::PointerDown {
    ///     position: corner,
    ///     button: PointerButton::Primary,
    /// });
    /// app.handle_event(InputEvent::PointerUp {
    ///     position: corner,
    ///     button: PointerButton::Primary,
    /// });
    /// assert_eq!(presses.get(), 1);
    /// ```
    pub fn on_press(mut self, handler: impl FnMut() + 'static) -> Self {
        self.handlers.on_press = Some(Box::new(handler));
        self
    }

    /// Runs `handler` when the node enters (`true`) or leaves (`false`) the
    /// hovered chain.
    ///
    /// The hovered chain is the nearest enabled node under the pointer that can
    /// respond and its enabled ancestors, so a container stays hovered while
    /// the pointer is over one of its children, and a disabled node never
    /// hears it. While a press is held, hover does not change until the
    /// button is released. The handler runs inside the node's owner, so it can
    /// write the signals the element's bindings read.
    pub fn on_hover(mut self, handler: impl FnMut(bool) + 'static) -> Self {
        self.handlers.on_hover = Some(Box::new(handler));
        self
    }

    /// Runs `handler` when the primary pointer button is pressed on the node.
    ///
    /// The position is in logical pixels, relative to the top left of the
    /// node's rectangle, so it does not depend on where layout or a scroll
    /// view put the node. Other buttons do not run it.
    pub fn on_pointer_down(mut self, handler: impl FnMut(Point) + 'static) -> Self {
        self.handlers.on_pointer_down = Some(Box::new(handler));
        self
    }

    /// Runs `handler` when a primary press targets a node that is neither this
    /// node nor one of its descendants.
    ///
    /// A press on the node itself, on a child, or on a deeper descendant does
    /// not run it, so a popup asks for presses outside itself and closes on
    /// the ones it gets. A press that reaches no node at all is outside every
    /// node.
    pub fn on_press_outside(mut self, handler: impl FnMut() + 'static) -> Self {
        self.handlers.on_press_outside = Some(Box::new(handler));
        self
    }

    /// Runs `handler` when the wheel scrolls while the node is in the hovered
    /// chain, which is the case when the pointer is over the node or over one
    /// of its descendants.
    ///
    /// The delta is in logical pixels, positive for scrolling right and down.
    /// The handlers run from the deepest node in the hovered chain outward,
    /// and the first that returns [`Handled::Yes`] takes the whole event, so
    /// of two nested scroll views the one under the pointer scrolls and the
    /// one around it does not. A handler that cannot use the event, such as
    /// a view already scrolled to its end in the wheel's direction, returns
    /// [`Handled::No`] and the event bubbles to the next one. The handler
    /// runs inside the node's owner, so it can write the signals the
    /// element's bindings read.
    pub fn on_wheel(mut self, handler: impl FnMut(Point) -> Handled + 'static) -> Self {
        self.handlers.on_wheel = Some(Box::new(handler));
        self
    }

    /// Runs `handler` when the pointer moves while a press that started on
    /// the node is held, which is how a drag reaches the node it started on.
    ///
    /// With no press held, the handler runs when the node is the hover target
    /// and the pointer moves, so a node can follow the pointer without being
    /// pressed. While a press is held, hover does not change, and the moves
    /// go to the captured node alone. The position is in logical pixels,
    /// relative to the top left of the node's rectangle. The handler runs
    /// inside the node's owner, so it can write the signals the element's
    /// bindings read.
    pub fn on_pointer_move(mut self, handler: impl FnMut(Point) + 'static) -> Self {
        self.handlers.on_pointer_move = Some(Box::new(handler));
        self
    }

    /// Runs `handler` when the primary button is released.
    ///
    /// After a press on the node, the handler runs when the button comes up
    /// wherever that happens, which is how a drag ends even when the pointer
    /// is no longer over the node. With no press held, the handler runs when
    /// the release happens over the node as the hover target. The position is
    /// in logical pixels, relative to the top left of the node's rectangle.
    /// The handler runs inside the node's owner, so it can write the signals the
    /// element's bindings read.
    pub fn on_pointer_up(mut self, handler: impl FnMut(Point) + 'static) -> Self {
        self.handlers.on_pointer_up = Some(Box::new(handler));
        self
    }

    /// Runs `handler` when the input method commits text while the node or
    /// one of its descendants holds the keyboard focus.
    ///
    /// A commit can arrive with no key event at all, because composing text
    /// with an input method ends in a commit rather than a key press, so an
    /// editor that takes text needs this handler. The commit goes to the
    /// deepest handler in the focused chain and does not bubble past it.
    /// While a focus trap is active and the focus is outside it, the commit
    /// starts at the trap instead, as a key does. The handler runs inside
    /// the node's owner, so it can write the signals the element's bindings
    /// read.
    pub fn on_ime_commit(mut self, handler: impl FnMut(&str) + 'static) -> Self {
        self.handlers.on_ime_commit = Some(Box::new(handler));
        self
    }

    /// Runs `handler` when the input method changes its composing text while
    /// the node or one of its descendants holds the keyboard focus.
    ///
    /// The handler receives the composing text and the byte range of the
    /// cursor inside it, or `None` when the input method shows no cursor. An
    /// empty text means the composition was canceled or committed, and the
    /// preedit must go. An editor draws the composing text itself, usually
    /// underlined, and does not write it into its value until the commit
    /// arrives. Like [`Element::on_ime_commit`], the event goes to the
    /// deepest handler in the focused chain and does not bubble past it, and
    /// the handler runs inside the node's owner.
    pub fn on_ime_preedit(
        mut self,
        handler: impl FnMut(&str, Option<(usize, usize)>) + 'static,
    ) -> Self {
        self.handlers.on_ime_preedit = Some(Box::new(handler));
        self
    }

    /// Disables the node, which takes it out of hit testing, or enables it
    /// again.
    ///
    /// A disabled node receives no pointer events of its own: its handlers
    /// never run, and a press over it passes to whatever enabled node is hit
    /// instead. Its children are still hit. This can be bound to a signal,
    /// like the style builders.
    pub fn disabled(mut self, disabled: impl Into<Value<bool>>) -> Self {
        self.replace_binding(Prop::Disabled);
        match disabled.into() {
            Value::Static(disabled) => self.disabled = disabled,
            Value::Dynamic(get) => self.bindings.push(Binding::disabled(get)),
        }
        self
    }

    /// Sets the cursor the pointer shows while it is over the node, or over
    /// a descendant that sets none of its own.
    ///
    /// The window shows the cursor of the deepest enabled node under the
    /// pointer that sets one, so a nested setter wins over an ancestor's.
    /// Setting a cursor does not make the node a target: a press over a node
    /// that sets only a cursor still lands on the nearest ancestor that
    /// responds, and so does hover. This takes a [`Cursor`], or an
    /// `Option<Cursor>` where `None` leaves the choice to the ancestors, and
    /// it can be bound to a signal, like the style builders: a binding that
    /// returns `None` hands the choice back to the ancestors.
    ///
    /// [`Cursor`]: crate::window::Cursor
    ///
    /// ```
    /// use smudge_core::geometry::Color;
    /// use smudge_core::widget::panel;
    /// use smudge_core::window::Cursor;
    ///
    /// let link = panel()
    ///     .width(smudge_core::style::px(80.0))
    ///     .height(smudge_core::style::px(24.0))
    ///     .background(Color::rgb(40, 40, 48))
    ///     .cursor(Cursor::Pointer);
    /// ```
    pub fn cursor(mut self, cursor: impl Into<Value<Option<crate::window::Cursor>>>) -> Self {
        self.replace_binding(Prop::Cursor);
        match cursor.into() {
            Value::Static(cursor) => self.cursor = cursor,
            Value::Dynamic(get) => self.bindings.push(Binding::cursor(get)),
        }
        self
    }

    /// Sets the role the accessibility projection reports for the node.
    ///
    /// A widget that reports no role of its own stays out of the projection
    /// and its children attach to the nearest projected ancestor, so this
    /// builder places a plain container on the accessibility tree. The role
    /// is fixed for the node's lifetime, and it overrides the role the
    /// widget itself reports.
    pub fn role(mut self, role: Role) -> Self {
        self.a11y_role = Some(role);
        self
    }

    /// Sets the accessible name a screen reader announces for the node.
    ///
    /// This can be bound to a signal, like the style builders. It overrides
    /// the name the widget itself reports.
    pub fn accessible_label(mut self, label: impl Into<Value<String>>) -> Self {
        self.a11y_label = Some(label.into());
        self
    }

    /// Makes the node able to take the keyboard focus, by a press on it or by
    /// Tab navigation.
    ///
    /// While a node holds the focus, key events reach it before they bubble to
    /// its ancestors, which is what [`Element::on_key`] hears.
    /// [`Element::on_key`] implies this, so a key handler never needs a
    /// separate `focusable` call.
    pub fn focusable(mut self) -> Self {
        self.focusable = true;
        self
    }

    /// Takes the keyboard focus on the first frame the node is laid out
    /// after it mounts.
    ///
    /// The request resolves after the layout pass that lays the node out, so
    /// the focus is set before the frame paints and a node a [`show`] mounts
    /// takes the focus in the frame it appears in. The request runs once per
    /// mount: when the focus moves away later, the node does not ask again,
    /// and a node unmounted and mounted again by a fresh [`show`] run does.
    /// A node that is hidden, or sits under a hidden ancestor, keeps its
    /// request until it is first laid out visible, so a dialog that mounts
    /// hidden and shows later takes the focus in the frame it shows in. A
    /// request whose node is disabled when it resolves is dropped and never
    /// asked again. When several nodes show in one frame, the node painted
    /// last wins.
    ///
    /// While a focus trap is mounted, only a node inside the trap can take
    /// the focus this way; a request for a node outside it is dropped, like
    /// any other request that cannot take the focus.
    ///
    /// This makes the node focusable, like [`Element::on_key`] does.
    ///
    /// ```
    /// use std::cell::Cell;
    /// use std::rc::Rc;
    ///
    /// use smudge_core::app::{App, AppConfig, RepaintMode};
    /// use smudge_core::geometry::{Color, Size};
    /// use smudge_core::widget::panel;
    ///
    /// let focused = Rc::new(Cell::new(false));
    /// let count = Rc::clone(&focused);
    /// let mut app = App::new(
    ///     AppConfig {
    ///         viewport: Size {
    ///             width: 100.0,
    ///             height: 60.0,
    ///         },
    ///         scale: 1.0,
    ///         clear_color: Color::WHITE,
    ///         repaint: RepaintMode::Damage,
    ///     },
    ///     move || panel().autofocus().on_focus(move |on| count.set(on)),
    /// );
    /// app.frame();
    ///
    /// assert!(focused.get(), "the node took the focus on its first frame");
    /// ```
    pub fn autofocus(mut self) -> Self {
        self.focusable = true;
        self.autofocus = true;
        self
    }

    /// Keeps Tab and Shift+Tab cycling among the focusable nodes inside the
    /// node's subtree, for as long as the node is mounted and not hidden.
    ///
    /// A node the user Tabs to inside the trap never lands outside it: the
    /// cycle wraps within the subtree, and a Tab pressed with nothing
    /// focused enters the trap at its first focusable node. While the trap
    /// holds no focusable node, a Tab press leaves the focus where it is. A
    /// pointer press that lands on no node that can respond, or on a node
    /// outside the trap, leaves the focus where it is, and a press on a node
    /// inside the trap moves the focus as usual: to that node when it can
    /// take the focus, and away when it cannot. This is how a modal dialog
    /// keeps the keyboard inside itself instead of wandering into the view
    /// behind it.
    ///
    /// While the trap is active, a key that would start outside it, because
    /// the focus is outside the trap or nothing holds the focus, starts at
    /// the trap node and bubbles from there to the root, so the trap's own
    /// key handlers hear it and a control behind it does not.
    ///
    /// When several traps are mounted, the last one wins, and a nested trap
    /// therefore takes over from the one around it. Removing a trap, which
    /// is what unmounting a [`show`] child does, restores the trap mounted
    /// before it, and returns the focus to the node that held it when the
    /// trap became active, when that node is still mounted and can take it.
    /// A trap becomes active when it mounts visible or shows again. A trap
    /// that cannot hold the focus, because it became disabled or hidden or
    /// sits under a hidden ancestor, yields to an earlier one while it stays
    /// mounted, and a trap that hides gives the focus back the way removing
    /// it does, when the focus was inside it or nowhere. A hidden or
    /// disabled state counts once a layout pass has run, which every frame
    /// that changes the hidden state does.
    pub fn trap_focus(mut self) -> Self {
        self.trap_focus = true;
        self
    }

    /// Pins the node's scroll offset to the end of its flowing content while
    /// `signal` reads `true`.
    ///
    /// Every layout pass that runs while the signal reads `true` ends with
    /// the node's offset at the furthest its flowing content reaches, minus
    /// the height of its content box, floored at zero. The pin uses the
    /// rectangles that pass just computed, so a frame that grows the content
    /// shows the end in view in the same frame. A signal that reads `false`
    /// leaves the offset where it is, and a write of `true` from anywhere
    /// pins the node in the next frame.
    ///
    /// What turns the signal is the caller's decision, not the core's: the
    /// scroll view widget pairs this builder with its wheel handling, so a
    /// step that leaves the end releases the pin and a step back to it
    /// engages it again.
    ///
    /// ```
    /// use smudge_core::element::Element;
    /// use smudge_core::reactive::RwSignal;
    /// use smudge_core::widget::Panel;
    ///
    /// let following = RwSignal::new(true);
    /// let view = Element::new(Panel).follow(following);
    /// ```
    pub fn follow(mut self, signal: RwSignal<bool>) -> Self {
        self.follow_end = Some(signal);
        self
    }

    /// Runs `handler` when a key event reaches the node while the node or one
    /// of its descendants holds the keyboard focus.
    ///
    /// The event walks up from the focused node, and the first handler that
    /// returns [`Handled::Yes`] stops it, so a handler that takes a key hides
    /// it from its ancestors. Tab moves the focus away only when no handler
    /// took the Tab key. This makes the node focusable, so a press on it or a
    /// Tab puts the focus on it.
    ///
    /// The handler runs inside the node's owner, so it can write the signals
    /// the element's bindings read.
    ///
    /// ```
    /// use std::cell::Cell;
    /// use std::rc::Rc;
    ///
    /// use smudge_core::app::{App, AppConfig, RepaintMode};
    /// use smudge_core::geometry::{Color, Size};
    /// use smudge_core::input::{Handled, InputEvent, Key, KeyEvent};
    /// use smudge_core::style::px;
    /// use smudge_core::widget::panel;
    ///
    /// let enters = Rc::new(Cell::new(0u32));
    /// let counted = Rc::clone(&enters);
    /// let mut app = App::new(
    ///     AppConfig {
    ///         viewport: Size {
    ///             width: 100.0,
    ///             height: 60.0,
    ///         },
    ///         scale: 1.0,
    ///         clear_color: Color::WHITE,
    ///         repaint: RepaintMode::Damage,
    ///     },
    ///     move || {
    ///         panel().child(
    ///             panel()
    ///                 .width(px(40.0))
    ///                 .height(px(20.0))
    ///                 .on_key(move |event: &KeyEvent| {
    ///                     if event.pressed && event.key == Key::Enter {
    ///                         counted.set(counted.get() + 1);
    ///                         Handled::Yes
    ///                     } else {
    ///                         Handled::No
    ///                     }
    ///                 }),
    ///         )
    ///     },
    /// );
    /// app.frame();
    ///
    /// // Tab moves the focus to the panel, which then hears the Enter key.
    /// app.handle_event(InputEvent::Key(KeyEvent {
    ///     key: Key::Tab,
    ///     pressed: true,
    ///     repeat: false,
    ///     modifiers: Default::default(),
    ///     text: None,
    /// }));
    /// app.handle_event(InputEvent::Key(KeyEvent {
    ///     key: Key::Enter,
    ///     pressed: true,
    ///     repeat: false,
    ///     modifiers: Default::default(),
    ///     text: None,
    /// }));
    /// assert_eq!(enters.get(), 1);
    /// ```
    pub fn on_key(mut self, handler: impl FnMut(&KeyEvent) -> Handled + 'static) -> Self {
        self.handlers.on_key = Some(Box::new(handler));
        self.focusable = true;
        self
    }

    /// Runs the handler set with [`Element::on_press`] when the node holds
    /// the keyboard focus and a fresh press of Enter or Space arrives.
    ///
    /// This is how a button fires from the keyboard with the same handler its
    /// pointer press uses. The activation runs before any
    /// [`Element::on_key`] handler on the same node, and a key repeat fires
    /// nothing. A press handler that ran takes the key, so it does not reach
    /// an ancestor; without a press handler the key bubbles as usual.
    ///
    /// This makes the node focusable, like [`Element::on_key`] does.
    pub fn activate_on_keys(mut self) -> Self {
        self.handlers.activate_on_keys = true;
        self.focusable = true;
        self
    }

    /// Runs `handler` when the node gains (`true`) or loses (`false`) the
    /// keyboard focus.
    ///
    /// The handler does not make the node focusable; pair it with
    /// [`Element::focusable`] for that. It runs inside the node's owner, so it
    /// can write the signals the element's bindings read. A node that is
    /// removed while focused clears the focus without hearing `on_focus` again,
    /// because its handlers are being torn down with it.
    pub fn on_focus(mut self, handler: impl FnMut(bool) + 'static) -> Self {
        self.handlers.on_focus = Some(Box::new(handler));
        self
    }

    /// Binds one property of the element's own widget.
    ///
    /// The first argument names the property: pass a value of a marker type, usually a
    /// unit struct, that stands for it and for nothing else. The last call
    /// for a key wins, fixed or bound, the way it does for the style
    /// builders: a later call drops the binding an earlier call with a key
    /// of the same type recorded. Bindings with different key types all
    /// stay, and they apply in the order they were made.
    ///
    /// `apply` writes the value into the widget and returns how much of the
    /// node the write invalidated. A write that changes what the widget
    /// measures returns [`Dirty::Layout`], and the node is laid out and painted
    /// again. Any other write returns [`Dirty::Paint`] and only repaints the
    /// node.
    ///
    /// ```
    /// use smudge_core::element::Element;
    /// use smudge_core::paint::PaintOp;
    /// use smudge_core::tree::Dirty;
    /// use smudge_core::widget::{PaintCx, Widget};
    ///
    /// struct Dot(f32);
    ///
    /// impl Widget for Dot {
    ///     fn paint(&self, _cx: &PaintCx<'_>, _out: &mut Vec<PaintOp>) {}
    /// }
    ///
    /// /// The key of the dot's radius.
    /// struct Radius;
    ///
    /// let element = Element::new(Dot(0.0)).bind(Radius, 3.0, |dot, value| {
    ///     dot.0 = value;
    ///     Dirty::Paint
    /// });
    /// ```
    pub fn bind<K: 'static, T: 'static>(
        mut self,
        _key: K,
        value: impl Into<Value<T>>,
        apply: fn(&mut W, T) -> Dirty,
    ) -> Self {
        let key = Key::Widget(TypeId::of::<K>());
        self.drop_bindings(key);
        match value.into() {
            Value::Static(value) => {
                apply(&mut self.widget, value);
            }
            Value::Dynamic(get) => self.bindings.push(Binding::widget(key, get, apply)),
        }
        self
    }
}

/// An element with its widget type erased, so that a parent can hold children
/// of different widget types.
///
/// Build one with [`IntoElement::into_any`]. Its contents are private: only
/// mounting reads them.
pub struct AnyElement {
    /// The node's widget.
    widget: Box<dyn Widget>,
    /// The style the node starts with.
    style: Style,
    /// Bindings installed when the node mounts.
    bindings: Vec<Binding>,
    /// The style patches per interaction state, when a variant builder ran.
    variants: Option<Variants>,
    /// The input handlers the node will own.
    handlers: Handlers,
    /// Whether the node starts disabled.
    disabled: bool,
    /// The cursor the node sets for the pointer over it, when its element
    /// set a static one.
    cursor: Option<crate::window::Cursor>,
    /// Whether the node can take the keyboard focus.
    focusable: bool,
    /// Whether the node requests the focus on the first frame after it is
    /// laid out.
    autofocus: bool,
    /// Whether the node keeps Tab movement inside its subtree while it is
    /// mounted.
    trap_focus: bool,
    /// The signal that pins the node's scroll offset to the end of its
    /// content while it reads `true`.
    follow_end: Option<RwSignal<bool>>,
    /// The role the accessibility projection reports, when an element set
    /// one.
    a11y_role: Option<Role>,
    /// The accessible label an element set, when it set one.
    a11y_label: Option<Value<String>>,
    /// The scroll offset written to the node when it mounts.
    scroll_offset: Point,
    /// The children, in paint order.
    children: Vec<AnyElement>,
}

impl AnyElement {
    /// Erases the widget type of `element`.
    fn new<W: Widget>(element: Element<W>) -> AnyElement {
        AnyElement {
            widget: Box::new(element.widget),
            style: element.style,
            bindings: element.bindings,
            variants: element.variants,
            handlers: element.handlers,
            disabled: element.disabled,
            cursor: element.cursor,
            focusable: element.focusable,
            autofocus: element.autofocus,
            trap_focus: element.trap_focus,
            follow_end: element.follow_end,
            a11y_role: element.a11y_role,
            a11y_label: element.a11y_label,
            scroll_offset: element.scroll_offset,
            children: element.children,
        }
    }
}

/// Converts an element into the erased form a parent stores.
pub trait IntoElement {
    /// Erases the widget type of this element.
    fn into_any(self) -> AnyElement;
}

impl<W: Widget> IntoElement for Element<W> {
    fn into_any(self) -> AnyElement {
        AnyElement::new(self)
    }
}

impl IntoElement for AnyElement {
    fn into_any(self) -> AnyElement {
        self
    }
}

/// Mounts `element` as a child of `parent`, or as the root when `parent` is
/// `None`, and returns the id of the node it created.
///
/// The node starts at [`Dirty::Layout`]. Bindings are installed inside the
/// node's owner and run once immediately, so the updates they queue are applied
/// before the first layout.
pub(crate) fn mount(
    element: AnyElement,
    tree: &mut WidgetTree,
    queue: &UpdateQueue,
    parent: Option<WidgetId>,
) -> WidgetId {
    let AnyElement {
        widget,
        style,
        mut bindings,
        variants,
        handlers,
        disabled,
        cursor,
        focusable,
        autofocus,
        trap_focus,
        follow_end,
        a11y_role,
        a11y_label,
        scroll_offset,
        children,
    } = element;
    let id = tree.insert(parent, widget, style);
    tree.set_variants(id, variants.map(Rc::new));
    tree.set_disabled(id, disabled);
    tree.set_cursor(id, cursor);
    tree.set_focusable(id, focusable);
    if autofocus {
        tree.queue_autofocus(id);
    }
    if trap_focus {
        tree.push_focus_trap(id);
    }
    if let Some(signal) = follow_end {
        tree.set_follow(id, signal);
    }
    tree.set_a11y_role(id, a11y_role);
    tree.set_handlers(id, handlers);
    let bindings = match a11y_label {
        Some(Value::Static(text)) => {
            tree.set_a11y_label(id, Some(text));
            bindings
        }
        Some(Value::Dynamic(get)) => {
            bindings.push(Binding::a11y_label(get));
            bindings
        }
        None => bindings,
    };
    if scroll_offset != Point::default() {
        tree.set_scroll_offset(id, scroll_offset);
    }
    let owner = tree.owner(id).expect("the node was just inserted").clone();
    for binding in bindings {
        owner.with(|| (binding.install)(id, queue));
    }
    for child in children {
        mount(child, tree, queue, Some(id));
    }
    id
}

/// A node that paints nothing and leaves its children to a binding.
///
/// [`show`] mounts its child under a slot, and [`for_each`] keeps one child
/// per key of a list under one.
pub struct Slot;

impl Widget for Slot {
    fn paint(&self, _cx: &PaintCx<'_>, _out: &mut Vec<PaintOp>) {}
}

/// Mounts the element that `build` returns as a child of `slot`, inside an
/// owner of its own.
///
/// The owner keeps the values the build creates alive for as long as the
/// child stays mounted, and [`unmount_child`] disposes them. Returns `None`
/// when `slot` is a stale id, which happens when the slot was removed while
/// an update that mounts into it was still queued.
fn mount_under_slot(
    slot: WidgetId,
    tree: &mut WidgetTree,
    queue: &UpdateQueue,
    build: impl FnOnce() -> AnyElement,
) -> Option<(WidgetId, Owner)> {
    let owner = tree.owner(slot)?.child();
    let element = owner.with(build);
    let child = mount(element, tree, queue, Some(slot));
    Some((child, owner))
}

/// Removes a child that [`mount_under_slot`] mounted and disposes the owner
/// its build ran in.
///
/// The tree removal runs first, so the child's bindings stop before the
/// values the build created are disposed.
fn unmount_child(child: WidgetId, owner: &Owner, tree: &mut WidgetTree) {
    tree.remove(child);
    owner.cleanup();
}

/// Mounts the element `build` returns while `when` is true, and removes it
/// while `when` is false.
///
/// Only `when` runs inside a binding, so only the signals it reads make the
/// slot check again. `build` runs untracked, once each time the child mounts,
/// under an owner of its own. Signals that `build` creates therefore live
/// exactly as long as the child: they survive every check that leaves the
/// child mounted, and they are disposed when the child is removed, after the
/// child's bindings have stopped.
///
/// ```
/// use smudge_core::element::show;
/// use smudge_core::reactive::{self, prelude::*};
/// use smudge_core::widget::panel;
///
/// let (visible, _set_visible) = reactive::signal_local(true);
/// let root = show(move || visible.get(), panel);
/// ```
pub fn show<E: IntoElement>(
    when: impl Fn() -> bool + 'static,
    build: impl Fn() -> E + 'static,
) -> Element<Slot> {
    let build: Rc<dyn Fn() -> AnyElement> = Rc::new(move || build().into_any());
    let mut element = Element::new(Slot);
    element.bindings.push(Binding {
        key: None,
        install: Box::new(move |id, queue| {
            let queue = queue.clone();
            let mounted: Rc<RefCell<Option<(WidgetId, Owner)>>> = Rc::new(RefCell::new(None));
            RenderEffect::new(move || {
                let visible = when();
                let child_queue = queue.clone();
                let mounted = Rc::clone(&mounted);
                let build = Rc::clone(&build);
                queue.push(Box::new(move |tree| {
                    let mut mounted = mounted.borrow_mut();
                    match (visible, mounted.take()) {
                        (true, None) => {
                            if let Some(child) =
                                mount_under_slot(id, tree, &child_queue, || build())
                            {
                                *mounted = Some(child);
                            }
                        }
                        (false, Some((child, owner))) => unmount_child(child, &owner, tree),
                        (_, unchanged) => *mounted = unchanged,
                    }
                }));
            })
        }),
    });
    element
}

/// Mounts one child per key of the list that `items` returns, keeping the
/// children that survive a change mounted and in place.
///
/// The returned element is a slot whose children follow the list. A key the
/// list gains mounts a new child, a key it loses removes that child's whole
/// tree, and a key that moves keeps its child, which is reordered rather than
/// rebuilt. A child keeps its reactive state across a reorder, and the frame
/// repaints only what changed position or stacking.
///
/// A row is built once per key, by `row`, the first time the key appears in
/// the list. Content that changes while a row stays mounted must come from
/// the signals that row reads: a new value for a key the list already had
/// reaches no mounted child.
///
/// The keys of a list must be unique. In a debug build a duplicate key trips
/// a debug assertion. In a release build the last duplicate wins: the row
/// mounted for that key takes the position of its last occurrence, and the
/// earlier occurrences contribute nothing.
///
/// `items` runs inside a binding, so only the signals it reads make the slot
/// diff the list again. `key` should depend on its item alone, because a key
/// that changes makes the slot remove one child and mount another. `row` runs
/// once per new key inside an owner of its own, so the signals a row creates
/// live exactly as long as the row.
///
/// The slot manages its own children; do not add children to the returned
/// element beside it.
///
/// ```
/// use smudge_core::element::for_each;
/// use smudge_core::reactive::{self, prelude::*};
/// use smudge_core::style::px;
/// use smudge_core::widget::panel;
///
/// let (items, _set_items) = reactive::signal_local(vec![1u32, 2, 3]);
/// let list = for_each(
///     move || items.get(),
///     |item| *item,
///     |item| panel().width(px(40.0)).height(px(10.0)),
/// );
/// ```
pub fn for_each<T, K, E>(
    items: impl Fn() -> Vec<T> + 'static,
    key: impl Fn(&T) -> K + 'static,
    row: impl Fn(T) -> E + 'static,
) -> Element<Slot>
where
    T: 'static,
    K: Eq + Hash + Clone + 'static,
    E: IntoElement,
{
    let items = Rc::new(items);
    let key = Rc::new(key);
    let row: Rc<dyn Fn(T) -> AnyElement> = Rc::new(move |item| row(item).into_any());
    let mut element = Element::new(Slot);
    element.bindings.push(Binding {
        key: None,
        install: Box::new(move |slot, queue| {
            let queue = queue.clone();
            let mounted: Rc<RefCell<HashMap<K, (WidgetId, Owner)>>> =
                Rc::new(RefCell::new(HashMap::new()));
            let order: Rc<RefCell<Vec<K>>> = Rc::new(RefCell::new(Vec::new()));
            RenderEffect::new(move || {
                let items = items();
                let keys: Vec<K> = items.iter().map(|item| key(item)).collect();
                // The last occurrence of a key decides where its row goes, so
                // a duplicate keeps one row and the earlier ones are skipped.
                let mut last: HashMap<K, usize> = HashMap::with_capacity(keys.len());
                for (at, item_key) in keys.iter().enumerate() {
                    last.insert(item_key.clone(), at);
                }
                debug_assert!(
                    last.len() == keys.len(),
                    "for_each found a duplicate key, but the keys of a list must be unique"
                );
                let child_queue = queue.clone();
                let mounted = Rc::clone(&mounted);
                let order = Rc::clone(&order);
                let row = Rc::clone(&row);
                queue.push(Box::new(move |tree| {
                    let mut mounted = mounted.borrow_mut();
                    let mut order = order.borrow_mut();

                    mounted.retain(|key, (child, owner)| {
                        let kept = last.contains_key(key);
                        if !kept {
                            unmount_child(*child, owner, tree);
                        }
                        kept
                    });

                    let mut new_order = Vec::with_capacity(last.len());
                    let mut children = Vec::with_capacity(last.len());
                    for (at, (item, item_key)) in items.into_iter().zip(keys).enumerate() {
                        if last[&item_key] != at {
                            continue;
                        }
                        let child = match mounted.get(&item_key) {
                            Some((child, _)) => *child,
                            None => {
                                let row = Rc::clone(&row);
                                let Some((child, owner)) =
                                    mount_under_slot(slot, tree, &child_queue, move || row(item))
                                else {
                                    continue;
                                };
                                mounted.insert(item_key.clone(), (child, owner));
                                child
                            }
                        };
                        children.push(child);
                        new_order.push(item_key);
                    }

                    if *order != new_order {
                        tree.set_children(slot, children);
                        *order = new_order;
                    }
                }));
            })
        }),
    });
    element
}

#[cfg(test)]
#[path = "element_tests.rs"]
mod tests;