frus-widgets 0.4.0

frus — declarative widget tree
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
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
//! **Components**: [`StatelessWidget`], [`StatefulWidget`] with its [`State`], and the
//! hooks that let a plain function keep state too.
//!
//! An interface is a tree of widgets, and some of them are not drawn: they are *built* —
//! a component is a widget whose only job is to say which other widgets it stands for.
//! `build` is called when the tree is rebuilt, and what it returns is put in its place.
//!
//! ```
//! use frus_widgets::{text, BuildContext, StatelessWidget, Widget};
//!
//! struct Greeting {
//!     name: String,
//! }
//!
//! impl StatelessWidget for Greeting {
//!     fn build(&self, _cx: &BuildContext) -> Box<dyn Widget> {
//!         Box::new(text(format!("Hello, {}", self.name)))
//!     }
//! }
//!
//! // used anywhere a widget is:
//! let greeting = Greeting { name: "world".into() }.into_widget();
//! # let _ = greeting;
//! ```
//!
//! ## State that outlives a rebuild
//!
//! The tree is rebuilt from scratch whenever something changes, so anything a widget must
//! remember cannot live in the widget. A [`StatefulWidget`] splits in two: the widget is
//! the *configuration* — cheap, thrown away and made again on every rebuild — and its
//! [`State`] is what stays. The framework keeps each `State` under the widget's place in
//! the tree, calls [`State::init_state`] when it is first created, [`State::did_update_widget`]
//! whenever the configuration above it changes, and [`State::dispose`] when the widget
//! leaves the tree.
//!
//! ```
//! use frus_widgets::{
//!     button, column, text, BuildContext, State, StateContext, StatefulWidget, Widget,
//! };
//!
//! struct Counter;
//!
//! struct CounterState {
//!     count: i32,
//! }
//!
//! impl StatefulWidget for Counter {
//!     type State = CounterState;
//!     fn create_state(&self) -> CounterState {
//!         CounterState { count: 0 }
//!     }
//! }
//!
//! impl State for CounterState {
//!     type Widget = Counter;
//!     fn build(&self, cx: &StateContext<Self>) -> Box<dyn Widget> {
//!         Box::new(column![
//!             text(format!("{}", self.count)),
//!             // `callback` is `set_state` wrapped up as a handler
//!             button("+", cx.callback(|state| state.count += 1)),
//!         ])
//!     }
//! }
//! ```
//!
//! ## State without a struct
//!
//! A function of `&BuildContext` is a component too, and inside one, **hooks** —
//! [`BuildContext::use_state`], [`BuildContext::use_ref`], [`BuildContext::use_memo`],
//! [`BuildContext::use_effect`] — keep what it needs between rebuilds. They are matched to
//! their values by the order they are called in, so they are called **unconditionally and in
//! the same order** every time: never inside an `if`, a loop or a closure.
//!
//! ```
//! use frus_widgets::{button, column, text, BuildContext, StatelessWidget, Widget};
//!
//! fn counter(cx: &BuildContext) -> Box<dyn Widget> {
//!     let count = cx.use_state(|| 0);
//!     let add = count.clone();
//!     Box::new(column![
//!         text(format!("{}", count.get())),
//!         button("+", move || add.update(|n| *n += 1)),
//!     ])
//! }
//!
//! let widget = counter.into_widget();
//! # let _ = widget;
//! ```
//!
//! ## Where a state lives
//!
//! A state is found again by **where its widget sits**: the same place in the tree, the
//! same kind of widget. Give a widget a key ([`Component::with_key`], or `keyed(..)`
//! around it) and it is found by the key instead, wherever its siblings move it. A widget
//! that is no longer built in a frame that rebuilt the tree is disposed at the end of that
//! frame.

use std::any::{Any, TypeId};
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::rc::Rc;

use frus_core::{Rect, Scene};
use frus_layout::Style;

use crate::callback::Callback;
use crate::interaction::{Status, WidgetId};
use crate::runtime::Runtime;
use crate::theme::Theme;
use crate::widget::Widget;

// ---------------------------------------------------------------------------------------
// Asking for a rebuild
// ---------------------------------------------------------------------------------------

thread_local! {
    static REBUILD: Cell<bool> = const { Cell::new(false) };
    static DEPTH: Cell<u32> = const { Cell::new(0) };
    static INTERVALS: RefCell<Vec<Interval>> = const { RefCell::new(Vec::new()) };
    static BACK_BLOCKS: Cell<u32> = const { Cell::new(0) };
}

// Every access to these goes through a function that is neither generic nor inlined, and so is
// compiled once, here. A generic function is compiled into the application that uses it, and a
// hot patch of the application carries its own copy of every thread-local such a function reads
// directly: fresh, and apart from the one the rest of frus holds (milestone 669).

/// How many components deep the expansion is, as `Deeper` keeps it.
#[inline(never)]
fn depth() -> u32 {
    DEPTH.with(|d| d.get())
}

/// Adds a timer to the latest build's.
#[inline(never)]
fn push_interval(interval: Interval) {
    INTERVALS.with(|intervals| intervals.borrow_mut().push(interval));
}

/// Whether some component of the latest build has said that the back gesture and the back
/// button are not for the router to answer — an open menu or dialog is what they close first.
/// See [`BuildContext::block_back`].
#[inline(never)]
pub fn back_blocked() -> bool {
    BACK_BLOCKS.with(|blocks| blocks.get() > 0)
}

/// A timer a component asked for with [`BuildContext::use_interval`].
#[derive(Clone)]
pub struct Interval {
    /// What tells this timer from the others, and the same one from one build to the next: it
    /// is what the shell diffs to start a timer, keep it running, and stop it.
    pub id: u64,
    /// How often it fires.
    pub period: std::time::Duration,
    /// What it does when it does.
    pub callback: Callback,
}

/// The timers the components of the latest build asked for. The shell starts the ones it is not
/// running and stops the ones no longer here.
#[inline(never)]
pub fn intervals() -> Vec<Interval> {
    INTERVALS.with(|intervals| intervals.borrow().clone())
}

/// Asks the shell to rebuild the tree on its next frame. Anything that changed what a
/// component would build — [`StateHandle::set_state`], a hook's `set`, a controller —
/// calls this; an application rarely does.
#[inline(never)]
pub fn request_rebuild() {
    REBUILD.with(|flag| flag.set(true));
}

/// Whether a rebuild has been asked for and not yet taken. Asking does not consume it.
#[inline(never)]
pub fn rebuild_requested() -> bool {
    REBUILD.with(|flag| flag.get())
}

/// Whether a rebuild was asked for since the last time this was called, and forgets it.
/// The shell reads this at the top of every frame.
#[inline(never)]
pub fn take_rebuild_request() -> bool {
    REBUILD.with(|flag| flag.replace(false))
}

/// How many components deep the transparent chain being expanded is. A component that
/// builds another component *directly* is the same place in the tree as it, so they are
/// told apart by this.
struct Deeper(u32);

impl Deeper {
    #[inline(never)]
    fn enter() -> Self {
        let now = DEPTH.with(|d| d.get());
        DEPTH.with(|d| d.set(now + 1));
        Deeper(now)
    }
}

impl Drop for Deeper {
    #[inline(never)]
    fn drop(&mut self) {
        DEPTH.with(|d| d.set(self.0));
    }
}

// ---------------------------------------------------------------------------------------
// The store
// ---------------------------------------------------------------------------------------

/// Where one component's state is found: its place in the tree, and how far down a chain of
/// components that place is.
type StateKey = (WidgetId, u32);

