waft-widgets 0.18.2

Widget framework and widgets for Waft
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
//! Flutter counterpart: `widgets/focus_scope.dart`.

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::panic::Location;
use std::rc::Rc;

use waft_embedder::TargetPlatform;
use waft_foundation::{
    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, FlagProperty, Handle, Listener,
    OptionRetained, Ref, StringProperty, ValueChanged,
};

use crate::framework::{
    AnyElement, BuildContext, ComponentElement, ComponentElementData, CreationLocation, Element,
    ElementData, ElementLifecycle, IntoWidget, KeyRef, ProxyElement, Slot, State, StateData,
    StatefulWidget, Widget, WidgetKind, WidgetRef, component_element_overrides, downcast_widget,
};
use crate::widgets::basic::Semantics;
use crate::widgets::focus_manager::{
    AnyFocusNode, FocusAttachment, FocusNode, FocusNodeLeaf, FocusNodeRef, FocusOnKeyEventCallback,
    FocusScopeNode,
};

/// A widget that manages a [`FocusNode`] to allow keyboard focus to be given to this widget and
/// its descendants.
///
/// When the focus is gained or lost, [`on_focus_change`](Self::on_focus_change) is called.
///
/// For key events, [`on_key_event`](Self::on_key_event) is called if
/// [`AnyFocusNode::has_focus`] is true for this widget's [`focus_node`](Self::focus_node),
/// unless a focused descendant's `on_key_event` callback returned
/// `KeyEventResult::Handled` when called.
///
/// This widget does not provide any visual indication that the focus has changed. Any desired
/// visual changes should be made when [`on_focus_change`](Self::on_focus_change) is called.
///
/// To access the [`FocusNode`] of the nearest ancestor [`Focus`] widget and establish a
/// relationship that will rebuild the widget when the focus changes, use the [`Focus::of`] and
/// [`FocusScope::of`] static methods.
///
/// Managing a [`FocusNode`] means managing its lifecycle, listening for changes in focus, and
/// re-parenting it when needed to keep the focus hierarchy in sync with the widget hierarchy.
/// This widget does all of those things for you.
///
/// If the [`Focus::new`] constructor is used, then this widget will manage any given
/// [`focus_node`](Self::focus_node) by overwriting the appropriate values of the node with the
/// values of this widget whenever the [`Focus`] widget is updated.
///
/// If [`Focus::with_external_focus_node`] is used instead, then the values returned by
/// [`on_key_event`](Self::on_key_event), [`skip_traversal`](Self::skip_traversal),
/// [`can_request_focus`](Self::can_request_focus), and
/// [`descendants_are_focusable`](Self::descendants_are_focusable) will be the values in the
/// external focus node, and the external focus node's values will not be overwritten when the
/// widget is updated.
///
/// To collect a sub-tree of nodes into an exclusive group that restricts focus traversal to the
/// group, use a [`FocusScope`].
pub struct Focus {
    /// See [`Widget::key`].
    pub key: Option<KeyRef>,

    /// The optional parent node to use when reparenting the
    /// [`focus_node`](Self::focus_node) for this [`Focus`] widget.
    ///
    /// If [`parent_node`](Self::parent_node) is `None`, then [`Focus::maybe_of`] is used to
    /// find the parent in the widget tree, which is typically what is desired, since it is
    /// easier to reason about the focus tree if it mirrors the shape of the widget tree.
    ///
    /// Set this property if the focus tree needs to have a different shape than the widget
    /// tree. This is typically in cases where a dialog is in an `Overlay` (or another part of
    /// the widget tree), and focus should behave as if the widgets in the overlay are
    /// descendants of the given [`parent_node`](Self::parent_node) for purposes of focus.
    ///
    /// Defaults to `None`.
    pub parent_node: Option<FocusNodeRef>,

    /// The child widget of this [`Focus`].
    pub child: WidgetRef,

    /// An optional focus node to use as the focus node for this widget.
    ///
    /// If one is not supplied, then one will be automatically allocated, owned, and managed by
    /// this widget. The widget will be focusable even if a
    /// [`focus_node`](Self::focus_node) is not supplied. If supplied, the given node will be
    /// _hosted_ by this widget, but not owned. See [`FocusNode`] for more information on what
    /// being hosted and/or owned implies.
    ///
    /// A non-null [`focus_node`](Self::focus_node) must be supplied if using the
    /// [`Focus::with_external_focus_node`] constructor.
    pub focus_node: Option<FocusNodeRef>,

    /// True if this widget will be selected as the initial focus when no other node in its
    /// scope is currently focused.
    ///
    /// Ideally, there is only one widget with autofocus set in each [`FocusScope`]. If there is
    /// more than one widget with autofocus set, then the first one added to the tree will get
    /// focus.
    ///
    /// Defaults to false.
    pub autofocus: bool,

    /// Handler called when the focus changes.
    ///
    /// Called with true if this widget's node gains focus, and false if it loses focus.
    pub on_focus_change: Option<ValueChanged<bool>>,

    /// Include semantics information in this widget.
    ///
    /// Defaults to true.
    pub include_semantics: bool,

    /// Dart's `Focus._usingExternalFocus`: whether the widget's focus node attributes should
    /// have priority when the widget is updated.
    using_external_focus: bool,

    /// Dart's `Focus._onKeyEvent`.
    on_key_event: Option<FocusOnKeyEventCallback>,

    /// Dart's `Focus._canRequestFocus`.
    can_request_focus: Option<bool>,

    /// Dart's `Focus._skipTraversal`.
    skip_traversal: Option<bool>,

    /// Dart's `Focus._descendantsAreFocusable`.
    descendants_are_focusable: Option<bool>,

    /// Dart's `Focus._descendantsAreTraversable`.
    descendants_are_traversable: Option<bool>,

    /// Dart's `Focus._debugLabel`.
    debug_label: Option<String>,
}

impl Focus {
    /// Creates a widget that manages a [`FocusNode`].
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(child: impl IntoWidget<K>) -> Focus {
        Focus {
            key: None,
            parent_node: None,
            child: child.into_widget(),
            focus_node: None,
            autofocus: false,
            on_focus_change: None,
            include_semantics: true,
            using_external_focus: false,
            on_key_event: None,
            can_request_focus: None,
            skip_traversal: None,
            descendants_are_focusable: None,
            descendants_are_traversable: None,
            debug_label: None,
        }
    }

    /// Creates a [`Focus`] widget that uses the given `focus_node` as the source of truth for
    /// attributes on the node, rather than the attributes of this widget.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn with_external_focus_node<K>(
        child: impl IntoWidget<K>,
        focus_node: FocusNodeRef,
    ) -> Focus {
        Focus {
            focus_node: Some(focus_node),
            using_external_focus: true,
            ..Focus::new(child)
        }
    }

    /// Dart `Focus(key:)`.
    pub fn key(mut self, key: KeyRef) -> Focus {
        self.key = Some(key);
        self
    }

    /// Dart `Focus(parentNode:)`.
    pub fn parent_node(mut self, parent_node: FocusNodeRef) -> Focus {
        self.parent_node = Some(parent_node);
        self
    }

    /// Dart `Focus(focusNode:)`.
    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> Focus {
        self.focus_node = Some(focus_node);
        self
    }

    /// Dart `Focus(autofocus:)`.
    pub fn autofocus(mut self, autofocus: bool) -> Focus {
        self.autofocus = autofocus;
        self
    }

    /// Dart `Focus(onFocusChange:)`.
    pub fn on_focus_change(mut self, on_focus_change: impl Fn(&mut App, bool) + 'static) -> Focus {
        self.on_focus_change = Some(Rc::new(on_focus_change));
        self
    }

    /// Dart `Focus(onKeyEvent:)`.
    pub fn on_key_event(mut self, on_key_event: FocusOnKeyEventCallback) -> Focus {
        self.on_key_event = Some(on_key_event);
        self
    }

    /// Dart `Focus(canRequestFocus:)`.
    pub fn can_request_focus(mut self, can_request_focus: bool) -> Focus {
        self.can_request_focus = Some(can_request_focus);
        self
    }

    /// Dart `Focus(skipTraversal:)`.
    pub fn skip_traversal(mut self, skip_traversal: bool) -> Focus {
        self.skip_traversal = Some(skip_traversal);
        self
    }

    /// Dart `Focus(descendantsAreFocusable:)`.
    pub fn descendants_are_focusable(mut self, descendants_are_focusable: bool) -> Focus {
        self.descendants_are_focusable = Some(descendants_are_focusable);
        self
    }

    /// Dart `Focus(descendantsAreTraversable:)`.
    pub fn descendants_are_traversable(mut self, descendants_are_traversable: bool) -> Focus {
        self.descendants_are_traversable = Some(descendants_are_traversable);
        self
    }

    /// Dart `Focus(includeSemantics:)`.
    pub fn include_semantics(mut self, include_semantics: bool) -> Focus {
        self.include_semantics = include_semantics;
        self
    }

    /// Dart `Focus(debugLabel:)`.
    pub fn debug_label(mut self, debug_label: impl Into<String>) -> Focus {
        self.debug_label = Some(debug_label.into());
        self
    }

    // ---- the getters `_FocusState` reads; a `withExternalFocusNode` widget leaves every
    // private field unset, so the node is already the source of truth ----

    /// A handler for keys that are pressed when this object or one of its children has focus.
    ///
    /// Key events are first given to the [`FocusNode`] that has primary focus, and if its
    /// `on_key_event` returns `KeyEventResult::Ignored`, then they are given to each ancestor
    /// node up the focus hierarchy in turn. If an event reaches the root of the hierarchy, it
    /// is discarded.
    pub fn get_on_key_event(&self, app: &App) -> Option<FocusOnKeyEventCallback> {
        self.on_key_event.clone().or_else(|| {
            self.focus_node
                .handle()
                .and_then(|node| node.on_key_event(app))
        })
    }

    /// If true, this widget may request the primary focus.
    ///
    /// Defaults to true. Set to false if you want the [`FocusNode`] this widget manages to do
    /// nothing when [`AnyFocusNode::request_focus`] is called on it. Does not affect the
    /// children of this node, and [`AnyFocusNode::has_focus`] can still return true if this
    /// node is the ancestor of the primary focus.
    pub fn get_can_request_focus(&self, app: &App) -> bool {
        let (explicit, node) = (self.can_request_focus, self.focus_node.handle());
        Focus::resolve_can_request_focus(explicit, node, app)
    }

    /// The body of [`get_can_request_focus`](Self::get_can_request_focus), over copies of the
    /// two fields it reads: reading the node needs `&mut App`, which a borrow of the widget
    /// out of the arena would conflict with.
    fn resolve_can_request_focus(
        explicit: Option<bool>,
        node: Option<AnyFocusNode>,
        app: &App,
    ) -> bool {
        explicit
            .or_else(|| node.map(|node| node.can_request_focus(app)))
            .unwrap_or(true)
    }

    /// Sets the [`AnyFocusNode::skip_traversal`] flag on the focus node so that it won't be
    /// visited by the `FocusTraversalPolicy`.
    pub fn get_skip_traversal(&self, app: &mut App) -> bool {
        let (explicit, node) = (self.skip_traversal, self.focus_node.handle());
        Focus::resolve_skip_traversal(explicit, node, app)
    }

    /// The body of [`get_skip_traversal`](Self::get_skip_traversal); see
    /// [`resolve_can_request_focus`](Self::resolve_can_request_focus).
    fn resolve_skip_traversal(
        explicit: Option<bool>,
        node: Option<AnyFocusNode>,
        app: &mut App,
    ) -> bool {
        explicit
            .or_else(|| node.map(|node| node.skip_traversal(app)))
            .unwrap_or(false)
    }

    /// If false, will make this widget's descendants unfocusable.
    ///
    /// Defaults to true. Does not affect focusability of this node (just its descendants): for
    /// that, use [`AnyFocusNode::can_request_focus`].
    pub fn get_descendants_are_focusable(&self, app: &App) -> bool {
        self.descendants_are_focusable
            .or_else(|| {
                self.focus_node
                    .handle()
                    .map(|node| node.descendants_are_focusable(app))
            })
            .unwrap_or(true)
    }

    /// If false, will make this widget's descendants untraversable.
    ///
    /// Defaults to true. Does not affect traversability of this node (just its descendants):
    /// for that, use [`AnyFocusNode::skip_traversal`].
    pub fn get_descendants_are_traversable(&self, app: &App) -> bool {
        self.descendants_are_traversable
            .or_else(|| {
                self.focus_node
                    .handle()
                    .map(|node| node.descendants_are_traversable(app))
            })
            .unwrap_or(true)
    }

    /// A debug label for this widget.
    pub fn get_debug_label(&self, app: &App) -> Option<String> {
        self.debug_label.clone().or_else(|| {
            self.focus_node
                .handle()
                .and_then(|node| node.debug_label(app))
        })
    }

    /// Returns the focus node of the [`Focus`] that most tightly encloses the given
    /// `BuildContext`.
    ///
    /// If no [`Focus`] node is found before reaching the nearest [`FocusScope`] widget, or
    /// there is no [`Focus`] widget in the context, then this method panics.
    ///
    /// If `create_dependency` is true, calling this function creates a dependency that will
    /// rebuild the given context when the focus node gains or loses focus.
    pub fn of(
        app: &mut App,
        context: BuildContext,
        scope_ok: bool,
        create_dependency: bool,
    ) -> AnyFocusNode {
        let node = Focus::maybe_of(app, context, scope_ok, create_dependency);
        let node = node.expect(
            "Focus.of() was called with a context that does not contain a Focus widget.\n\
             No Focus widget ancestor could be found starting from the context that was passed \
             to Focus.of(). This can happen because you are using a widget that looks for a \
             Focus ancestor, and do not have a Focus widget descendant in the nearest \
             FocusScope.",
        );
        debug_assert!(
            scope_ok || node.as_scope().is_none(),
            "Focus.of() was called with a context that does not contain a Focus between the \
             given context and the nearest FocusScope widget."
        );
        node
    }

    /// Returns the focus node of the [`Focus`] that most tightly encloses the given
    /// `BuildContext`.
    ///
    /// If no [`Focus`] node is found before reaching the nearest [`FocusScope`] widget, or
    /// there is no [`Focus`] widget in scope, then this method returns `None`.
    ///
    /// If `create_dependency` is true, calling this function creates a dependency that will
    /// rebuild the given context when the focus node gains or loses focus.
    pub fn maybe_of(
        app: &mut App,
        context: BuildContext,
        scope_ok: bool,
        create_dependency: bool,
    ) -> Option<AnyFocusNode> {
        let node = if create_dependency {
            context
                .depend_on_inherited_widget_of_exact_type::<FocusInheritedScope>(app)
                .map(|scope| scope.node.handle())
        } else {
            context
                .get_inherited_widget_of_exact_type::<FocusInheritedScope>(app)
                .map(|scope| scope.node.handle())
        }?;
        match node.as_scope() {
            Some(_) if !scope_ok => None,
            _ => Some(node),
        }
    }

    /// Returns true if the nearest enclosing [`Focus`] widget's node is focused.
    ///
    /// A convenience method to allow build methods to write `Focus::is_at(app, context)` to get
    /// whether or not the nearest [`Focus`] above them in the widget hierarchy currently has
    /// the input focus.
    ///
    /// Returns false if no [`Focus`] widget is found before reaching the nearest
    /// [`FocusScope`], or if the root of the focus tree is reached without finding a [`Focus`]
    /// widget.
    ///
    /// Calling this function creates a dependency that will rebuild the given context when the
    /// focus changes.
    pub fn is_at(app: &mut App, context: BuildContext) -> bool {
        match Focus::maybe_of(app, context, false, true) {
            Some(node) => node.has_focus(app),
            None => false,
        }
    }
}