/// What every component's state, and every hook's, is kept in between rebuilds. It lives in
/// the [`Runtime`], under the place of the component that owns it.
#[derive(Default)]
pub struct StateStore {
    entries: RefCell<HashMap<StateKey, Entry>>,
    /// Counts the rebuilds. What a rebuild does not touch, it has left behind.
    epoch: Cell<u64>,
    /// Whether a rebuild has run since the last sweep.
    building: Cell<bool>,
    effects: RefCell<Vec<PendingEffect>>,
    services: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
    /// What a restart handed over and no component has taken yet: by place, then type name.
    restoring: RefCell<HashMap<(StateKey, String), String>>,
}

struct Entry {
    kind: TypeId,
    epoch: u64,
    state: Option<Rc<dyn Any>>,
    hooks: Rc<Hooks>,
    dispose: Option<Box<dyn FnOnce()>>,
    /// What [`State::save`] says, for a restart; `None` for hooks.
    save: Option<Saver>,
}

/// A state's type name and its [`State::save`], reached without its type.
struct Saver {
    name: &'static str,
    save: Box<dyn Fn() -> Option<String>>,
}

impl Entry {
    fn dispose_all(self) {
        if let Some(dispose) = self.dispose {
            dispose();
        }
        self.hooks.dispose();
    }
}

/// Work that undoes what an effect did.
type Cleanup = Box<dyn FnOnce()>;

struct PendingEffect {
    hooks: Rc<Hooks>,
    index: usize,
    run: Box<dyn FnOnce() -> Option<Cleanup>>,
}

impl StateStore {
    /// A rebuild of the tree is about to run. Every state it reaches is marked as reached.
    #[inline(never)]
    pub fn begin_build(&self) {
        self.epoch.set(self.epoch.get() + 1);
        self.building.set(true);
        // Each build says which timers it wants, and what stands in the way of going back,
        // from scratch.
        INTERVALS.with(|intervals| intervals.borrow_mut().clear());
        BACK_BLOCKS.with(|blocks| blocks.set(0));
    }

    /// The frame is done laying out: the states a rebuild did not reach are disposed, and
    /// the effects it asked for run.
    ///
    /// Effects run *after* the tree is built and laid out, so that what they do — start a
    /// timer, read a controller, ask for another rebuild — never happens in the middle of
    /// building.
    pub fn end_frame(&self) {
        if self.building.replace(false) {
            self.sweep();
        }
        self.flush_effects();
    }

    /// What every live state that opts in ([`State::save`]) wants kept across a restart, as
    /// text: a line a state, its place, its type and what it saved.
    ///
    /// `frus run` asks for this just before it stops the application to start a new build,
    /// and hands it to [`StateStore::restore_from`] in the new one. A state is given back what
    /// it saved only by the component at the same place, of the same type.
    pub fn snapshot(&self) -> String {
        let mut lines: Vec<String> = self
            .entries
            .borrow()
            .iter()
            .filter_map(|((id, depth), entry)| {
                let saver = entry.save.as_ref()?;
                let saved = (saver.save)()?;
                Some(format!(
                    "{:x}\t{depth}\t{}\t{}",
                    id.as_u64(),
                    saver.name,
                    escape(&saved)
                ))
            })
            .collect();
        lines.sort();
        lines.join("\n")
    }

    /// Takes a [`StateStore::snapshot`]: each state it holds is given back to the component
    /// that mounts first at its place, with its type.
    pub fn restore_from(&self, snapshot: &str) {
        let mut restoring = self.restoring.borrow_mut();
        for line in snapshot.lines() {
            let mut fields = line.splitn(4, '\t');
            let (Some(id), Some(depth), Some(name), Some(saved)) =
                (fields.next(), fields.next(), fields.next(), fields.next())
            else {
                continue;
            };
            let (Ok(id), Ok(depth)) = (u64::from_str_radix(id, 16), depth.parse::<u32>()) else {
                continue;
            };
            restoring.insert(
                ((WidgetId::from_u64(id), depth), name.to_string()),
                unescape(saved),
            );
        }
    }

    /// Makes `value` available to every component below as a service: the way an
    /// application-wide object — a router, a repository — is reached from a `build`.
    pub fn provide<T: 'static>(&self, value: Rc<T>) {
        self.services.borrow_mut().insert(TypeId::of::<T>(), value);
    }

    /// The service of type `T`, if one was provided.
    pub fn service<T: 'static>(&self) -> Option<Rc<T>> {
        self.services
            .borrow()
            .get(&TypeId::of::<T>())
            .and_then(|s| s.clone().downcast::<T>().ok())
    }

    /// How many components currently hold state. For tests and diagnostics.
    pub fn len(&self) -> usize {
        self.entries.borrow().len()
    }

    /// Whether no component holds any state.
    pub fn is_empty(&self) -> bool {
        self.entries.borrow().is_empty()
    }

    fn sweep(&self) {
        let epoch = self.epoch.get();
        let stale: Vec<Entry> = {
            let mut entries = self.entries.borrow_mut();
            let keys: Vec<StateKey> = entries
                .iter()
                .filter(|(_, entry)| entry.epoch < epoch)
                .map(|(key, _)| *key)
                .collect();
            keys.into_iter()
                .filter_map(|key| entries.remove(&key))
                .collect()
        };
        for entry in stale {
            entry.dispose_all();
        }
    }

    fn flush_effects(&self) {
        let pending: Vec<PendingEffect> = std::mem::take(&mut *self.effects.borrow_mut());
        for effect in pending {
            if effect.hooks.disposed.get() {
                continue;
            }
            let previous = effect.hooks.take_cleanup(effect.index);
            if let Some(cleanup) = previous {
                cleanup();
            }
            let cleanup = (effect.run)();
            effect.hooks.set_cleanup(effect.index, cleanup);
        }
    }

    /// The hooks of the component at `key`, made if it has none yet. A component of a
    /// different kind that was there is disposed: the place is the same, the widget is not.
    fn hooks_for(&self, key: StateKey, kind: TypeId) -> Rc<Hooks> {
        let stale = {
            let mut entries = self.entries.borrow_mut();
            match entries.get_mut(&key) {
                Some(entry) if entry.kind == kind => {
                    entry.epoch = self.epoch.get();
                    return entry.hooks.clone();
                }
                Some(_) => entries.remove(&key),
                None => None,
            }
        };
        if let Some(stale) = stale {
            stale.dispose_all();
        }
        let hooks = Rc::new(Hooks::default());
        self.entries.borrow_mut().insert(
            key,
            Entry {
                kind,
                epoch: self.epoch.get(),
                state: None,
                hooks: hooks.clone(),
                dispose: None,
                save: None,
            },
        );
        hooks
    }

    /// The state of the stateful widget at `key`: found if there is one, created if not.
    /// The widget that was there before comes back with a state that already existed.
    fn mount<W: StatefulWidget>(&self, key: StateKey, widget: Rc<W>) -> Mounted<W> {
        let kind = TypeId::of::<W>();
        let found = {
            let mut entries = self.entries.borrow_mut();
            entries
                .get_mut(&key)
                .filter(|entry| entry.kind == kind)
                .map(|entry| {
                    entry.epoch = self.epoch.get();
                    (entry.state.clone(), entry.hooks.clone())
                })
        };
        if let Some((Some(state), hooks)) = found {
            let cell = state
                .downcast::<StateCell<W::State>>()
                .unwrap_or_else(|_| unreachable!("an entry's kind says what its state is"));
            let previous = std::mem::replace(&mut *cell.widget.borrow_mut(), widget);
            return Mounted {
                cell,
                hooks,
                previous: Some(previous),
            };
        }
        let stale = self.entries.borrow_mut().remove(&key);
        if let Some(stale) = stale {
            stale.dispose_all();
        }
        let cell = Rc::new(StateCell {
            state: RefCell::new(widget.create_state()),
            widget: RefCell::new(widget),
            mounted: Cell::new(true),
        });
        // A restart handed over what this state saved: given back before `init_state`.
        let name = std::any::type_name::<W::State>();
        let saved = self.restoring.borrow_mut().remove(&(key, name.to_string()));
        if let Some(saved) = saved {
            cell.state.borrow_mut().restore(&saved);
        }
        let hooks = Rc::new(Hooks::default());
        let leaving = cell.clone();
        let saving = cell.clone();
        self.entries.borrow_mut().insert(
            key,
            Entry {
                kind,
                epoch: self.epoch.get(),
                state: Some(cell.clone() as Rc<dyn Any>),
                hooks: hooks.clone(),
                dispose: Some(Box::new(move || {
                    leaving.mounted.set(false);
                    if let Ok(mut state) = leaving.state.try_borrow_mut() {
                        state.dispose();
                    }
                })),
                save: Some(Saver {
                    name,
                    save: Box::new(move || saving.state.try_borrow().ok()?.save()),
                }),
            },
        );
        Mounted {
            cell,
            hooks,
            previous: None,
        }
    }
}

struct Mounted<W: StatefulWidget> {
    cell: Rc<StateCell<W::State>>,
    hooks: Rc<Hooks>,
    previous: Option<Rc<W>>,
}

/// A saved state on one line of a snapshot: `\\`, tabs and line breaks escaped.
fn escape(text: &str) -> String {
    text.replace('\\', "\\\\")
        .replace('\t', "\\t")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
}

fn unescape(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('t') => out.push('\t'),
            Some('n') => out.push('\n'),
            Some('r') => out.push('\r'),
            Some(other) => out.push(other),
            None => out.push('\\'),
        }
    }
    out
}

// ---------------------------------------------------------------------------------------
// Hooks
// ---------------------------------------------------------------------------------------

const ORDER: &str = "hooks were called in a different order than on the last build: call every \
                     hook unconditionally, in the same order, never inside an `if`, a loop or a \
                     closure";

#[derive(Default)]
struct Hooks {
    slots: RefCell<Vec<Slot>>,
    disposed: Cell<bool>,
}

enum Slot {
    Value(Rc<dyn Any>),
    Effect {
        deps: Box<dyn Any>,
        cleanup: Option<Cleanup>,
    },
}

impl Hooks {
    /// The value in slot `index`, made by `init` the first time.
    fn value<T: 'static>(&self, index: usize, init: impl FnOnce() -> T) -> Rc<T> {
        let existing = self.slots.borrow().get(index).map(|slot| match slot {
            Slot::Value(value) => Some(value.clone()),
            Slot::Effect { .. } => None,
        });
        match existing {
            Some(Some(value)) => value.downcast::<T>().unwrap_or_else(|_| panic!("{ORDER}")),
            Some(None) => panic!("{ORDER}"),
            None => {
                let value = Rc::new(init());
                let mut slots = self.slots.borrow_mut();
                assert_eq!(slots.len(), index, "{ORDER}");
                slots.push(Slot::Value(value.clone() as Rc<dyn Any>));
                value
            }
        }
    }

    fn take_cleanup(&self, index: usize) -> Option<Cleanup> {
        match self.slots.borrow_mut().get_mut(index) {
            Some(Slot::Effect { cleanup, .. }) => cleanup.take(),
            _ => None,
        }
    }

    fn set_cleanup(&self, index: usize, cleanup: Option<Cleanup>) {
        if let Some(Slot::Effect { cleanup: slot, .. }) = self.slots.borrow_mut().get_mut(index) {
            *slot = cleanup;
        }
    }

    fn dispose(&self) {
        self.disposed.set(true);
        let cleanups: Vec<Cleanup> = self
            .slots
            .borrow_mut()
            .iter_mut()
            .filter_map(|slot| match slot {
                Slot::Effect { cleanup, .. } => cleanup.take(),
                Slot::Value(_) => None,
            })
            .collect();
        for cleanup in cleanups {
            cleanup();
        }
    }
}

/// What an effect may hand back: nothing, or the work that undoes it.
pub trait IntoCleanup {
    /// The cleanup, if there is one.
    fn into_cleanup(self) -> Option<Box<dyn FnOnce()>>;
}

impl IntoCleanup for () {
    fn into_cleanup(self) -> Option<Cleanup> {
        None
    }
}

impl<F: FnOnce() + 'static> IntoCleanup for F {
    fn into_cleanup(self) -> Option<Cleanup> {
        Some(Box::new(self))
    }
}

/// A value kept between rebuilds by [`BuildContext::use_state`]. Changing it asks for a
/// rebuild; reading it does not.
///
/// Cloning a `UseState` clones the *handle*: every clone reads and writes the same value,
/// which is what lets a handler own one.
pub struct UseState<T> {
    cell: Rc<RefCell<T>>,
}

impl<T> Clone for UseState<T> {
    fn clone(&self) -> Self {
        Self {
            cell: self.cell.clone(),
        }
    }
}

impl<T: 'static> UseState<T> {
    /// A copy of the current value.
    pub fn get(&self) -> T
    where
        T: Clone,
    {
        self.cell.borrow().clone()
    }

    /// Reads the current value without copying it.
    pub fn with<R>(&self, read: impl FnOnce(&T) -> R) -> R {
        read(&self.cell.borrow())
    }

    /// Replaces the value, and asks for a rebuild.
    pub fn set(&self, value: T) {
        *self.cell.borrow_mut() = value;
        request_rebuild();
    }

    /// Changes the value in place, and asks for a rebuild.
    pub fn update(&self, change: impl FnOnce(&mut T)) {
        change(&mut self.cell.borrow_mut());
        request_rebuild();
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for UseState<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("UseState")
            .field(&*self.cell.borrow())
            .finish()
    }
}

/// A value kept between rebuilds by [`BuildContext::use_ref`]. Unlike [`UseState`],
/// changing it does *not* ask for a rebuild: it is for what the interface does not show.
pub struct UseRef<T> {
    cell: Rc<RefCell<T>>,
}

impl<T> Clone for UseRef<T> {
    fn clone(&self) -> Self {
        Self {
            cell: self.cell.clone(),
        }
    }
}

impl<T: 'static> UseRef<T> {
    /// A copy of the current value.
    pub fn get(&self) -> T
    where
        T: Clone,
    {
        self.cell.borrow().clone()
    }

    /// Reads the current value without copying it.
    pub fn with<R>(&self, read: impl FnOnce(&T) -> R) -> R {
        read(&self.cell.borrow())
    }

    /// Replaces the value.
    pub fn set(&self, value: T) {
        *self.cell.borrow_mut() = value;
    }

    /// Changes the value in place.
    pub fn update(&self, change: impl FnOnce(&mut T)) {
        change(&mut self.cell.borrow_mut());
    }
}

// ---------------------------------------------------------------------------------------
// BuildContext
// ---------------------------------------------------------------------------------------

/// What a component is told when it is built: where it is, under which theme, and where
/// its hooks keep their values.
pub struct BuildContext<'a> {
    key: StateKey,
    kind: TypeId,
    runtime: &'a Runtime,
    theme: &'a Theme,
    hooks: OnceCell<Rc<Hooks>>,
    cursor: Cell<usize>,
    intervals: Cell<usize>,
}

impl<'a> BuildContext<'a> {
    fn new(key: StateKey, kind: TypeId, runtime: &'a Runtime, theme: &'a Theme) -> Self {
        Self {
            key,
            kind,
            runtime,
            theme,
            hooks: OnceCell::new(),
            cursor: Cell::new(0),
            intervals: Cell::new(0),
        }
    }

    /// A context for a test that builds something by hand, under `theme`.
    #[cfg(test)]
    pub(crate) fn for_test(runtime: &'a Runtime, theme: &'a Theme) -> Self {
        Self::new((WidgetId::ROOT, 0), TypeId::of::<()>(), runtime, theme)
    }

    /// The theme this component is built under.
    pub fn theme(&self) -> &Theme {
        self.theme
    }