impl fmt::Debug for Focus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Focus")
            .field("debugLabel", &self.debug_label)
            .field("autofocus", &self.autofocus)
            .field("focusNode", &self.focus_node)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for Focus {
    type State = FocusState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        properties.add(StringProperty::new("debugLabel", self.get_debug_label(app)));
        properties.add(
            FlagProperty::new("autofocus", Some(self.autofocus))
                .if_true("AUTOFOCUS")
                .default_value(Some(false)),
        );
        properties.add(
            FlagProperty::new("canRequestFocus", Some(self.get_can_request_focus(app)))
                .if_false("NOT FOCUSABLE")
                .default_value(Some(false)),
        );
        properties.add(
            FlagProperty::new(
                "descendantsAreFocusable",
                Some(self.get_descendants_are_focusable(app)),
            )
            .if_false("DESCENDANTS UNFOCUSABLE")
            .default_value(Some(true)),
        );
        properties.add(
            FlagProperty::new(
                "descendantsAreTraversable",
                Some(self.get_descendants_are_traversable(app)),
            )
            .if_false("DESCENDANTS UNTRAVERSABLE")
            .default_value(Some(true)),
        );
        properties.add(
            DiagnosticsProperty::<String>::new(
                "focusNode",
                self.focus_node.handle().map(|node| node.to_string(app)),
            )
            .default_value(None),
        );
    }

    fn create_state(&self) -> FocusState {
        FocusState {
            state: StateData::new(),
            focus: FocusStateData::new(),
        }
    }
}

/// Dart's private members of `_FocusState`; both [`FocusState`] and [`FocusScopeState`] carry
/// this bag under the field `focus`.
pub struct FocusStateData {
    internal_node: Option<FocusNodeRef>,
    had_primary_focus: bool,
    could_request_focus: bool,
    descendants_were_focusable: bool,
    descendants_were_traversable: bool,
    did_autofocus: bool,
    focus_attachment: Option<Ref<FocusAttachment>>,
}

impl FocusStateData {
    /// A state that has not run `init_state` yet.
    pub fn new() -> FocusStateData {
        FocusStateData {
            internal_node: None,
            had_primary_focus: false,
            could_request_focus: false,
            descendants_were_focusable: false,
            descendants_were_traversable: false,
            did_autofocus: false,
            focus_attachment: None,
        }
    }
}

impl Default for FocusStateData {
    fn default() -> FocusStateData {
        FocusStateData::new()
    }
}

/// The shared bodies of Dart's `_FocusState`, which `_FocusScopeState` extends.
///
/// [`create_node`](Self::create_node) is the only virtual; the rest are Dart's `_FocusState`
/// members, and each state's `State` hooks call them where Dart's inherited body would run.
pub trait FocusStateLeaf: State + Sized + 'static {
    /// Dart's `_FocusState` fields, held under the field `focus`.
    fn focus_state_data(self: Handle<Self>, app: &App) -> &FocusStateData;

    /// See [`focus_state_data`](Self::focus_state_data).
    fn focus_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusStateData;

    /// The `Focus` fields of this state's widget: the widget itself for [`Focus`], the
    /// superclass bag for [`FocusScope`].
    fn focus_widget(self: Handle<Self>, app: &App) -> &Focus;

    /// Dart's `_FocusState._createNode`.
    fn create_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef;

    /// Dart's `widget.canRequestFocus`.
    fn widget_can_request_focus(self: Handle<Self>, app: &mut App) -> bool {
        let widget = self.focus_widget(app);
        let (explicit, node) = (widget.can_request_focus, widget.focus_node.handle());
        Focus::resolve_can_request_focus(explicit, node, app)
    }

    /// Dart's `widget.skipTraversal`.
    fn widget_skip_traversal(self: Handle<Self>, app: &mut App) -> bool {
        let widget = self.focus_widget(app);
        let (explicit, node) = (widget.skip_traversal, widget.focus_node.handle());
        Focus::resolve_skip_traversal(explicit, node, app)
    }

    /// Dart's `_FocusState.focusNode`.
    fn focus_node(self: Handle<Self>, app: &mut App) -> AnyFocusNode {
        if let Some(node) = self.focus_widget(app).focus_node.handle() {
            return node;
        }
        if let Some(node) = self.focus_state_data(app).internal_node.handle() {
            return node;
        }
        let node = self.create_node(app);
        let handle = node.handle();
        self.focus_state_data_mut(app).internal_node = Some(node);
        handle
    }

    /// [`focus_node`](Self::focus_node) as the reference a widget built from this state keeps.
    fn kept_focus_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
        let node = self.focus_node(app);
        node.keep(app)
    }

    /// Dart's `_FocusState._initNode`.
    fn init_node(self: Handle<Self>, app: &mut App) {
        let focus_node = self.focus_node(app);
        if !self.focus_widget(app).using_external_focus {
            let descendants_are_focusable =
                self.focus_widget(app).get_descendants_are_focusable(app);
            focus_node.set_descendants_are_focusable(app, descendants_are_focusable);
            let descendants_are_traversable =
                self.focus_widget(app).get_descendants_are_traversable(app);
            focus_node.set_descendants_are_traversable(app, descendants_are_traversable);
            let skip_traversal = self.widget_skip_traversal(app);
            focus_node.set_skip_traversal(app, skip_traversal);
            if let Some(can_request_focus) = self.focus_widget(app).can_request_focus {
                focus_node.set_can_request_focus(app, can_request_focus);
            }
        }
        let could_request_focus = focus_node.can_request_focus(app);
        let descendants_were_focusable = focus_node.descendants_are_focusable(app);
        let descendants_were_traversable = focus_node.descendants_are_traversable(app);
        let had_primary_focus = focus_node.has_primary_focus(app);
        let data = self.focus_state_data_mut(app);
        data.could_request_focus = could_request_focus;
        data.descendants_were_focusable = descendants_were_focusable;
        data.descendants_were_traversable = descendants_were_traversable;
        data.had_primary_focus = had_primary_focus;
        let context = self.context(app);
        let on_key_event = self.focus_widget(app).get_on_key_event(app);
        let attachment = focus_node.attach(app, Some(context), on_key_event);
        self.focus_state_data_mut(app).focus_attachment = Some(attachment);

        // Add listener even if the internal node existed before, since it should not be
        // listening now if we're re-using a previous one because it should have already
        // removed its listener.
        focus_node.add_listener(
            app,
            Listener::handle_method(self, Self::handle_focus_changed),
        );
    }

    /// Dart's `_FocusState.dispose`.
    fn dispose_focus(self: Handle<Self>, app: &mut App) {
        // Regardless of the node owner, we need to remove it from the tree and stop listening
        // to it.
        let focus_node = self.focus_node(app);
        focus_node.remove_listener(
            app,
            &Listener::handle_method(self, Self::handle_focus_changed),
        );
        self.focus_state_data(app)
            .focus_attachment
            .handle()
            .expect("attached in init_state")
            .detach(app);

        // Don't manage the lifetime of external nodes given to the widget, just the internal
        // node.
        if let Some(internal_node) = self.focus_state_data(app).internal_node.handle() {
            internal_node.dispose(app);
        }
    }

    /// Dart's `_FocusState.didChangeDependencies`.
    fn did_change_dependencies_focus(self: Handle<Self>, app: &mut App) {
        if let Some(attachment) = self.focus_state_data(app).focus_attachment.handle() {
            attachment.reparent(app, None);
        }
        self.handle_autofocus(app);
    }

    /// Dart's `_FocusState._handleAutofocus`.
    fn handle_autofocus(self: Handle<Self>, app: &mut App) {
        if !self.focus_state_data(app).did_autofocus && self.focus_widget(app).autofocus {
            let context = self.context(app);
            let scope = FocusScope::of(app, context, true);
            let focus_node = self.focus_node(app);
            scope.autofocus(app, focus_node);
            self.focus_state_data_mut(app).did_autofocus = true;
        }
    }

    /// Dart's `_FocusState.deactivate`.
    ///
    /// The focus node's location in the tree is no longer valid here. But we can't unfocus or
    /// remove the node from the tree because if the widget is moved to a different part of the
    /// tree (via global key) it should retain its focus state. That's why we temporarily park
    /// it on the root focus node (via reparent) until it either gets moved to a different part
    /// of the tree (via `did_change_dependencies`) or until it is disposed.
    fn deactivate_focus(self: Handle<Self>, app: &mut App) {
        if let Some(attachment) = self.focus_state_data(app).focus_attachment.handle() {
            attachment.reparent(app, None);
        }
        self.focus_state_data_mut(app).did_autofocus = false;
    }

    /// Dart's `_FocusState.didUpdateWidget`.
    fn did_update_widget_focus(self: Handle<Self>, app: &mut App, old_widget: &Focus) {
        if cfg!(debug_assertions) {
            // Only update the debug label in debug builds.
            let widget_label = self.focus_widget(app).debug_label.clone();
            if old_widget.focus_node == self.focus_widget(app).focus_node
                && !self.focus_widget(app).using_external_focus
                && old_widget.debug_label != widget_label
            {
                let focus_node = self.focus_node(app);
                let label = self.focus_widget(app).get_debug_label(app);
                focus_node.set_debug_label(app, label);
            }
        }

        if old_widget.focus_node == self.focus_widget(app).focus_node {
            if !self.focus_widget(app).using_external_focus {
                let focus_node = self.focus_node(app);
                let on_key_event = self.focus_widget(app).get_on_key_event(app);
                let same_handler = match (&on_key_event, &focus_node.on_key_event(app)) {
                    (None, None) => true,
                    (Some(a), Some(b)) => Rc::ptr_eq(a, b),
                    _ => false,
                };
                if !same_handler {
                    focus_node.set_on_key_event(app, on_key_event);
                }
                let skip_traversal = self.widget_skip_traversal(app);
                focus_node.set_skip_traversal(app, skip_traversal);
                if let Some(can_request_focus) = self.focus_widget(app).can_request_focus {
                    focus_node.set_can_request_focus(app, can_request_focus);
                }
                let descendants_are_focusable =
                    self.focus_widget(app).get_descendants_are_focusable(app);
                focus_node.set_descendants_are_focusable(app, descendants_are_focusable);
                let descendants_are_traversable =
                    self.focus_widget(app).get_descendants_are_traversable(app);
                focus_node.set_descendants_are_traversable(app, descendants_are_traversable);
            }
        } else {
            self.focus_state_data(app)
                .focus_attachment
                .handle()
                .expect("attached in init_state")
                .detach(app);
            if let Some(old_node) = old_widget.focus_node.handle() {
                old_node.remove_listener(
                    app,
                    &Listener::handle_method(self, Self::handle_focus_changed),
                );
            }
            self.init_node(app);
        }

        if old_widget.autofocus != self.focus_widget(app).autofocus {
            self.handle_autofocus(app);
        }
    }

    /// Dart's `_FocusState._handleFocusChanged`.
    fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
        let focus_node = self.focus_node(app);
        let has_primary_focus = focus_node.has_primary_focus(app);
        let can_request_focus = focus_node.can_request_focus(app);
        let descendants_are_focusable = focus_node.descendants_are_focusable(app);
        let descendants_are_traversable = focus_node.descendants_are_traversable(app);
        if let Some(on_focus_change) = self.focus_widget(app).on_focus_change.clone() {
            let has_focus = focus_node.has_focus(app);
            on_focus_change(app, has_focus);
        }
        // Check the cached states that matter here, and call set_state if they have changed.
        if self.focus_state_data(app).had_primary_focus != has_primary_focus {
            self.set_state(app, |state| {
                state.focus_state_data_field().had_primary_focus = has_primary_focus;
            });
        }
        if self.focus_state_data(app).could_request_focus != can_request_focus {
            self.set_state(app, |state| {
                state.focus_state_data_field().could_request_focus = can_request_focus;
            });
        }
        if self.focus_state_data(app).descendants_were_focusable != descendants_are_focusable {
            self.set_state(app, |state| {
                state.focus_state_data_field().descendants_were_focusable =
                    descendants_are_focusable;
            });
        }
        if self.focus_state_data(app).descendants_were_traversable != descendants_are_traversable {
            self.set_state(app, |state| {
                state.focus_state_data_field().descendants_were_traversable =
                    descendants_are_traversable;
            });
        }
    }

    /// The bag, reached from `&mut Self` inside a `set_state` callback.
    fn focus_state_data_field(&mut self) -> &mut FocusStateData;
}

/// Dart's `_FocusState`.
pub struct FocusState {
    state: StateData<Focus>,
    focus: FocusStateData,
}

impl FocusStateLeaf for FocusState {
    fn focus_state_data(self: Handle<Self>, app: &App) -> &FocusStateData {
        &app.get(self).focus
    }

    fn focus_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusStateData {
        &mut app.get_mut(self).focus
    }