    /// Where in the tree this component sits.
    pub fn id(&self) -> WidgetId {
        self.key.0
    }

    /// The runtime the tree is being built for.
    pub fn runtime(&self) -> &Runtime {
        self.runtime
    }

    /// An application-wide object provided with [`StateStore::provide`] — a router, say.
    pub fn service<T: 'static>(&self) -> Option<Rc<T>> {
        self.runtime.states.service::<T>()
    }

    fn hooks(&self) -> Rc<Hooks> {
        self.hooks
            .get_or_init(|| self.runtime.states.hooks_for(self.key, self.kind))
            .clone()
    }

    fn next_slot(&self) -> usize {
        let slot = self.cursor.get();
        self.cursor.set(slot + 1);
        slot
    }

    /// A value that lives as long as this component does, and that asks for a rebuild when
    /// it changes. `init` makes it the first time and is not called again.
    ///
    /// ```
    /// # use frus_widgets::{text, BuildContext, Widget};
    /// fn label(cx: &BuildContext) -> Box<dyn Widget> {
    ///     let taps = cx.use_state(|| 0);
    ///     taps.set(taps.get() + 1);
    ///     Box::new(text(format!("{}", taps.get())))
    /// }
    /// ```
    pub fn use_state<T: 'static>(&self, init: impl FnOnce() -> T) -> UseState<T> {
        let cell = self
            .hooks()
            .value(self.next_slot(), || RefCell::new(init()));
        UseState { cell }
    }

    /// A value that lives as long as this component does and does *not* ask for a
    /// rebuild when it changes.
    pub fn use_ref<T: 'static>(&self, init: impl FnOnce() -> T) -> UseRef<T> {
        let cell = self
            .hooks()
            .value(self.next_slot(), || RefCell::new(init()));
        UseRef { cell }
    }

    /// `compute()`, kept until `deps` change. The work is not repeated on a rebuild that
    /// changes nothing it depends on.
    pub fn use_memo<D: PartialEq + 'static, T: 'static>(
        &self,
        deps: D,
        compute: impl FnOnce() -> T,
    ) -> Rc<T> {
        let memo = self
            .hooks()
            .value(self.next_slot(), || RefCell::new(None::<(D, Rc<T>)>));
        let mut memo = memo.borrow_mut();
        match memo.as_ref() {
            Some((previous, value)) if *previous == deps => value.clone(),
            _ => {
                let value = Rc::new(compute());
                *memo = Some((deps, value.clone()));
                value
            }
        }
    }

    /// Calls `on_tick` every `period`, for as long as this component asks for it.
    ///
    /// It asks again on every build: a build that does not call this any more stops the timer,
    /// and a build that calls it with another `period` starts a new one. So, unlike the other
    /// hooks, it may be called conditionally — a timer that is only wanted while something is on
    /// is `if on { cx.use_interval(..) }`.
    ///
    /// `on_tick` runs on the interface's thread, like any other handler, so it may change
    /// state: `cx.use_interval(period, cx.callback(|state| state.seconds += 1))`.
    ///
    /// ```
    /// # use std::time::Duration;
    /// # use frus_widgets::{text, BuildContext, Widget};
    /// fn clock(cx: &BuildContext) -> Box<dyn Widget> {
    ///     let seconds = cx.use_state(|| 0);
    ///     let tick = seconds.clone();
    ///     cx.use_interval(Duration::from_secs(1), move || tick.update(|s| *s += 1));
    ///     Box::new(text(format!("{}s", seconds.get())))
    /// }
    /// ```
    pub fn use_interval(&self, period: std::time::Duration, on_tick: impl Into<Callback>) {
        let index = self.intervals.get();
        self.intervals.set(index + 1);
        let id = {
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
            (self.key.0.as_u64(), self.key.1, index, period.as_millis()).hash(&mut hasher);
            hasher.finish()
        };
        push_interval(Interval {
            id,
            period,
            callback: on_tick.into(),
        });
    }

    /// Says, for this build, whether something this component shows — a menu, a dialog, a
    /// drawer — should take the back gesture and the back button before the router does.
    /// While any component says `true`, the router is not asked to go back.
    ///
    /// Like [`use_interval`](Self::use_interval) it is asked again on every build and may be
    /// called conditionally: `cx.block_back(self.menu_open)`.
    #[inline(never)]
    pub fn block_back(&self, blocked: bool) {
        if blocked {
            BACK_BLOCKS.with(|blocks| blocks.set(blocks.get() + 1));
        }
    }

    /// Work to do *after* the tree is built — start a timer, subscribe, read a controller —
    /// run again whenever `deps` change, not otherwise. Pass `()` to run it once.
    ///
    /// The work may return a closure, which undoes it: it runs before the next run and when
    /// the component leaves the tree.
    ///
    /// ```
    /// # use frus_widgets::{text, BuildContext, Widget};
    /// fn title(cx: &BuildContext) -> Box<dyn Widget> {
    ///     cx.use_effect((), || {
    ///         println!("mounted");
    ///         || println!("unmounted")
    ///     });
    ///     Box::new(text("hello"))
    /// }
    /// ```
    pub fn use_effect<D, C>(&self, deps: D, effect: impl FnOnce() -> C + 'static)
    where
        D: PartialEq + 'static,
        C: IntoCleanup,
    {
        let hooks = self.hooks();
        let index = self.next_slot();
        let changed = {
            let mut slots = hooks.slots.borrow_mut();
            match slots.get_mut(index) {
                None => {
                    assert_eq!(slots.len(), index, "{ORDER}");
                    slots.push(Slot::Effect {
                        deps: Box::new(deps),
                        cleanup: None,
                    });
                    true
                }
                Some(Slot::Effect { deps: old, .. }) => {
                    if old.downcast_ref::<D>().is_some_and(|old| *old == deps) {
                        false
                    } else {
                        *old = Box::new(deps);
                        true
                    }
                }
                Some(Slot::Value(_)) => panic!("{ORDER}"),
            }
        };
        if changed {
            self.runtime
                .states
                .effects
                .borrow_mut()
                .push(PendingEffect {
                    hooks,
                    index,
                    run: Box::new(move || effect().into_cleanup()),
                });
        }
    }
}

// ---------------------------------------------------------------------------------------
// StatelessWidget
// ---------------------------------------------------------------------------------------

/// A widget with nothing to remember: it says what it looks like from what it is
/// configured with, and from nothing else.
///
/// Any `Fn(&BuildContext) -> Box<dyn Widget>` is one, which is how a function becomes a
/// component — and, with hooks, one that remembers.
pub trait StatelessWidget: 'static {
    /// The widget this one stands for. Called whenever the tree is rebuilt.
    fn build(&self, cx: &BuildContext) -> Box<dyn Widget>;

    /// This component as a widget: what goes in a `column![..]`, a `Scaffold`'s body, a
    /// route's page.
    fn into_widget(self) -> Component
    where
        Self: Sized,
    {
        Component::stateless(self)
    }
}

impl<F> StatelessWidget for F
where
    F: Fn(&BuildContext) -> Box<dyn Widget> + 'static,
{
    fn build(&self, cx: &BuildContext) -> Box<dyn Widget> {
        self(cx)
    }
}

// ---------------------------------------------------------------------------------------
// StatefulWidget
// ---------------------------------------------------------------------------------------

/// A widget whose [`State`] outlives the rebuilds. The widget is only the configuration:
/// it is made again on every rebuild, and the state is what is kept.
pub trait StatefulWidget: 'static {
    /// What is kept.
    type State: State<Widget = Self>;

    /// Makes the state, once, when the widget first enters the tree.
    fn create_state(&self) -> Self::State;

    /// This component as a widget.
    fn into_widget(self) -> Component
    where
        Self: Sized,
    {
        Component::stateful(self)
    }
}

/// What a [`StatefulWidget`] keeps, and how it draws itself from it.
pub trait State: Sized + 'static {
    /// The widget this is the state of.
    type Widget: StatefulWidget<State = Self>;

    /// Called once, right after the state is made. Start what has to run for as long as
    /// the widget is there — a listener, a timer — here, and stop it in
    /// [`State::dispose`].
    fn init_state(&mut self, _cx: &StateContext<Self>) {}

    /// Called when the tree is rebuilt and the widget above changed, or was made again.
    /// `old` is the configuration it replaces; the new one is [`StateContext::widget`].
    fn did_update_widget(&mut self, _old: &Self::Widget, _cx: &StateContext<Self>) {}

    /// Called once, when the widget leaves the tree. The state is never used again.
    fn dispose(&mut self) {}

    /// What this state keeps across a **restart** under `frus run` (`R`, or `r`): the new
    /// build of the application starts with it, given back through [`State::restore`]. Any
    /// text will do — a number, a few fields joined, a JSON document.
    ///
    /// `None`, the default, keeps nothing: the state starts afresh, as on a first launch.
    /// Nothing is saved outside `frus run`.
    ///
    /// ```ignore
    /// fn save(&self) -> Option<String> {
    ///     Some(self.count.to_string())
    /// }
    ///
    /// fn restore(&mut self, saved: &str) {
    ///     self.count = saved.parse().unwrap_or(0);
    /// }
    /// ```
    fn save(&self) -> Option<String> {
        None
    }

    /// Takes back what [`State::save`] returned before a restart. Called once, right after
    /// [`StatefulWidget::create_state`] and before [`State::init_state`], and only for the
    /// component at the same place, of the same type. What no longer fits — the code changed
    /// in between — can simply be ignored.
    fn restore(&mut self, _saved: &str) {}

    /// The widget this state stands for. Called whenever the tree is rebuilt.
    ///
    /// It only *reads* the state. What a handler changes goes through
    /// [`StateContext::callback`] or [`StateContext::handle`]; changing the state from
    /// inside `build` itself panics, because a build that changes what it builds from
    /// never settles.
    fn build(&self, cx: &StateContext<Self>) -> Box<dyn Widget>;
}

pub(crate) struct StateCell<S: State> {
    state: RefCell<S>,
    widget: RefCell<Rc<S::Widget>>,
    mounted: Cell<bool>,
}

/// A way to reach a widget's state from outside its `build`: from a handler, a listener, a
/// timer. Cheap to clone.
pub struct StateHandle<S: State> {
    cell: Rc<StateCell<S>>,
}

impl<S: State> Clone for StateHandle<S> {
    fn clone(&self) -> Self {
        Self {
            cell: self.cell.clone(),
        }
    }
}

impl<S: State> StateHandle<S> {
    /// Changes the state, and asks for a rebuild.
    ///
    /// Does nothing once the widget has left the tree: a timer that outlives its widget
    /// finds nothing to change.
    pub fn set_state(&self, change: impl FnOnce(&mut S)) {
        if !self.cell.mounted.get() {
            return;
        }
        match self.cell.state.try_borrow_mut() {
            Ok(mut state) => change(&mut state),
            Err(_) => panic!(
                "set_state was called while the state was being read — from inside `build`, or \
                 from inside another `set_state`. Change state from a handler, not while building"
            ),
        }
        request_rebuild();
    }

    /// Reads the state.
    pub fn read<R>(&self, read: impl FnOnce(&S) -> R) -> R {
        read(&self.cell.state.borrow())
    }

    /// The widget's current configuration.
    pub fn widget(&self) -> Rc<S::Widget> {
        self.cell.widget.borrow().clone()
    }

    /// Whether the widget is still in the tree.
    pub fn is_mounted(&self) -> bool {
        self.cell.mounted.get()
    }

    /// A handler that changes the state, for anything that takes a [`Callback`].
    pub fn callback(&self, change: impl Fn(&mut S) + 'static) -> Callback {
        let handle = self.clone();
        Callback::new(move || handle.set_state(|state| change(state)))
    }

    /// A handler for a widget that reports a **value** — a field's text, a slider's position, a
    /// switch's new setting: `TextField::new(..).on_input(cx.handler(|s, text: String| s.name = text))`.
    ///
    /// It answers the value with a [`Callback`] that makes the change when it is delivered, which
    /// is what every widget's setter takes and what leaves no doubt about the message type — a
    /// closure that returns nothing could be a handler for any.
    pub fn handler<T: Clone + 'static>(
        &self,
        change: impl Fn(&mut S, T) + 'static,
    ) -> impl Fn(T) -> Callback + 'static {
        let handle = self.clone();
        let change = Rc::new(change);
        move |value| {
            let (handle, change) = (handle.clone(), change.clone());
            Callback::new(move || handle.set_state(|state| change(state, value.clone())))
        }
    }
}

/// What a [`State`] is told when it builds and when its lifecycle runs: everything a
/// [`BuildContext`] offers (this dereferences to one), and the state's own handle.
pub struct StateContext<'c, 'a, S: State> {
    cx: &'c BuildContext<'a>,
    cell: &'c Rc<StateCell<S>>,
}

impl<'a, S: State> Deref for StateContext<'_, 'a, S> {
    type Target = BuildContext<'a>;

    fn deref(&self) -> &BuildContext<'a> {
        self.cx
    }
}

impl<S: State> StateContext<'_, '_, S> {
    /// The widget's current configuration.
    pub fn widget(&self) -> Rc<S::Widget> {
        self.cell.widget.borrow().clone()
    }

    /// A handle to this state that a handler, a listener or a timer can own.
    pub fn handle(&self) -> StateHandle<S> {
        StateHandle {
            cell: self.cell.clone(),
        }
    }

    /// A handler that changes this state — [`StateHandle::callback`], from here.
    pub fn callback(&self, change: impl Fn(&mut S) + 'static) -> Callback {
        self.handle().callback(change)
    }

    /// A handler that changes this state from a value the widget reports —
    /// [`StateHandle::handler`], from here.
    pub fn handler<T: Clone + 'static>(
        &self,
        change: impl Fn(&mut S, T) + 'static,
    ) -> impl Fn(T) -> Callback + 'static {
        self.handle().handler(change)
    }
}

// ---------------------------------------------------------------------------------------
// The node
// ---------------------------------------------------------------------------------------

type Builder<Msg> = Box<dyn FnOnce(&BuildContext) -> Box<dyn Widget<Msg>>>;

/// A component in the tree: a widget that is built into another when the tree is.
///
/// It is transparent: once built it *is* the widget it built, the same box, the same
/// children, the same behaviour, so wrapping something in a component changes nothing about
/// where it lands. Made by [`StatelessWidget::into_widget`] and
/// [`StatefulWidget::into_widget`].
pub struct Component<Msg = Callback> {
    inner: LazyChild<Msg>,
    key: Option<u64>,
}

/// A stateless widget's `build` — looked up in the hot-patching table, by the method itself,
/// when frus is built for hot reload: the method is the application's code, which a patch
/// replaces, and the table answers for functions, not for closures frus made around them.
#[inline]
fn build_stateless<W: StatelessWidget>(widget: &W, cx: &BuildContext) -> Box<dyn Widget> {
    #[cfg(feature = "hot-reload")]
    {
        subsecond::HotFn::current(<W as StatelessWidget>::build).call((widget, cx))
    }
    #[cfg(not(feature = "hot-reload"))]
    {
        widget.build(cx)
    }
}

/// A state's `build`, the same way.
#[inline]
fn build_state<S: State>(state: &S, cx: &StateContext<S>) -> Box<dyn Widget> {
    #[cfg(feature = "hot-reload")]
    {
        subsecond::HotFn::current(<S as State>::build).call((state, cx))
    }
    #[cfg(not(feature = "hot-reload"))]
    {
        state.build(cx)
    }
}