    fn focus_state_data_field(&mut self) -> &mut FocusStateData {
        &mut self.focus
    }

    fn focus_widget(self: Handle<Self>, app: &App) -> &Focus {
        self.widget(app)
    }

    fn create_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
        let node = FocusNode::new(app);
        let label = self.widget(app).get_debug_label(app);
        node.set_debug_label(app, label);
        let can_request_focus = self.widget_can_request_focus(app);
        node.set_can_request_focus(app, can_request_focus);
        let descendants_are_focusable = self.widget(app).get_descendants_are_focusable(app);
        node.set_descendants_are_focusable(app, descendants_are_focusable);
        let descendants_are_traversable = self.widget(app).get_descendants_are_traversable(app);
        node.set_descendants_are_traversable(app, descendants_are_traversable);
        let skip_traversal = self.widget_skip_traversal(app);
        node.set_skip_traversal(app, skip_traversal);
        node.into_erased()
    }
}

impl State for FocusState {
    type Widget = Focus;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        self.init_node(app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        self.dispose_focus(app);
    }

    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
        self.did_change_dependencies_focus(app);
    }

    fn deactivate(self: Handle<Self>, app: &mut App) {
        self.deactivate_focus(app);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Focus) {
        self.did_update_widget_focus(app, old_widget);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let parent_node = self.widget(app).parent_node.handle();
        self.focus_state_data(app)
            .focus_attachment
            .handle()
            .expect("attached in init_state")
            .reparent(app, parent_node);
        let mut child = self.widget(app).child.clone();
        let node = self.kept_focus_node(app);
        if self.widget(app).include_semantics {
            let could_request_focus = self.focus_state_data(app).could_request_focus;
            let had_primary_focus = self.focus_state_data(app).had_primary_focus;
            let mut semantics = Semantics::new().focusable(could_request_focus);
            // Automatically request the focus for a focusable widget when it
            // receives an input focus action from the semantics. Nothing is needed
            // for losing the focus because if focus is lost, that means another
            // node will gain focus and take focus from this widget.
            // TODO(gspencergoog): Allow this to be set on iOS once the issue is
            // addressed: https://github.com/flutter/flutter/issues/150030
            if app.platform().target_platform() != TargetPlatform::IOS && could_request_focus {
                let node = node.clone();
                semantics =
                    semantics.on_focus(Rc::new(move |app: &mut App| node.request_focus(app, None)));
            }
            if could_request_focus {
                semantics = semantics.focused(had_primary_focus);
            }
            child = semantics.child(child).into_widget();
        }
        // Dart wraps the child in a `_DebugFocusBorder` when `debugPaintFocusBoxes` is set;
        // that waits.
        FocusInheritedScope {
            node,
            child,
            created: None,
        }
        .into_widget()
    }
}

// ---------------------------------------------------------------------------------------------
// FocusScope

/// A [`FocusScope`] is similar to a [`Focus`], but also serves as a scope for its descendants,
/// restricting focus traversal to the scoped controls.
///
/// For example a new [`FocusScope`] is created automatically when a route is pushed, keeping
/// the focus traversal from moving to a control in a previous route.
///
/// Like [`Focus`], [`FocusScope`] provides an `on_focus_change` as a way to be notified when
/// the focus is given to or removed from this widget.
///
/// Managing a [`FocusScopeNode`] means managing its lifecycle, listening for changes in focus,
/// and re-parenting it when needed to keep the focus hierarchy in sync with the widget
/// hierarchy. This widget does all of those things for you.
///
/// [`FocusScopeNode`]s remember the last [`FocusNode`] that was focused within their
/// descendants.
pub struct FocusScope {
    /// Dart's `class FocusScope extends Focus`: the superclass's fields.
    focus: Focus,
}

impl FocusScope {
    /// Creates a widget that manages a [`FocusScopeNode`].
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(child: impl IntoWidget<K>) -> FocusScope {
        FocusScope {
            focus: Focus::new(child),
        }
    }

    /// Creates a [`FocusScope`] widget that uses the given `focus_scope_node` as the source of
    /// truth for attributes on the node, rather than the attributes of this widget.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn with_external_focus_node<K>(
        child: impl IntoWidget<K>,
        focus_scope_node: Ref<FocusScopeNode>,
    ) -> FocusScope {
        FocusScope {
            focus: Focus::with_external_focus_node(child, focus_scope_node.into_erased()),
        }
    }

    /// Dart `FocusScope(node:)`.
    pub fn node(mut self, node: Ref<FocusScopeNode>) -> FocusScope {
        self.focus.focus_node = Some(node.into_erased());
        self
    }

    /// Dart `FocusScope(key:)`.
    pub fn key(mut self, key: KeyRef) -> FocusScope {
        self.focus = self.focus.key(key);
        self
    }

    /// Dart `FocusScope(parentNode:)`.
    pub fn parent_node(mut self, parent_node: FocusNodeRef) -> FocusScope {
        self.focus = self.focus.parent_node(parent_node);
        self
    }

    /// Dart `FocusScope(autofocus:)`.
    pub fn autofocus(mut self, autofocus: bool) -> FocusScope {
        self.focus = self.focus.autofocus(autofocus);
        self
    }

    /// Dart `FocusScope(onFocusChange:)`.
    pub fn on_focus_change(
        mut self,
        on_focus_change: impl Fn(&mut App, bool) + 'static,
    ) -> FocusScope {
        self.focus = self.focus.on_focus_change(on_focus_change);
        self
    }

    /// Dart `FocusScope(onKeyEvent:)`.
    pub fn on_key_event(mut self, on_key_event: FocusOnKeyEventCallback) -> FocusScope {
        self.focus = self.focus.on_key_event(on_key_event);
        self
    }

    /// Dart `FocusScope(canRequestFocus:)`.
    pub fn can_request_focus(mut self, can_request_focus: bool) -> FocusScope {
        self.focus = self.focus.can_request_focus(can_request_focus);
        self
    }

    /// Dart `FocusScope(skipTraversal:)`.
    pub fn skip_traversal(mut self, skip_traversal: bool) -> FocusScope {
        self.focus = self.focus.skip_traversal(skip_traversal);
        self
    }

    /// Dart `FocusScope(descendantsAreFocusable:)`.
    pub fn descendants_are_focusable(mut self, descendants_are_focusable: bool) -> FocusScope {
        self.focus = self
            .focus
            .descendants_are_focusable(descendants_are_focusable);
        self
    }

    /// Dart `FocusScope(descendantsAreTraversable:)`.
    pub fn descendants_are_traversable(mut self, descendants_are_traversable: bool) -> FocusScope {
        self.focus = self
            .focus
            .descendants_are_traversable(descendants_are_traversable);
        self
    }

    /// Dart `FocusScope(includeSemantics:)`.
    pub fn include_semantics(mut self, include_semantics: bool) -> FocusScope {
        self.focus = self.focus.include_semantics(include_semantics);
        self
    }

    /// Dart `FocusScope(debugLabel:)`.
    pub fn debug_label(mut self, debug_label: impl Into<String>) -> FocusScope {
        self.focus = self.focus.debug_label(debug_label);
        self
    }

    /// The `Focus` fields this widget inherits.
    pub fn focus(&self) -> &Focus {
        &self.focus
    }

    /// Returns the [`AnyFocusNode::nearest_scope`] of the [`Focus`] or [`FocusScope`] that most
    /// tightly encloses the given `context`.
    ///
    /// If this node doesn't have a [`Focus`] or [`FocusScope`] widget ancestor, then the
    /// [`FocusManager`](crate::FocusManager)'s root scope is returned.
    pub fn of(
        app: &mut App,
        context: BuildContext,
        create_dependency: bool,
    ) -> Handle<FocusScopeNode> {
        Focus::maybe_of(app, context, true, create_dependency)
            .and_then(|node| node.nearest_scope(app))
            .unwrap_or_else(|| {
                let owner = context
                    .owner(app)
                    .expect("a mounted element has a build owner");
                let manager = owner.focus_manager(app);
                manager.root_scope(app).handle()
            })
    }
}