impl Component<Callback> {
    /// A stateless component.
    pub fn stateless<W: StatelessWidget>(widget: W) -> Self {
        Self::from_builder(
            TypeId::of::<W>(),
            Box::new(move |cx: &BuildContext| build_stateless(&widget, cx)),
        )
    }

    /// A stateful component.
    pub fn stateful<W: StatefulWidget>(widget: W) -> Self {
        Self::from_builder(
            TypeId::of::<W>(),
            Box::new(move |cx: &BuildContext| {
                let Mounted {
                    cell,
                    hooks,
                    previous,
                } = cx.runtime.states.mount(cx.key, Rc::new(widget));
                let _ = cx.hooks.set(hooks);
                let state_cx = StateContext { cx, cell: &cell };
                match previous {
                    None => cell.state.borrow_mut().init_state(&state_cx),
                    Some(old) => cell.state.borrow_mut().did_update_widget(&old, &state_cx),
                }
                let built = build_state(&*cell.state.borrow(), &state_cx);
                built
            }),
        )
    }
}

impl<Msg> Component<Msg> {
    fn from_builder(kind: TypeId, build: Builder<Msg>) -> Self {
        Self {
            inner: LazyChild {
                kind,
                build: RefCell::new(Some(build)),
                built: OnceCell::new(),
                unbuilt: Unbuilt,
            },
            key: None,
        }
    }

    /// Gives this component an identity that does not depend on where it sits: its state
    /// follows the key when its siblings move.
    pub fn with_key(mut self, key: impl Hash) -> Self {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        key.hash(&mut hasher);
        self.key = Some(hasher.finish());
        self
    }

    /// A component is its child's box: nothing to add.
    fn restyle(&self, base: Style) -> Style {
        base
    }
}

/// The child a component builds, made the first time the tree reaches it.
struct LazyChild<Msg> {
    kind: TypeId,
    build: RefCell<Option<Builder<Msg>>>,
    built: OnceCell<Box<dyn Widget<Msg>>>,
    unbuilt: Unbuilt,
}

impl<Msg> LazyChild<Msg> {
    /// Builds the child if it has not been, then lets *it* expand: what it built may be a
    /// component too.
    fn expand(&self, id: WidgetId, runtime: &Runtime, theme: &Theme) {
        if self.built.get().is_none() {
            let build = self.build.borrow_mut().take();
            if let Some(build) = build {
                let cx = BuildContext::new((id, depth()), self.kind, runtime, theme);
                let child = build(&cx);
                let _ = self.built.set(child);
            }
        }
        if let Some(child) = self.built.get() {
            let _deeper = Deeper::enter();
            child.expand(id, runtime, theme);
        }
    }

    fn build_in(&self, id: WidgetId, runtime: &Runtime, theme: &Theme) {
        if let Some(child) = self.built.get() {
            child.build_in(id, runtime, theme);
        }
    }

    fn build_themed(&self, theme: &Theme) {
        if let Some(child) = self.built.get() {
            child.build_themed(theme);
        }
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        match self.built.get() {
            Some(child) => child.children(),
            None => {
                #[cfg(debug_assertions)]
                if self.build.borrow().is_some() {
                    panic!(
                        "a component's children were read before it was built: a traversal \
                         reached this tree before the walk that builds components did. Call \
                         `build_deferred(tree, &theme, &runtime)` on it first"
                    );
                }
                &[]
            }
        }
    }
}

impl<Msg> Deref for LazyChild<Msg> {
    type Target = dyn Widget<Msg>;

    fn deref(&self) -> &(dyn Widget<Msg> + 'static) {
        match self.built.get() {
            Some(child) => child.as_ref(),
            None => &self.unbuilt,
        }
    }
}

/// What a component answers as before it is built: nothing.
struct Unbuilt;

impl<Msg> Widget<Msg> for Unbuilt {
    fn style(&self) -> Style {
        Style::default()
    }

    fn children(&self) -> &[Box<dyn Widget<Msg>>] {
        &[]
    }

    fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {}

    fn on_click(&self) -> Option<Msg> {
        None
    }

    fn debug_name(&self) -> &'static str {
        "Component"
    }
}

crate::transparent::forward_transparent!(Component {
    /// A component's key is its own and never its child's: the parent reads it to place
    /// the component *before* the component has been built, and an answer that changed
    /// when the child arrived would move the place under the state that lives there.
    fn key(&self) -> Option<u64> {
        self.key
    }

    fn positioned(&self) -> Option<crate::positioned::Positioning> {
        self.inner.positioned()
    }

    fn theme_override(
        &self,
        inherited: &crate::theme::Theme,
    ) -> Option<Box<crate::theme::Theme>> {
        self.inner.theme_override(inherited)
    }

    fn media_override(&self, inherited: crate::MediaQuery) -> Option<crate::MediaQuery> {
        self.inner.media_override(inherited)
    }

    fn scaffold_override(&self) -> Option<crate::ScaffoldInfo> {
        self.inner.scaffold_override()
    }
    fn scroll_behavior_override(&self) -> Option<crate::ScrollBehavior> {
        self.inner.scroll_behavior_override()
    }

    fn autofill_group(&self) -> bool {
        self.inner.autofill_group()
    }
    /// Forwarded: the area's bar is the area's, whatever wraps it.
    fn area_toolbar(
        &self,
        context: crate::ToolbarContext,
    ) -> Option<Option<&dyn crate::widget::Widget<Msg>>> {
        self.inner.area_toolbar(context)
    }
});