impl fmt::Debug for FocusScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FocusScope")
            .field("focus", &self.focus)
            .finish()
    }
}

impl StatefulWidget for FocusScope {
    type State = FocusScopeState;

    fn key(&self) -> Option<&KeyRef> {
        self.focus.key.as_ref()
    }

    fn create_state(&self) -> FocusScopeState {
        FocusScopeState {
            state: StateData::new(),
            focus: FocusStateData::new(),
        }
    }
}

/// Dart's `_FocusScopeState`.
pub struct FocusScopeState {
    state: StateData<FocusScope>,
    focus: FocusStateData,
}

impl FocusStateLeaf for FocusScopeState {
    fn focus_state_data(self: Handle<Self>, app: &App) -> &FocusStateData {
        &app.get(self).focus
    }

    fn focus_state_data_mut(self: Handle<Self>, app: &mut App) -> &mut FocusStateData {
        &mut app.get_mut(self).focus
    }

    fn focus_state_data_field(&mut self) -> &mut FocusStateData {
        &mut self.focus
    }

    fn focus_widget(self: Handle<Self>, app: &App) -> &Focus {
        &self.widget(app).focus
    }

    fn create_node(self: Handle<Self>, app: &mut App) -> FocusNodeRef {
        let node = FocusScopeNode::new(app);
        let label = self.focus_widget(app).get_debug_label(app);
        node.set_debug_label(app, label);
        let can_request_focus = self.widget_can_request_focus(app);
        node.set_can_request_focus(app, can_request_focus);
        let skip_traversal = self.widget_skip_traversal(app);
        node.set_skip_traversal(app, skip_traversal);
        node.into_erased()
    }
}

impl State for FocusScopeState {
    type Widget = FocusScope;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        self.init_node(app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        self.dispose_focus(app);
    }

    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
        self.did_change_dependencies_focus(app);
    }

    fn deactivate(self: Handle<Self>, app: &mut App) {
        self.deactivate_focus(app);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FocusScope) {
        self.did_update_widget_focus(app, &old_widget.focus);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let parent_node = self.widget(app).focus.parent_node.handle();
        self.focus_state_data(app)
            .focus_attachment
            .handle()
            .expect("attached in init_state")
            .reparent(app, parent_node);
        let child = self.widget(app).focus.child.clone();
        let node = self.kept_focus_node(app);
        let result = FocusInheritedScope {
            node,
            child,
            created: None,
        }
        .into_widget();
        if self.widget(app).focus.include_semantics {
            return Semantics::new()
                .explicit_child_nodes(true)
                .child(result)
                .into_widget();
        }
        result
    }
}

// ---------------------------------------------------------------------------------------------
// _FocusInheritedScope

/// The `InheritedWidget` for [`Focus`] and [`FocusScope`].
///
/// Dart's `_FocusInheritedScope extends InheritedNotifier<FocusNode>`; the notifier behavior
/// lives in [`FocusInheritedScopeElement`] until `inherited_notifier.dart` is ported.
struct FocusInheritedScope {
    /// The [`AnyFocusNode`] to which to listen. Whenever it sends change notifications, the
    /// dependents of this widget are triggered.
    node: FocusNodeRef,
    child: WidgetRef,
    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
    created: Option<CreationLocation>,
}

impl FocusInheritedScope {
    /// The tree node: an `InheritedWidget` with its own element, outside the `IntoWidget`
    /// kinds.
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(mut self) -> WidgetRef {
        self.created = Some(CreationLocation::of_caller());
        Rc::new(self)
    }
}

impl fmt::Debug for FocusInheritedScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("_FocusInheritedScope")
            .field("node", &self.node)
            .finish_non_exhaustive()
    }
}

/// Dart's `InheritedNotifier.updateShouldNotify`; the trait also names the type
/// `Focus::maybe_of` looks up with `depend_on_inherited_widget_of_exact_type`.
impl crate::framework::InheritedWidget for FocusInheritedScope {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &FocusInheritedScope) -> bool {
        old_widget.node != self.node
    }
}

impl Widget for FocusInheritedScope {
    fn key(&self) -> Option<&KeyRef> {
        None
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.created.and_then(CreationLocation::location)
    }

    fn record_creation_location(&mut self, location: CreationLocation) {
        self.created = Some(location);
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        FocusInheritedScopeElement::new(app, this).as_element()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn widget_type(&self) -> TypeId {
        TypeId::of::<FocusInheritedScope>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }
}

/// Dart's `_InheritedNotifierElement<FocusNode>`, specialised to [`FocusInheritedScope`]: an
/// `InheritedElement` that marks itself dirty whenever the node notifies, and notifies its
/// dependents on the next build.
struct FocusInheritedScopeElement {
    element: ElementData,
    component: ComponentElementData,
    dependents: HashMap<AnyElement, Option<Rc<dyn Any>>>,
    dirty: bool,
}

impl FocusInheritedScopeElement {
    fn new(app: &mut App, widget: WidgetRef) -> Handle<Self> {
        let node = FocusInheritedScopeElement::widget_of(&widget).node.handle();
        let this = app
            .create(FocusInheritedScopeElement {
                element: ElementData::new(widget),
                component: ComponentElementData::default(),
                dependents: HashMap::new(),
                dirty: false,
            })
            .into_tree_node(app);
        node.add_listener(
            app,
            Listener::handle_method(this, FocusInheritedScopeElement::handle_update),
        );
        this
    }

    fn widget_of(widget: &WidgetRef) -> &FocusInheritedScope {
        downcast_widget::<FocusInheritedScope>(&**widget)
            .expect("a FocusInheritedScopeElement holds its FocusInheritedScope")
    }

    fn widget(self: Handle<Self>, app: &App) -> &FocusInheritedScope {
        FocusInheritedScopeElement::widget_of(self.as_element().widget(app))
    }

    fn handle_update(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).dirty = true;
        self.as_element().mark_needs_build(app);
    }

    /// `InheritedElement.notifyClients`, plus Dart's `_dirty` reset.
    fn notify_clients(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
        let dependents: Vec<AnyElement> = app.get(self).dependents.keys().copied().collect();
        for dependent in dependents {
            let _ = &old_widget;
            dependent.did_change_dependencies(app);
        }
        app.get_mut(self).dirty = false;
    }
}