/// A component made of a function: `component(|cx| …)`. The closure is called whenever the
/// tree is rebuilt, and may call hooks.
///
/// ```
/// use frus_widgets::{component, text};
///
/// let clock = component(|cx| {
///     let ticks = cx.use_state(|| 0);
///     Box::new(text(format!("{} ticks", ticks.get())))
/// });
/// # let _ = clock;
/// ```
pub fn component(build: impl Fn(&BuildContext) -> Box<dyn Widget> + 'static) -> Component {
    Component::stateless(build)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{build_deferred, keyed, Container, Flex};
    use frus_layout::Dimension;

    type Builder = Rc<dyn Fn(&BuildContext) -> Box<dyn Widget>>;
    type Log = Rc<RefCell<Vec<String>>>;
    type Handle = Rc<RefCell<Option<StateHandle<LifeState>>>>;

    fn log() -> Log {
        Rc::new(RefCell::new(Vec::new()))
    }

    fn taken(log: &Log) -> Vec<String> {
        std::mem::take(&mut *log.borrow_mut())
    }

    /// One frame of the shell's, less the drawing: the tree is built, and what it did not
    /// reach is let go.
    fn frame(runtime: &Runtime, root: &dyn Widget) {
        runtime.states.begin_build();
        build_deferred(root, &Theme::default(), runtime);
        runtime.states.end_frame();
    }

    /// A stateful widget that says what happens to it.
    struct Life {
        tag: u32,
        log: Log,
        out: Handle,
    }

    struct LifeState {
        log: Log,
        out: Handle,
        count: i32,
    }

    impl StatefulWidget for Life {
        type State = LifeState;
        fn create_state(&self) -> LifeState {
            LifeState {
                log: self.log.clone(),
                out: self.out.clone(),
                count: 0,
            }
        }
    }

    impl State for LifeState {
        type Widget = Life;
        fn init_state(&mut self, cx: &StateContext<Self>) {
            self.log
                .borrow_mut()
                .push(format!("init {}", cx.widget().tag));
            *self.out.borrow_mut() = Some(cx.handle());
        }
        fn did_update_widget(&mut self, old: &Life, cx: &StateContext<Self>) {
            self.log
                .borrow_mut()
                .push(format!("update {}->{}", old.tag, cx.widget().tag));
        }
        fn dispose(&mut self) {
            self.log.borrow_mut().push("dispose".to_string());
        }
        fn build(&self, _cx: &StateContext<Self>) -> Box<dyn Widget> {
            Box::new(Container::new().width(10.0 + self.count as f32).height(4.0))
        }
    }

    fn life(tag: u32, log: &Log, out: &Handle) -> Component {
        Life {
            tag,
            log: log.clone(),
            out: out.clone(),
        }
        .into_widget()
    }

    fn handle() -> Handle {
        Rc::new(RefCell::new(None))
    }

    fn width(widget: &dyn Widget) -> Dimension {
        widget.style().width
    }

    /// A counter that keeps its count across a restart.
    struct Kept;

    struct KeptState {
        count: i32,
        seen_at_init: Option<i32>,
    }

    impl StatefulWidget for Kept {
        type State = KeptState;
        fn create_state(&self) -> KeptState {
            KeptState {
                count: 0,
                seen_at_init: None,
            }
        }
    }

    impl State for KeptState {
        type Widget = Kept;
        fn init_state(&mut self, _cx: &StateContext<Self>) {
            self.seen_at_init = Some(self.count);
        }
        fn save(&self) -> Option<String> {
            Some(format!("{}\tline two\n\\", self.count))
        }
        fn restore(&mut self, saved: &str) {
            assert!(saved.ends_with("\tline two\n\\"), "{saved:?}");
            self.count = saved.split('\t').next().unwrap().parse().unwrap();
        }
        fn build(&self, _cx: &StateContext<Self>) -> Box<dyn Widget> {
            Box::new(Container::new().width(10.0 + self.count as f32).height(4.0))
        }
    }

    /// What a state saves comes back to the component at the same place in the next build of
    /// the application — before its `init_state` — and a state that saves nothing is left out.
    #[test]
    fn kept_states_cross_a_restart() {
        let before = Runtime::default();
        let (log, out) = (log(), handle());
        let tree = || -> Box<dyn Widget> {
            Box::new(crate::column![Kept.into_widget(), life(1, &log, &out)])
        };
        let root = tree();
        frame(&before, root.as_ref());
        let kept = before
            .states
            .entries
            .borrow()
            .values()
            .find_map(|entry| entry.state.clone()?.downcast::<StateCell<KeptState>>().ok())
            .unwrap();
        kept.state.borrow_mut().count = 7;
        let snapshot = before.states.snapshot();
        assert_eq!(
            snapshot.lines().count(),
            1,
            "only the state that saves: {snapshot}"
        );

        let after = Runtime::default();
        after.states.restore_from(&snapshot);
        let root = tree();
        frame(&after, root.as_ref());
        let restored = after
            .states
            .entries
            .borrow()
            .values()
            .find_map(|entry| entry.state.clone()?.downcast::<StateCell<KeptState>>().ok())
            .unwrap();
        let state = restored.state.borrow();
        assert_eq!(state.count, 7);
        assert_eq!(state.seen_at_init, Some(7), "restored before init_state");
        assert!(after.states.restoring.borrow().is_empty(), "taken once");
    }

    #[test]
    fn saved_text_survives_escaping() {
        for text in [
            "plain",
            "tab\there",
            "two\nlines",
            "back\\slash",
            "\\n literally",
            "",
        ] {
            assert_eq!(unescape(&escape(text)), text);
            assert!(!escape(text).contains(['\n', '\t']));
        }
    }

    #[test]
    fn a_stateless_component_is_the_widget_it_builds() {
        let runtime = Runtime::default();
        let root = component(|_| Box::new(Container::new().width(120.0).height(30.0)));
        frame(&runtime, &root);
        assert_eq!(width(&root), Dimension::Length(120.0));
        assert_eq!(root.style().height, Dimension::Length(30.0));
    }

    #[test]
    fn a_state_is_made_once_and_survives_rebuilds() {
        let (runtime, log, out) = (Runtime::default(), log(), handle());
        let first = life(1, &log, &out);
        frame(&runtime, &first);
        assert_eq!(taken(&log), ["init 1"]);
        assert_eq!(width(&first), Dimension::Length(10.0));

        // the state is changed from outside, as a handler does
        out.borrow().as_ref().unwrap().set_state(|s| s.count = 5);
        assert!(take_rebuild_request(), "set_state asks for a rebuild");

        let second = life(2, &log, &out);
        frame(&runtime, &second);
        assert_eq!(
            taken(&log),
            ["update 1->2"],
            "the same place, the same kind: the state is kept and told what changed"
        );
        assert_eq!(
            width(&second),
            Dimension::Length(15.0),
            "and it is the kept one"
        );
    }

    #[test]
    fn a_handler_carries_the_value_a_widget_reports_into_the_state() {
        let (runtime, log, out) = (Runtime::default(), log(), handle());
        frame(&runtime, &life(1, &log, &out));
        let handle = out.borrow().clone().unwrap();
        let on_value = handle.handler(|s, by: i32| s.count += by);
        let (three, four) = (on_value(3), on_value(4));
        assert_eq!(
            handle.read(|s| s.count),
            0,
            "nothing changes until it is delivered"
        );
        three.call();
        four.call();
        four.call();
        assert_eq!(
            handle.read(|s| s.count),
            11,
            "each delivery makes the change"
        );
        assert!(take_rebuild_request(), "and it asks for the rebuild");
    }

    #[test]
    fn a_component_that_blocks_back_does_so_for_one_build_only() {
        let runtime = Runtime::default();
        let open = Rc::new(Cell::new(true));
        let asked = open.clone();
        let root = component(move |cx| {
            cx.block_back(asked.get());
            Box::new(Container::new().width(4.0).height(4.0))
        });
        frame(&runtime, &root);
        assert!(back_blocked(), "an open menu is in the way");
        open.set(false);
        frame(&runtime, &root);
        assert!(!back_blocked(), "each build says it afresh");
    }

    #[test]
    fn a_state_is_disposed_when_a_rebuild_no_longer_reaches_it() {
        let (runtime, log, out) = (Runtime::default(), log(), handle());
        frame(&runtime, &Flex::column().child(life(1, &log, &out)));
        taken(&log);
        assert_eq!(runtime.states.len(), 1);

        frame(&runtime, &Flex::column().child(Container::new()));
        assert_eq!(taken(&log), ["dispose"]);
        assert!(runtime.states.is_empty());
        let handle = out.borrow().clone().unwrap();
        assert!(!handle.is_mounted());
        take_rebuild_request();
        handle.set_state(|s| s.count = 9);
        assert!(
            !take_rebuild_request(),
            "a state that has left cannot ask for a rebuild"
        );
    }

    #[test]
    fn a_different_kind_of_widget_in_the_same_place_starts_over() {
        let (runtime, log, out) = (Runtime::default(), log(), handle());
        frame(&runtime, &Flex::column().child(life(1, &log, &out)));
        taken(&log);
        // a stateless component that keeps hooks takes the place the state had
        let other = component(|cx| {
            cx.use_state(|| 0u8);
            Box::new(Container::new())
        });
        frame(&runtime, &Flex::column().child(other));
        assert_eq!(
            taken(&log),
            ["dispose"],
            "the old kind is disposed, not reused"
        );
    }

    #[test]
    fn a_key_carries_the_state_wherever_the_siblings_go() {
        let (runtime, log) = (Runtime::default(), log());
        let (a, b) = (handle(), handle());
        let column = |order: [u32; 2]| {
            let mut column = Flex::column();
            for tag in order {
                let out = if tag == 1 { &a } else { &b };
                column = column.child(keyed(tag, life(tag, &log, out)));
            }
            column
        };
        frame(&runtime, &column([1, 2]));
        a.borrow().as_ref().unwrap().set_state(|s| s.count = 1);
        b.borrow().as_ref().unwrap().set_state(|s| s.count = 2);
        taken(&log);

        frame(&runtime, &column([2, 1]));
        let counts = |h: &Handle| h.borrow().as_ref().unwrap().read(|s| s.count);
        assert_eq!(
            (counts(&a), counts(&b)),
            (1, 2),
            "each state stayed with its key"
        );
        assert_eq!(runtime.states.len(), 2);
        assert!(
            !taken(&log)
                .iter()
                .any(|line| line == "dispose" || line.starts_with("init")),
            "and neither was made again or let go"
        );
    }

    #[test]
    fn a_component_that_builds_a_component_keeps_both_states() {
        let (runtime, log, out) = (Runtime::default(), log(), handle());
        let (inner_log, inner_out) = (log.clone(), out.clone());
        let outer = component(move |cx| {
            cx.use_state(|| 0);
            // built *directly*: the same place in the tree as this component
            Box::new(life(7, &inner_log, &inner_out))
        });
        frame(&runtime, &outer);
        assert_eq!(
            runtime.states.len(),
            2,
            "one for the hooks, one for the state"
        );
        assert_eq!(taken(&log), ["init 7"]);
    }

    #[test]
    fn hooks_keep_their_values_between_builds() {
        let runtime = Runtime::default();
        let seen = Rc::new(RefCell::new(Vec::new()));
        // One closure, built again by every frame: the same kind of component each time.
        let build = {
            let seen = seen.clone();
            Rc::new(move |cx: &BuildContext| -> Box<dyn Widget> {
                let taps = cx.use_state(|| 10);
                let scratch = cx.use_ref(|| 0);
                scratch.update(|n| *n += 1);
                taps.update(|n| *n += 1);
                seen.borrow_mut().push((taps.get(), scratch.get()));
                Box::new(Container::new())
            })
        };
        let make = |build: &Builder| {
            let build = build.clone();
            Component::stateless(move |cx: &BuildContext| build(cx))
        };
        let build: Builder = build;
        frame(&runtime, &make(&build));
        assert!(
            take_rebuild_request(),
            "changing a state hook asks for a rebuild"
        );
        frame(&runtime, &make(&build));
        frame(&runtime, &make(&build));
        assert_eq!(*seen.borrow(), [(11, 1), (12, 2), (13, 3)]);
    }

    #[test]
    fn use_memo_recomputes_only_when_its_dependencies_change() {
        let runtime = Runtime::default();
        let computed = Rc::new(Cell::new(0));
        let dep = Rc::new(Cell::new(1));
        let build: Builder = {
            let (computed, dep) = (computed.clone(), dep.clone());
            Rc::new(move |cx| {
                let d = dep.get();
                let value = cx.use_memo(d, || {
                    computed.set(computed.get() + 1);
                    d * 100
                });
                Box::new(Container::new().width(*value as f32))
            })
        };
        let make = || {
            let build = build.clone();
            Component::stateless(move |cx: &BuildContext| build(cx))
        };
        let root = make();
        frame(&runtime, &root);
        assert_eq!(
            (computed.get(), width(&root)),
            (1, Dimension::Length(100.0))
        );
        let root = make();
        frame(&runtime, &root);
        assert_eq!(computed.get(), 1, "the same dependency: not computed again");
        dep.set(2);
        let root = make();
        frame(&runtime, &root);
        assert_eq!(
            (computed.get(), width(&root)),
            (2, Dimension::Length(200.0))
        );
    }

    #[test]
    fn effects_run_after_the_build_and_clean_up_before_the_next_and_at_the_end() {
        let (runtime, log) = (Runtime::default(), log());
        let dep = Rc::new(Cell::new(1));
        let build: Builder = {
            let (log, dep) = (log.clone(), dep.clone());
            Rc::new(move |cx| {
                let d = dep.get();
                let log = log.clone();
                log.borrow_mut().push(format!("build {d}"));
                cx.use_effect(d, move || {
                    log.borrow_mut().push(format!("effect {d}"));
                    move || log.borrow_mut().push(format!("cleanup {d}"))
                });
                Box::new(Container::new())
            })
        };
        let make = || {
            let build = build.clone();
            Component::stateless(move |cx: &BuildContext| build(cx))
        };
        frame(&runtime, &make());
        assert_eq!(
            taken(&log),
            ["build 1", "effect 1"],
            "after the build, not during it"
        );

        frame(&runtime, &make());
        assert_eq!(
            taken(&log),
            ["build 1"],
            "the same dependency: nothing runs"
        );

        dep.set(2);
        frame(&runtime, &make());
        assert_eq!(
            taken(&log),
            ["build 2", "cleanup 1", "effect 2"],
            "the old one is undone before the new one starts"
        );

        // leaving the tree runs the last cleanup
        frame(&runtime, &Flex::column().child(Container::new()));
        assert_eq!(taken(&log), ["cleanup 2"]);
    }

    #[test]
    #[should_panic(expected = "different order")]
    fn hooks_called_in_a_different_order_are_caught() {
        let runtime = Runtime::default();
        let first = Rc::new(Cell::new(true));
        let build: Builder = {
            let first = first.clone();
            Rc::new(move |cx| {
                if first.get() {
                    cx.use_state(|| 1i32);
                }
                cx.use_ref(String::new);
                Box::new(Container::new())
            })
        };
        let make = || {
            let build = build.clone();
            Component::stateless(move |cx: &BuildContext| build(cx))
        };
        frame(&runtime, &make());
        first.set(false);
        frame(&runtime, &make());
    }

    #[test]
    #[should_panic(expected = "set_state was called while")]
    fn changing_state_from_inside_build_is_refused() {
        struct Greedy;
        struct GreedyState;
        impl StatefulWidget for Greedy {
            type State = GreedyState;
            fn create_state(&self) -> GreedyState {
                GreedyState
            }
        }
        impl State for GreedyState {
            type Widget = Greedy;
            fn build(&self, cx: &StateContext<Self>) -> Box<dyn Widget> {
                cx.handle().set_state(|_| {});
                Box::new(Container::new())
            }
        }
        frame(&Runtime::default(), &Greedy.into_widget());
    }

    #[test]
    fn an_interval_is_asked_for_by_each_build_that_wants_it() {
        let runtime = Runtime::default();
        let on = Rc::new(Cell::new(true));
        let build: Builder = {
            let on = on.clone();
            Rc::new(move |cx| {
                if on.get() {
                    cx.use_interval(std::time::Duration::from_secs(1), || {});
                    cx.use_interval(std::time::Duration::from_secs(5), || {});
                }
                Box::new(Container::new())
            })
        };
        let make = || {
            let build = build.clone();
            Component::stateless(move |cx: &BuildContext| build(cx))
        };
        frame(&runtime, &make());
        let first = intervals();
        assert_eq!(first.len(), 2);
        assert_ne!(first[0].id, first[1].id, "two timers are told apart");

        frame(&runtime, &make());
        let second = intervals();
        assert_eq!(
            first.iter().map(|i| i.id).collect::<Vec<_>>(),
            second.iter().map(|i| i.id).collect::<Vec<_>>(),
            "and each is the same timer from one build to the next"
        );

        on.set(false);
        frame(&runtime, &make());
        assert!(
            intervals().is_empty(),
            "a build that stops asking stops the timer"
        );
    }

    #[test]
    fn a_service_provided_to_the_runtime_is_reachable_from_a_build() {
        let runtime = Runtime::default();
        runtime.states.provide(Rc::new(41u32));
        let root = component(|cx| {
            let n = cx.service::<u32>().expect("provided");
            Box::new(Container::new().width(*n as f32 + 1.0))
        });
        frame(&runtime, &root);
        assert_eq!(width(&root), Dimension::Length(42.0));
        assert!(runtime.states.service::<String>().is_none());
    }
}