impl ComponentElement for FocusInheritedScopeElement {
    fn component_data(self: Handle<Self>, app: &App) -> &ComponentElementData {
        &app.get(self).component
    }

    fn component_data_mut(self: Handle<Self>, app: &mut App) -> &mut ComponentElementData {
        &mut app.get_mut(self).component
    }

    fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
        if app.get(self).dirty {
            let widget = self.as_element().widget(app).clone();
            FocusInheritedScopeElement::notify_clients(self, app, widget);
        }
        self.proxied_child(app)
    }
}

impl ProxyElement for FocusInheritedScopeElement {
    fn proxied_child(self: Handle<Self>, app: &App) -> WidgetRef {
        self.widget(app).child.clone()
    }

    fn updated(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
        // `InheritedNotifier.updateShouldNotify`: the notifier changed.
        let old_node = FocusInheritedScopeElement::widget_of(&old_widget)
            .node
            .handle();
        if old_node != self.widget(app).node {
            FocusInheritedScopeElement::notify_clients(self, app, old_widget);
        }
    }

    fn notify_clients(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
        FocusInheritedScopeElement::notify_clients(self, app, old_widget);
    }
}

impl Element for FocusInheritedScopeElement {
    crate::element_accessors!();
    component_element_overrides!();

    const IS_INHERITED_ELEMENT: bool = true;

    #[inline(always)]
    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        ComponentElement::mount(self, app, parent, new_slot);
    }

    #[inline(always)]
    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        let old_node = self.widget(app).node.handle();
        let new_node = FocusInheritedScopeElement::widget_of(&new_widget)
            .node
            .handle();
        if old_node != new_node {
            old_node.remove_listener(
                app,
                &Listener::handle_method(self, FocusInheritedScopeElement::handle_update),
            );
            new_node.add_listener(
                app,
                Listener::handle_method(self, FocusInheritedScopeElement::handle_update),
            );
        }
        ProxyElement::update(self, app, new_widget);
    }

    #[inline(always)]
    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
        ComponentElement::perform_rebuild(self, app);
    }

    fn unmount(self: Handle<Self>, app: &mut App) {
        let node = self.widget(app).node.handle();
        node.remove_listener(
            app,
            &Listener::handle_method(self, FocusInheritedScopeElement::handle_update),
        );
        crate::framework::ElementBase::unmount(self, app);
    }

    fn update_inheritance(self: Handle<Self>, app: &mut App) {
        debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Active);
        let incoming = self
            .as_element()
            .parent(app)
            .and_then(|parent| parent.inherited_elements(app));
        let mut widgets: HashMap<TypeId, AnyElement> = incoming
            .map(|incoming| (*incoming).clone())
            .unwrap_or_default();
        widgets.insert(TypeId::of::<FocusInheritedScope>(), self.as_element());
        self.as_element()
            .set_inherited_elements(app, Some(Rc::new(widgets)));
    }

    fn debug_deactivated(self: Handle<Self>, app: &mut App) {
        debug_assert!(app.get(self).dependents.is_empty());
        debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
    }

    fn update_dependencies(
        self: Handle<Self>,
        app: &mut App,
        dependent: AnyElement,
        _aspect: Option<Rc<dyn Any>>,
    ) {
        app.get_mut(self).dependents.insert(dependent, None);
    }

    fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
        app.get_mut(self).dependents.remove(&dependent);
    }
}

// ---------------------------------------------------------------------------------------------
// ExcludeFocus

/// A widget that controls whether or not the descendants of this widget are focusable.
///
/// Does not affect the value of [`Focus::can_request_focus`] on the descendants.
#[derive(Debug)]
pub struct ExcludeFocus {
    /// See [`Widget::key`].
    pub key: Option<KeyRef>,

    /// If true, will make this widget's descendants unfocusable.
    ///
    /// Defaults to true.
    ///
    /// If any descendants are focused when this is set to true, they will be unfocused. When
    /// [`excluding`](Self::excluding) is set to false again, they will not be refocused,
    /// although they will be able to accept focus again.
    ///
    /// Does not affect the value of [`AnyFocusNode::can_request_focus`] on the descendants.
    pub excluding: bool,

    /// The child widget of this [`ExcludeFocus`].
    pub child: WidgetRef,
}

impl ExcludeFocus {
    /// Creates an [`ExcludeFocus`] widget.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(child: impl IntoWidget<K>) -> ExcludeFocus {
        ExcludeFocus {
            key: None,
            excluding: true,
            child: child.into_widget(),
        }
    }

    /// Dart `ExcludeFocus(key:)`.
    pub fn key(mut self, key: KeyRef) -> ExcludeFocus {
        self.key = Some(key);
        self
    }

    /// Dart `ExcludeFocus(excluding:)`.
    pub fn excluding(mut self, excluding: bool) -> ExcludeFocus {
        self.excluding = excluding;
        self
    }
}

impl crate::framework::StatelessWidget for ExcludeFocus {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        Focus::new(self.child.clone())
            .can_request_focus(false)
            .skip_traversal(true)
            .include_semantics(false)
            .descendants_are_focusable(!self.excluding)
            .into_widget()
    }
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};

    use super::*;
    use crate::framework::GlobalKey;
    use crate::testing::test_widgets;
    use crate::widgets::basic::{Builder, Center, Padding, SizedBox};
    use crate::widgets::focus_manager::{FocusManager, FocusNode, KeyEventResult};
    use crate::widgets::value_listenable_builder::ValueListenableBuilder;
    use waft_foundation::ValueNotifier;

    type Captured = Rc<Cell<Option<AnyFocusNode>>>;

    /// A `Builder` that records `Focus.of` at its own context.
    fn probe(captured: &Captured) -> WidgetRef {
        let captured = Rc::clone(captured);
        Builder::new(move |app, context| {
            captured.set(Focus::maybe_of(app, context, false, true));
            SizedBox::shrink().into_widget()
        })
        .into_widget()
    }

    /// A node a caller keeps outlives the `Focus` it hung under: `FocusNode._removeChild` clears
    /// its parent but leaves its cached ancestors, which the next `Focus` reads through
    /// `skipTraversal` before it attaches the node again.
    #[test]
    fn a_kept_node_remounts_after_the_focus_it_hung_under_is_freed() {
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            let node: FocusNodeRef = FocusNode::new(&mut app).into_erased();
            let layout = app.create(ValueNotifier::new(0));
            drop(app);
            let widget = ValueListenableBuilder::new(Rc::new(layout.clone()), {
                let node = node.clone();
                move |_app, _context, layout: &i32, _child| match layout {
                    0 => Focus::new(Focus::new(SizedBox::shrink()).focus_node(node.clone()))
                        .debug_label("outer")
                        .into_widget(),
                    1 => SizedBox::shrink().into_widget(),
                    _ => Focus::new(SizedBox::shrink())
                        .focus_node(node.clone())
                        .into_widget(),
                }
            });
            tester.pump_widget(widget.into_widget());
            let mut app = tester.cell.borrow_mut();
            let outer = node
                .parent(&app)
                .expect("the node hangs under the outer Focus");
            assert!(node.ancestors(&mut app).contains(&outer));

            layout.set_value(&mut app, 1);
            drop(app);
            tester.pump();
            let app = tester.cell.borrow();
            assert_eq!(node.parent(&app), None);
            drop(app);
            tester.cell.checkpoint();
            let mut app = tester.cell.borrow_mut();
            assert!(!app.contains(outer));

            layout.set_value(&mut app, 2);
            drop(app);
            tester.pump();
            let mut app = tester.cell.borrow_mut();
            assert!(!node.skip_traversal(&mut app));
            assert!(!node.ancestors(&mut app).contains(&outer));
        });
    }

    #[test]
    fn autofocus_gives_the_focus_widgets_node_the_primary_focus() {
        test_widgets(|tester| {
            let app = tester.cell.borrow();
            let captured: Captured = Rc::default();
            drop(app);
            tester.pump_widget(Focus::new(probe(&captured)).autofocus(true).into_widget());
            let mut app = tester.cell.borrow_mut();
            let node = captured.get().expect("Focus.of found the node");
            assert!(node.has_primary_focus(&app));
            let manager = FocusManager::instance(&mut app);
            assert_eq!(manager.primary_focus(&app), Some(node));
        });
    }

    #[test]
    fn focus_of_reports_has_focus_on_the_ancestor_and_primary_focus_on_the_leaf() {
        test_widgets(|tester| {
            let app = tester.cell.borrow();
            let outer: Captured = Rc::default();
            let inner: Captured = Rc::default();
            let inner_sink = Rc::clone(&inner);
            let outer_sink = Rc::clone(&outer);
            drop(app);
            tester.pump_widget(
                Focus::new(Builder::new(move |app, context| {
                    outer_sink.set(Focus::maybe_of(app, context, false, true));
                    Focus::new(probe(&inner_sink)).autofocus(true).into_widget()
                }))
                .debug_label("outer")
                .into_widget(),
            );
            let app = tester.cell.borrow_mut();

            let outer = outer.get().expect("the outer Focus.of found nothing");
            let inner = inner.get().expect("the inner Focus.of found nothing");
            assert_ne!(outer, inner);
            assert_eq!(inner.parent(&app), Some(outer));
            assert!(inner.has_primary_focus(&app));
            assert!(inner.has_focus(&app));
            assert!(outer.has_focus(&app));
            assert!(!outer.has_primary_focus(&app));
            assert_eq!(outer.debug_label(&app).as_deref(), Some("outer"));
        });
    }

    #[test]
    fn focus_scope_of_returns_the_enclosing_scope() {
        test_widgets(|tester| {
            // With no FocusScope of its own, the context reaches the one the `View` installs, which
            // hangs off the root scope through the view's `FocusTraversalGroup`.
            let app = tester.cell.borrow();
            let scope_node = Rc::new(Cell::new(None));
            let sink = Rc::clone(&scope_node);
            drop(app);
            tester.pump_widget(
                Builder::new(move |app, context| {
                    sink.set(Some(FocusScope::of(app, context, true)));
                    SizedBox::shrink().into_widget()
                })
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let manager = FocusManager::instance(&mut app);
            let view_scope = scope_node.get().expect("FocusScope.of ran");
            assert_ne!(view_scope, manager.root_scope(&app).handle());
            assert_eq!(view_scope.debug_label(&app).as_deref(), Some("View Scope"));
            assert_eq!(
                view_scope.enclosing_scope(&mut app),
                Some(manager.root_scope(&app).handle())
            );
        });
        test_widgets(|tester| {
            // A FocusScope widget below the view scopes its own subtree instead.
            let app = tester.cell.borrow();
            let scope_node = Rc::new(Cell::new(None));
            let sink = Rc::clone(&scope_node);
            drop(app);
            tester.pump_widget(
                FocusScope::new(Builder::new(move |app, context| {
                    sink.set(Some(FocusScope::of(app, context, true)));
                    SizedBox::shrink().into_widget()
                }))
                .debug_label("scope")
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let manager = FocusManager::instance(&mut app);
            let scope = scope_node.get().expect("FocusScope.of ran");
            assert_ne!(scope, manager.root_scope(&app).handle());
            assert_eq!(scope.debug_label(&app).as_deref(), Some("scope"));
            assert_eq!(
                scope
                    .enclosing_scope(&mut app)
                    .and_then(|scope| scope.debug_label(&app)),
                Some("View Scope".to_string())
            );
        });
    }

    #[test]
    fn a_focus_widgets_on_key_event_receives_events_addressed_to_its_node() {
        test_widgets(|tester| {
            use std::time::Duration;

            use waft_services::{
                HardwareKeyboard, KeyDownEvent, KeyEvent, LogicalKeyboardKey, PhysicalKeyboardKey,
            };

            let app = tester.cell.borrow();
            let seen: Rc<RefCell<Vec<&'static str>>> = Rc::default();
            let inner_seen = Rc::clone(&seen);
            let outer_seen = Rc::clone(&seen);
            drop(app);
            tester.pump_widget(
                Focus::new(
                    Focus::new(SizedBox::shrink())
                        .autofocus(true)
                        .on_key_event(Rc::new(move |_app, _node, _event| {
                            inner_seen.borrow_mut().push("inner");
                            KeyEventResult::Ignored
                        })),
                )
                .on_key_event(Rc::new(move |_app, _node, _event| {
                    outer_seen.borrow_mut().push("outer");
                    KeyEventResult::Handled
                }))
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();

            let event = KeyEvent::Down(KeyDownEvent::new(
                PhysicalKeyboardKey::KEY_A,
                LogicalKeyboardKey::KEY_A,
                Duration::ZERO,
            ));
            let handled = HardwareKeyboard::instance(&mut app).handle_key_event(&mut app, &event);
            assert!(handled);
            assert_eq!(*seen.borrow(), vec!["inner", "outer"]);
        });
    }

    #[test]
    fn moving_a_focus_widget_by_global_key_keeps_its_node_and_its_focus() {
        test_widgets(|tester| {
            let app = tester.cell.borrow();
            let captured: Captured = Rc::default();
            let key = GlobalKey::new();
            drop(app);
            tester.pump_widget(
                Padding::new(waft_painting::EdgeInsetsGeometry::all(4.0))
                    .child(
                        Focus::new(probe(&captured))
                            .key(key.clone().into())
                            .autofocus(true),
                    )
                    .into_widget(),
            );
            let app = tester.cell.borrow();
            let node = captured.get().expect("Focus.of found the node");
            assert!(node.has_primary_focus(&app));

            drop(app);
            tester.pump_widget(
                Center::new()
                    .child(Focus::new(probe(&captured)).key(key.clone().into()))
                    .into_widget(),
            );
            let app = tester.cell.borrow();
            assert_eq!(captured.get(), Some(node));
            assert!(node.has_primary_focus(&app));
        });
    }

    #[test]
    fn exclude_focus_blocks_the_descendants() {
        test_widgets(|tester| {
            let app = tester.cell.borrow();
            let captured: Captured = Rc::default();
            drop(app);
            tester.pump_widget(ExcludeFocus::new(Focus::new(probe(&captured))).into_widget());
            let mut app = tester.cell.borrow_mut();
            let node = captured.get().expect("Focus.of found the node");
            assert!(!node.can_request_focus(&app));

            node.request_focus(&mut app, None);
            app.drain_microtasks();
            assert!(!node.has_primary_focus(&app));
        });
    }
}