waft-widgets 0.6.0

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
//! Flutter counterpart: `widgets/text.dart`, plus the public `RichText` from `basic.dart`.
//!
//! [`Text`] builds only the [`RichText`] branch: selection (`SelectionContainer.maybeOf`,
//! `_SelectableTextContainer`, `selectionColor`), `Locale`, and `Semantics` wait.

use waft_embedder::{Color, FontWeight, TextAlign, TextDirection, TextHeightBehavior};
use waft_foundation::App;
use waft_painting::{
    InlineSpanRef, StrutStyle, TextOverflow, TextScaler, TextSpan, TextStyle, TextWidthBasis,
};
use waft_rendering::{
    AnyRenderObject, RenderBox, RenderHandle, RenderParagraph, SelectionRegistrarRef,
};

use crate::framework::{
    BuildContext, InheritedWidget, IntoWidget, KeyRef, MultiChildRenderObjectWidget,
    RenderObjectWidget, StatelessWidget, WidgetRef,
};
use crate::view::View;
use crate::widgets::basic::{Builder, Directionality, ExcludeSemantics, Semantics};
use crate::widgets::inherited_theme::InheritedTheme;
use crate::widgets::media_query::MediaQuery;
use crate::widgets::widget_span::WidgetSpan;

// ---------------------------------------------------------------------------------------------
// DefaultTextStyle

/// The text style to apply to descendant [`Text`] widgets which don't have an explicit style.
///
/// A `MediaQuery` ancestor of a [`Text`] widget may still override the `TextStyle.height`,
/// `TextStyle.letterSpacing`, and `TextStyle.wordSpacing` of the [`TextStyle`] set by this
/// [`DefaultTextStyle`] widget through its `MediaQueryData.lineHeightScaleFactorOverride`,
/// `MediaQueryData.letterSpacingOverride`, and `MediaQueryData.wordSpacingOverride` members.
///
/// See also:
///
///  * `AnimatedDefaultTextStyle`, which animates changes in the text style smoothly over a
///    given duration.
///  * `DefaultTextStyleTransition`, which takes a provided `Animation` to animate changes in
///    text style smoothly over time.
///
/// Dart's named constructor arguments are the fluent setters
/// (`DefaultTextStyle::new(style, child).max_lines(2)`).
#[derive(Clone, Debug)]
pub struct DefaultTextStyle {
    /// See [`InheritedWidget::key`].
    pub key: Option<KeyRef>,
    /// The text style to apply.
    pub style: TextStyle,
    /// How each line of text in the Text widget should be aligned horizontally.
    pub text_align: Option<TextAlign>,
    /// Whether the text should break at soft line breaks.
    ///
    /// If false, the glyphs in the text will be positioned as if there was unlimited
    /// horizontal space.
    ///
    /// This also decides the `overflow` property's behavior. If this is true or null, the
    /// glyph causing overflow, and those that follow, will not be rendered.
    pub soft_wrap: bool,
    /// How visual overflow should be handled.
    ///
    /// If `soft_wrap` is true or null, the glyph causing overflow, and those that follow,
    /// will not be rendered. Otherwise, it will be shown with the given overflow option.
    pub overflow: TextOverflow,
    /// An optional maximum number of lines for the text to span, wrapping if necessary. If
    /// the text exceeds the given number of lines, it will be truncated according to
    /// `overflow`.
    ///
    /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the edge of the
    /// box.
    ///
    /// If this is non-null, it will override even explicit null values of `Text.max_lines`.
    pub max_lines: Option<i32>,
    /// The strategy to use when calculating the width of the Text.
    ///
    /// See [`TextWidthBasis`] for possible values and their implications.
    pub text_width_basis: TextWidthBasis,
    /// Defines how to apply `TextStyle.height` over and under text.
    pub text_height_behavior: Option<TextHeightBehavior>,
    /// The widget below this widget in the tree.
    pub child: WidgetRef,
}

impl DefaultTextStyle {
    /// Creates a default text style for the given subtree.
    ///
    /// Consider using `DefaultTextStyle.merge` to inherit styling information from the
    /// current default text style for a given [`BuildContext`].
    ///
    /// The `max_lines` property may be `None` (and indeed defaults to `None`), but if it is
    /// not `None`, it must be greater than zero.
    pub fn new<K>(style: TextStyle, child: impl IntoWidget<K>) -> DefaultTextStyle {
        DefaultTextStyle {
            key: None,
            style,
            text_align: None,
            soft_wrap: true,
            overflow: TextOverflow::Clip,
            max_lines: None,
            text_width_basis: TextWidthBasis::Parent,
            text_height_behavior: None,
            child: child.into_widget(),
        }
    }

    /// A default text style that provides fallback values.
    ///
    /// Returned from [`of`](Self::of) when the given [`BuildContext`] doesn't have an
    /// enclosing default text style.
    ///
    /// This constructor creates a [`DefaultTextStyle`] with an invalid `child`, which means
    /// the constructed value cannot be incorporated into the tree.
    pub fn fallback() -> DefaultTextStyle {
        DefaultTextStyle::new(TextStyle::new(), NullWidget)
    }

    /// Creates a default text style that overrides the text styles in scope at this point in
    /// the widget tree.
    ///
    /// The given `style` is merged with the `style` from the default text style for the
    /// [`BuildContext`] where the widget is inserted, and any of the other arguments that are
    /// not `None` replace the corresponding properties on that same default text style.
    ///
    /// This constructor cannot be used to override the `max_lines` property of the ancestor
    /// with the value `None`, since `None` here is used to mean "defer to ancestor". To
    /// replace a non-`None` `max_lines` from an ancestor with the `None` value (to remove the
    /// restriction on number of lines), manually obtain the ambient [`DefaultTextStyle`]
    /// using [`of`](Self::of), then create a new [`DefaultTextStyle`] using
    /// [`new`](Self::new) directly.
    ///
    /// If a `text_height_behavior` is provided, the existing configuration will be replaced
    /// completely. To retain part of the original `text_height_behavior`, manually obtain the
    /// ambient [`DefaultTextStyle`] using [`of`](Self::of).
    ///
    /// Dart's optional named arguments are the setters of the [`DefaultTextStyleMerge`] this
    /// returns.
    pub fn merge<K>(child: impl IntoWidget<K>) -> DefaultTextStyleMerge {
        DefaultTextStyleMerge {
            key: None,
            style: None,
            text_align: None,
            soft_wrap: None,
            overflow: None,
            max_lines: None,
            text_width_basis: None,
            text_height_behavior: None,
            child: child.into_widget(),
        }
    }

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

    /// Dart `DefaultTextStyle(textAlign:)`.
    pub fn text_align(mut self, text_align: TextAlign) -> DefaultTextStyle {
        self.text_align = Some(text_align);
        self
    }

    /// Dart `DefaultTextStyle(softWrap:)`.
    pub fn soft_wrap(mut self, soft_wrap: bool) -> DefaultTextStyle {
        self.soft_wrap = soft_wrap;
        self
    }

    /// Dart `DefaultTextStyle(overflow:)`.
    pub fn overflow(mut self, overflow: TextOverflow) -> DefaultTextStyle {
        self.overflow = overflow;
        self
    }

    /// Dart `DefaultTextStyle(maxLines:)`. Must be greater than zero.
    pub fn max_lines(mut self, max_lines: i32) -> DefaultTextStyle {
        debug_assert!(max_lines > 0);
        self.max_lines = Some(max_lines);
        self
    }

    /// Dart `DefaultTextStyle(textWidthBasis:)`.
    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> DefaultTextStyle {
        self.text_width_basis = text_width_basis;
        self
    }

    /// Dart `DefaultTextStyle(textHeightBehavior:)`.
    pub fn text_height_behavior(
        mut self,
        text_height_behavior: TextHeightBehavior,
    ) -> DefaultTextStyle {
        self.text_height_behavior = Some(text_height_behavior);
        self
    }

    /// The closest instance of this class that encloses the given context.
    ///
    /// If no such instance exists, returns an instance created by
    /// [`fallback`](Self::fallback), which contains fallback values.
    ///
    /// Typical usage is as follows:
    ///
    /// ```text
    /// let style = DefaultTextStyle::of(app, context);
    /// ```
    pub fn of(app: &mut App, context: BuildContext) -> DefaultTextStyle {
        context
            .depend_on_inherited_widget_of_exact_type::<DefaultTextStyle>(app)
            .cloned()
            .unwrap_or_else(DefaultTextStyle::fallback)
    }
}

/// Dart's `DefaultTextStyle.merge(..)` before its optional arguments are known: a `Builder`
/// that merges them into the ambient [`DefaultTextStyle`].
#[derive(Debug)]
pub struct DefaultTextStyleMerge {
    key: Option<KeyRef>,
    style: Option<TextStyle>,
    text_align: Option<TextAlign>,
    soft_wrap: Option<bool>,
    overflow: Option<TextOverflow>,
    max_lines: Option<i32>,
    text_width_basis: Option<TextWidthBasis>,
    text_height_behavior: Option<TextHeightBehavior>,
    child: WidgetRef,
}

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

    /// Dart `DefaultTextStyle.merge(style:)`.
    pub fn style(mut self, style: TextStyle) -> DefaultTextStyleMerge {
        self.style = Some(style);
        self
    }

    /// Dart `DefaultTextStyle.merge(textAlign:)`.
    pub fn text_align(mut self, text_align: TextAlign) -> DefaultTextStyleMerge {
        self.text_align = Some(text_align);
        self
    }

    /// Dart `DefaultTextStyle.merge(softWrap:)`.
    pub fn soft_wrap(mut self, soft_wrap: bool) -> DefaultTextStyleMerge {
        self.soft_wrap = Some(soft_wrap);
        self
    }

    /// Dart `DefaultTextStyle.merge(overflow:)`.
    pub fn overflow(mut self, overflow: TextOverflow) -> DefaultTextStyleMerge {
        self.overflow = Some(overflow);
        self
    }

    /// Dart `DefaultTextStyle.merge(maxLines:)`. Must be greater than zero.
    pub fn max_lines(mut self, max_lines: i32) -> DefaultTextStyleMerge {
        debug_assert!(max_lines > 0);
        self.max_lines = Some(max_lines);
        self
    }

    /// Dart `DefaultTextStyle.merge(textWidthBasis:)`.
    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> DefaultTextStyleMerge {
        self.text_width_basis = Some(text_width_basis);
        self
    }

    /// Dart `DefaultTextStyle.merge(textHeightBehavior:)`.
    pub fn text_height_behavior(
        mut self,
        text_height_behavior: TextHeightBehavior,
    ) -> DefaultTextStyleMerge {
        self.text_height_behavior = Some(text_height_behavior);
        self
    }
}

/// The kind tag of [`IntoWidget`] for a [`DefaultTextStyleMerge`].
pub struct DefaultTextStyleMergeKind;

impl IntoWidget<DefaultTextStyleMergeKind> for DefaultTextStyleMerge {
    fn into_widget(self) -> WidgetRef {
        Builder::new(move |app, context| {
            let parent = DefaultTextStyle::of(app, context);
            DefaultTextStyle {
                key: self.key.clone(),
                style: parent.style.merge(self.style.as_ref()),
                text_align: self.text_align.or(parent.text_align),
                soft_wrap: self.soft_wrap.unwrap_or(parent.soft_wrap),
                overflow: self.overflow.unwrap_or(parent.overflow),
                max_lines: self.max_lines.or(parent.max_lines),
                text_width_basis: self.text_width_basis.unwrap_or(parent.text_width_basis),
                text_height_behavior: self.text_height_behavior.or(parent.text_height_behavior),
                child: self.child.clone(),
            }
            .into_widget()
        })
        .into_widget()
    }
}

impl InheritedWidget for DefaultTextStyle {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &DefaultTextStyle) -> bool {
        self.style != old_widget.style
            || self.text_align != old_widget.text_align
            || self.soft_wrap != old_widget.soft_wrap
            || self.overflow != old_widget.overflow
            || self.max_lines != old_widget.max_lines
            || self.text_width_basis != old_widget.text_width_basis
            || self.text_height_behavior != old_widget.text_height_behavior
    }

    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
        Some(self)
    }
}

impl InheritedTheme for DefaultTextStyle {
    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
        DefaultTextStyle {
            key: None,
            style: self.style.clone(),
            text_align: self.text_align,
            soft_wrap: self.soft_wrap,
            overflow: self.overflow,
            max_lines: self.max_lines,
            text_width_basis: self.text_width_basis,
            text_height_behavior: self.text_height_behavior,
            child,
        }
        .into_widget()
    }
}

/// Dart's `_NullWidget`: the child of [`DefaultTextStyle::fallback`], which must never build.
#[derive(Debug)]
struct NullWidget;

impl StatelessWidget for NullWidget {
    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        panic!(
            "A DefaultTextStyle constructed with DefaultTextStyle::fallback cannot be \
             incorporated into the widget tree, it is meant only to provide a fallback value \
             returned by DefaultTextStyle::of() when no enclosing default text style is \
             present in a BuildContext."
        );
    }
}

// ---------------------------------------------------------------------------------------------
// DefaultTextHeightBehavior

/// The [`TextHeightBehavior`] that will apply to descendant [`Text`] and `EditableText`
/// widgets which have not explicitly set `Text.text_height_behavior`.
///
/// If there is a [`DefaultTextStyle`] with a non-null `DefaultTextStyle.text_height_behavior`
/// below this widget, the `DefaultTextStyle.text_height_behavior` will be used over this
/// widget's [`TextHeightBehavior`].
///
/// See also:
///
///  * [`DefaultTextStyle`], which defines a [`TextStyle`] to apply to descendant [`Text`]
///    widgets.
#[derive(Debug)]
pub struct DefaultTextHeightBehavior {
    /// See [`InheritedWidget::key`].
    pub key: Option<KeyRef>,
    /// Defines how to apply `TextStyle.height` over and under text.
    pub text_height_behavior: TextHeightBehavior,
    /// The widget below this widget in the tree.
    pub child: WidgetRef,
}

impl DefaultTextHeightBehavior {
    /// Creates a default text height behavior for the given subtree.
    pub fn new<K>(
        text_height_behavior: TextHeightBehavior,
        child: impl IntoWidget<K>,
    ) -> DefaultTextHeightBehavior {
        DefaultTextHeightBehavior {
            key: None,
            text_height_behavior,
            child: child.into_widget(),
        }
    }

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

    /// The closest instance of [`DefaultTextHeightBehavior`] that encloses the given
    /// context, or `None` if none is found.
    ///
    /// Calling this method will create a dependency on the closest
    /// [`DefaultTextHeightBehavior`] in the `context`, if there is one.
    ///
    /// See also:
    ///
    /// * [`of`](Self::of), which is similar to this method, but asserts if no
    ///   [`DefaultTextHeightBehavior`] ancestor is found.
    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<TextHeightBehavior> {
        context
            .depend_on_inherited_widget_of_exact_type::<DefaultTextHeightBehavior>(app)
            .map(|widget| widget.text_height_behavior)
    }

    /// The closest instance of [`DefaultTextHeightBehavior`] that encloses the given
    /// context.
    ///
    /// If no such instance exists, this method panics.
    ///
    /// Calling this method will create a dependency on the closest
    /// [`DefaultTextHeightBehavior`] in the `context`.
    ///
    /// See also:
    ///
    /// * [`maybe_of`](Self::maybe_of), which is similar to this method, but returns `None`
    ///   if no [`DefaultTextHeightBehavior`] ancestor is found.
    pub fn of(app: &mut App, context: BuildContext) -> TextHeightBehavior {
        let behavior = Self::maybe_of(app, context);
        behavior.expect(
            "DefaultTextHeightBehavior::of() was called with a context that does not contain \
             a DefaultTextHeightBehavior widget.\n\
             No DefaultTextHeightBehavior widget ancestor could be found starting from the \
             context that was passed to DefaultTextHeightBehavior::of(). This can happen \
             because you are using a widget that looks for a DefaultTextHeightBehavior \
             ancestor, but no such ancestor exists.",
        )
    }
}

impl InheritedWidget for DefaultTextHeightBehavior {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn child(&self) -> &WidgetRef {
        &self.child
    }

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

    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
        Some(self)
    }
}

impl InheritedTheme for DefaultTextHeightBehavior {
    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
        DefaultTextHeightBehavior::new(self.text_height_behavior, child).into_widget()
    }
}

// ---------------------------------------------------------------------------------------------
// Text

/// A run of text with a single style.
///
/// The [`Text`] widget displays a string of text with single style. The string might break
/// across multiple lines or might all be displayed on the same line depending on the layout
/// constraints.
///
/// The `style` argument is optional. When omitted, the text will use the style from the
/// closest enclosing [`DefaultTextStyle`]. If the given style's `TextStyle.inherit` property
/// is true (the default), the given style will be merged with the closest enclosing
/// [`DefaultTextStyle`]. This merging behavior is useful, for example, to make the text bold
/// while using the default font family and size.
///
/// This example shows how to display text using the [`Text`] widget with the `overflow` set
/// to [`TextOverflow::Ellipsis`].
///
/// ```text
/// Text::new("Hello, how are you?").overflow(TextOverflow::Ellipsis)
/// ```
///
/// Setting `max_lines` to `1` is not equivalent to disabling soft wrapping with `soft_wrap`.
/// This is apparent when using [`TextOverflow::Fade`]: with `max_lines(1)` a second line
/// overflows and the fade appears in a horizontal direction at the bottom; with
/// `soft_wrap(false)` the single line overflows and the fade appears in a vertical direction
/// at the right.
///
/// Using the [`rich`](Self::rich) constructor, the [`Text`] widget can display a paragraph
/// with differently styled [`TextSpan`]s.
///
/// ## Interactivity
///
/// To make [`Text`] react to touch events, wrap it in a `GestureDetector` widget with a
/// `GestureDetector.on_tap` handler.
///
/// To make sections of the text interactive, use [`RichText`] and specify a
/// `TapGestureRecognizer` as the `TextSpan.recognizer` of the relevant part of the text.
///
/// ## Selection
///
/// [`Text`] is not selectable by default. To make a [`Text`] selectable, one can wrap a
/// subtree with a `SelectionArea` widget.
///
/// See also:
///
///  * [`RichText`], which gives you more control over the text styles.
///  * [`DefaultTextStyle`], which sets default styles for [`Text`] widgets.
///
/// Dart's named constructor arguments are the fluent setters
/// (`Text::new("Hi").max_lines(1)`).
#[derive(Debug)]
pub struct Text {
    /// See [`StatelessWidget::key`].
    pub key: Option<KeyRef>,
    /// The text to display.
    ///
    /// This will be `None` if a `text_span` is provided instead.
    pub data: Option<String>,
    /// The text to display as an [`InlineSpan`](waft_painting::InlineSpan).
    ///
    /// This will be `None` if `data` is provided instead.
    pub text_span: Option<InlineSpanRef>,
    /// If non-null, the style to use for this text.
    ///
    /// If the style's "inherit" property is true, the style will be merged with the closest
    /// enclosing [`DefaultTextStyle`]. Otherwise, the style will replace the closest
    /// enclosing [`DefaultTextStyle`].
    pub style: Option<TextStyle>,
    /// The strut style to use. Strut style defines the strut, which sets minimum vertical
    /// layout metrics.
    ///
    /// Omitting or providing `None` will disable strut.
    ///
    /// The user or platform may override this strut's [`StrutStyle::height`] via a
    /// [`MediaQuery`] ancestor's `MediaQueryData.lineHeightScaleFactorOverride`.
    pub strut_style: Option<StrutStyle>,
    /// How the text should be aligned horizontally.
    pub text_align: Option<TextAlign>,
    /// The directionality of the text.
    ///
    /// This decides how `text_align` values like [`TextAlign::Start`] and [`TextAlign::End`]
    /// are interpreted.
    ///
    /// This is also used to disambiguate how to render bidirectional text. For example, if
    /// the `data` is an English phrase followed by a Hebrew phrase, in a
    /// [`TextDirection::Ltr`] context the English phrase will be on the left and the Hebrew
    /// phrase to its right, while in a [`TextDirection::Rtl`] context, the English phrase
    /// will be on the right and the Hebrew phrase on its left.
    ///
    /// Defaults to the ambient `Directionality`, if any.
    pub text_direction: Option<TextDirection>,
    /// Whether the text should break at soft line breaks.
    ///
    /// If false, the glyphs in the text will be positioned as if there was unlimited
    /// horizontal space.
    pub soft_wrap: Option<bool>,
    /// How visual overflow should be handled.
    ///
    /// If this is `None`, `TextStyle.overflow` will be used, otherwise the value from the
    /// nearest [`DefaultTextStyle`] ancestor will be used.
    pub overflow: Option<TextOverflow>,
    /// The font scaling strategy to use when laying out and rendering the text.
    pub text_scaler: Option<TextScaler>,
    /// An optional maximum number of lines for the text to span, wrapping if necessary. If
    /// the text exceeds the given number of lines, it will be truncated according to
    /// `overflow`.
    ///
    /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the edge of the
    /// box.
    ///
    /// If this is `None`, but there is an ambient [`DefaultTextStyle`] that specifies an
    /// explicit number for its `DefaultTextStyle.max_lines`, then the [`DefaultTextStyle`]
    /// value will take precedence. You can use a [`RichText`] widget directly to entirely
    /// override the [`DefaultTextStyle`].
    pub max_lines: Option<i32>,
    /// An alternative semantics label for this text.
    ///
    /// If present, the semantics of this widget will contain this value instead
    /// of the actual text. This will overwrite any of the semantics labels applied
    /// directly to the [`TextSpan`]s.
    ///
    /// This is useful for replacing abbreviations or shorthands with the full
    /// text value: `Text::new("$$").semantics_label("Double dollars")`.
    pub semantics_label: Option<String>,
    /// A unique identifier for the semantics node for this widget.
    ///
    /// This is useful for cases where the text widget needs to have a uniquely
    /// identifiable ID that is recognized through the automation tools without
    /// having a dependency on the actual content of the text that can possibly be
    /// dynamic in nature.
    pub semantics_identifier: Option<String>,
    /// Defines how to measure the width of the rendered text.
    pub text_width_basis: Option<TextWidthBasis>,
    /// Defines how to apply `TextStyle.height` over and under text.
    pub text_height_behavior: Option<TextHeightBehavior>,
}

impl Text {
    /// Creates a text widget.
    ///
    /// If the `style` argument is `None`, the text will use the style from the closest
    /// enclosing [`DefaultTextStyle`].
    ///
    /// The `overflow` property's behavior is affected by the `soft_wrap` argument. If the
    /// `soft_wrap` is true or `None`, the glyph causing overflow, and those that follow, will
    /// not be rendered. Otherwise, it will be shown with the given overflow option.
    pub fn new(data: impl Into<String>) -> Text {
        Text::unstyled(Some(data.into()), None)
    }

    /// Creates a text widget with an [`InlineSpan`](waft_painting::InlineSpan).
    ///
    /// The following subclasses of `InlineSpan` may be used to build rich text:
    ///
    /// * [`TextSpan`]s define text and children `InlineSpan`s.
    /// * `WidgetSpan`s define embedded inline widgets.
    ///
    /// See [`RichText`] which provides a lower-level way to draw text.
    pub fn rich(text_span: InlineSpanRef) -> Text {
        Text::unstyled(None, Some(text_span))
    }

    /// The fields both constructors leave unset.
    fn unstyled(data: Option<String>, text_span: Option<InlineSpanRef>) -> Text {
        Text {
            key: None,
            data,
            text_span,
            style: None,
            strut_style: None,
            text_align: None,
            text_direction: None,
            soft_wrap: None,
            overflow: None,
            text_scaler: None,
            max_lines: None,
            semantics_label: None,
            semantics_identifier: None,
            text_width_basis: None,
            text_height_behavior: None,
        }
    }

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

    /// Dart `Text(style:)`.
    pub fn style(mut self, style: TextStyle) -> Text {
        self.style = Some(style);
        self
    }

    /// Dart `Text(strutStyle:)`.
    pub fn strut_style(mut self, strut_style: StrutStyle) -> Text {
        self.strut_style = Some(strut_style);
        self
    }

    /// Dart `Text(textAlign:)`.
    pub fn text_align(mut self, text_align: TextAlign) -> Text {
        self.text_align = Some(text_align);
        self
    }

    /// Dart `Text(textDirection:)`.
    pub fn text_direction(mut self, text_direction: TextDirection) -> Text {
        self.text_direction = Some(text_direction);
        self
    }

    /// Dart `Text(softWrap:)`.
    pub fn soft_wrap(mut self, soft_wrap: bool) -> Text {
        self.soft_wrap = Some(soft_wrap);
        self
    }

    /// Dart `Text(overflow:)`.
    pub fn overflow(mut self, overflow: TextOverflow) -> Text {
        self.overflow = Some(overflow);
        self
    }

    /// Dart `Text(textScaler:)`.
    pub fn text_scaler(mut self, text_scaler: TextScaler) -> Text {
        self.text_scaler = Some(text_scaler);
        self
    }

    /// Dart `Text(maxLines:)`.
    pub fn max_lines(mut self, max_lines: i32) -> Text {
        self.max_lines = Some(max_lines);
        self
    }

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

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

    /// Dart `Text(textWidthBasis:)`.
    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> Text {
        self.text_width_basis = Some(text_width_basis);
        self
    }

    /// Dart `Text(textHeightBehavior:)`.
    pub fn text_height_behavior(mut self, text_height_behavior: TextHeightBehavior) -> Text {
        self.text_height_behavior = Some(text_height_behavior);
        self
    }
}

impl StatelessWidget for Text {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let default_text_style = DefaultTextStyle::of(app, context);
        let mut effective_text_style = self.style.clone();
        if self.style.as_ref().is_none_or(|style| style.inherit) {
            effective_text_style = Some(default_text_style.style.merge(self.style.as_ref()));
        }
        if MediaQuery::bold_text_of(app, context) {
            let bold = TextStyle::new().font_weight(FontWeight::BOLD);
            effective_text_style = Some(
                effective_text_style
                    .expect("the style is set above")
                    .merge(Some(&bold)),
            );
        }
        // Flutter leaves `MediaQueryData.paragraphSpacingOverride` to its own text components.
        let line_height_scale_factor =
            MediaQuery::maybe_line_height_scale_factor_override_of(app, context);
        let letter_spacing = MediaQuery::maybe_letter_spacing_override_of(app, context);
        let word_spacing = MediaQuery::maybe_word_spacing_override_of(app, context);
        let effective_text_span = apply_text_spacing_overrides(
            line_height_scale_factor,
            letter_spacing,
            word_spacing,
            TextSpan {
                style: effective_text_style.clone(),
                text: self.data.clone(),
                children: self
                    .text_span
                    .as_ref()
                    .map(|text_span| vec![text_span.clone()]),
                ..TextSpan::default()
            },
        );
        let effective_strut_style = self.strut_style.as_ref().map(|strut_style| {
            line_height_scale_factor.map_or_else(
                || strut_style.clone(),
                |height| strut_style.merge(Some(&StrutStyle::new().height(height))),
            )
        });
        let text_scaler = self
            .text_scaler
            .clone()
            .unwrap_or_else(|| MediaQuery::text_scaler_of(app, context));
        let text_height_behavior = self
            .text_height_behavior
            .or(default_text_style.text_height_behavior)
            .or_else(|| DefaultTextHeightBehavior::maybe_of(app, context));
        let mut rich_text = RichText::new(effective_text_span.into_span())
            .text_align(
                self.text_align
                    .or(default_text_style.text_align)
                    .unwrap_or(TextAlign::Start),
            )
            .soft_wrap(self.soft_wrap.unwrap_or(default_text_style.soft_wrap))
            .overflow(
                self.overflow
                    .or(effective_text_style
                        .as_ref()
                        .and_then(|style| style.overflow))
                    .unwrap_or(default_text_style.overflow),
            )
            .text_scaler(text_scaler)
            .text_width_basis(
                self.text_width_basis
                    .unwrap_or(default_text_style.text_width_basis),
            );
        // RichText uses Directionality.of to obtain a default if this is None.
        if let Some(text_direction) = self.text_direction {
            rich_text = rich_text.text_direction(text_direction);
        }
        if let Some(max_lines) = self.max_lines.or(default_text_style.max_lines) {
            rich_text = rich_text.max_lines(max_lines);
        }
        if let Some(text_height_behavior) = text_height_behavior {
            rich_text = rich_text.text_height_behavior(text_height_behavior);
        }
        if let Some(strut_style) = effective_strut_style {
            rich_text = rich_text.strut_style(strut_style);
        }
        let mut result = rich_text.into_widget();
        if self.semantics_label.is_some() || self.semantics_identifier.is_some() {
            let mut semantics = Semantics::new();
            if let Some(text_direction) = self.text_direction {
                semantics = semantics.text_direction(text_direction);
            }
            if let Some(semantics_label) = &self.semantics_label {
                semantics = semantics.label(semantics_label.clone());
            }
            if let Some(semantics_identifier) = &self.semantics_identifier {
                semantics = semantics.identifier(semantics_identifier.clone());
            }
            result = semantics
                .child(
                    ExcludeSemantics::new()
                        .excluding(self.semantics_label.is_some())
                        .child(result),
                )
                .into_widget();
        }
        result
    }
}

// ---------------------------------------------------------------------------------------------
// RichText (basic.dart)

/// Dart's `_OverridingTextStyleTextSpanUtils.applyTextSpacingOverrides`: overrides the text
/// styles of a [`TextSpan`] tree with the `MediaQuery` spacing overrides.
pub(crate) fn apply_text_spacing_overrides(
    line_height_scale_factor: Option<f64>,
    letter_spacing: Option<f64>,
    word_spacing: Option<f64>,
    text_span: TextSpan,
) -> TextSpan {
    if line_height_scale_factor.is_none() && letter_spacing.is_none() && word_spacing.is_none() {
        return text_span;
    }
    let mut override_text_style = TextStyle::new();
    if let Some(height) = line_height_scale_factor {
        override_text_style = override_text_style.height(height);
    }
    if let Some(letter_spacing) = letter_spacing {
        override_text_style = override_text_style.letter_spacing(letter_spacing);
    }
    if let Some(word_spacing) = word_spacing {
        override_text_style = override_text_style.word_spacing(word_spacing);
    }
    apply_text_style_overrides(&override_text_style, &text_span)
}

/// Dart's `_OverridingTextStyleTextSpanUtils._applyTextStyleOverrides`.
fn apply_text_style_overrides(override_text_style: &TextStyle, text_span: &TextSpan) -> TextSpan {
    TextSpan {
        text: text_span.text.clone(),
        children: text_span.children.as_ref().map(|children| {
            children
                .iter()
                .map(|child| match child.as_any().downcast_ref::<TextSpan>() {
                    Some(child) => {
                        apply_text_style_overrides(override_text_style, child).into_span()
                    }
                    None => child.clone(),
                })
                .collect()
        }),
        style: Some(match &text_span.style {
            Some(style) => style.merge(Some(override_text_style)),
            None => override_text_style.clone(),
        }),
        recognizer: text_span.recognizer.clone(),
        mouse_cursor: text_span.mouse_cursor.clone(),
        on_enter: text_span.on_enter.clone(),
        on_exit: text_span.on_exit.clone(),
    }
}

/// A paragraph of rich text.
///
/// The [`RichText`] widget displays text that uses multiple different styles. The text to
/// display is described using a tree of [`TextSpan`] objects, each of which has an
/// associated style that is used for that subtree. The text might break across multiple
/// lines or might all be displayed on the same line depending on the layout constraints.
///
/// Text displayed in a [`RichText`] widget must be explicitly styled. When picking which
/// style to use, consider using [`DefaultTextStyle::of`] the current [`BuildContext`] to
/// provide defaults. For more details on how to style text in a [`RichText`] widget, see the
/// documentation for [`TextStyle`].
///
/// Consider using the [`Text`] widget to integrate with the [`DefaultTextStyle`]
/// automatically. When all the text uses the same style, the default constructor is less
/// verbose. The [`Text::rich`] constructor allows you to style multiple spans with the
/// default text style while still allowing specified styles per span.
///
/// ```text
/// RichText::new(
///     TextSpan::new()
///         .text("Hello ")
///         .style(DefaultTextStyle::of(app, context).style)
///         .children(vec![
///             TextSpan::new().text("bold").style(TextStyle::new().font_weight(FontWeight::BOLD)).into_span(),
///             TextSpan::new().text(" world!").into_span(),
///         ])
///         .into_span(),
/// )
/// ```
///
/// See also:
///
///  * [`TextStyle`], which discusses how to style text.
///  * [`TextSpan`], which is used to describe the text in a paragraph.
///  * [`Text`], which automatically applies the ambient styles described by a
///    [`DefaultTextStyle`] to a single string.
///  * [`Text::rich`], a text widget that provides similar functionality as [`RichText`].
///    [`Text::rich`] will inherit [`TextStyle`] from [`DefaultTextStyle`].
///
/// Dart's named constructor arguments are the fluent setters
/// (`RichText::new(span).text_align(TextAlign::Center)`).
#[derive(Debug)]
pub struct RichText {
    /// See [`RenderObjectWidget::key`].
    pub key: Option<KeyRef>,
    /// The text to display in this widget.
    pub text: InlineSpanRef,
    /// The inline widgets of [`text`](Self::text), its `WidgetSpan`s at
    /// [`text_scaler`](Self::text_scaler), as Dart's constructor extracts them.
    children: Vec<WidgetRef>,
    /// How the text should be aligned horizontally.
    pub text_align: TextAlign,
    /// The directionality of the text.
    ///
    /// This decides how `text_align` values like [`TextAlign::Start`] and [`TextAlign::End`]
    /// are interpreted.
    ///
    /// This is also used to disambiguate how to render bidirectional text. For example, if
    /// the `text` is an English phrase followed by a Hebrew phrase, in a
    /// [`TextDirection::Ltr`] context the English phrase will be on the left and the Hebrew
    /// phrase to its right, while in a [`TextDirection::Rtl`] context, the English phrase
    /// will be on the right and the Hebrew phrase on its left.
    ///
    /// Defaults to the ambient `Directionality`, if any. If there is no ambient
    /// `Directionality`, then this must not be `None`.
    pub text_direction: Option<TextDirection>,
    /// Whether the text should break at soft line breaks.
    ///
    /// If false, the glyphs in the text will be positioned as if there was unlimited
    /// horizontal space.
    pub soft_wrap: bool,
    /// How visual overflow should be handled.
    pub overflow: TextOverflow,
    /// The font scaling strategy to use when laying out and rendering the text.
    pub text_scaler: TextScaler,
    /// An optional maximum number of lines for the text to span, wrapping if necessary. If
    /// the text exceeds the given number of lines, it will be truncated according to
    /// `overflow`.
    ///
    /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the edge of the
    /// box.
    pub max_lines: Option<i32>,
    /// The strut style to use. Strut style defines the strut, which sets minimum vertical
    /// layout metrics.
    pub strut_style: Option<StrutStyle>,
    /// Defines how to measure the width of the rendered text.
    pub text_width_basis: TextWidthBasis,
    /// Defines how to apply `TextStyle.height` over and under text.
    pub text_height_behavior: Option<TextHeightBehavior>,
    /// The [`SelectionRegistrar`](waft_rendering::SelectionRegistrar) this rich text is
    /// subscribed to.
    ///
    /// If this is set, [`selection_color`](Self::selection_color) must be non-null.
    pub selection_registrar: Option<SelectionRegistrarRef>,
    /// The color to use when painting the selection.
    pub selection_color: Option<Color>,
}

impl RichText {
    /// Creates a paragraph of rich text.
    ///
    /// The `max_lines` property may be `None` (and indeed defaults to `None`), but if it is
    /// not `None`, it must be greater than zero.
    ///
    /// The `text_direction`, if `None`, defaults to the ambient `Directionality`, which in
    /// that case must not be null.
    pub fn new(text: InlineSpanRef) -> RichText {
        RichText {
            key: None,
            children: WidgetSpan::extract_from_inline_span(&*text, &TextScaler::NO_SCALING),
            text,
            text_align: TextAlign::Start,
            text_direction: None,
            soft_wrap: true,
            overflow: TextOverflow::Clip,
            text_scaler: TextScaler::NO_SCALING,
            max_lines: None,
            strut_style: None,
            text_width_basis: TextWidthBasis::Parent,
            text_height_behavior: None,
            selection_registrar: None,
            selection_color: None,
        }
    }

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

    /// Dart `RichText(textAlign:)`.
    pub fn text_align(mut self, text_align: TextAlign) -> RichText {
        self.text_align = text_align;
        self
    }

    /// Dart `RichText(textDirection:)`.
    pub fn text_direction(mut self, text_direction: TextDirection) -> RichText {
        self.text_direction = Some(text_direction);
        self
    }

    /// Dart `RichText(softWrap:)`.
    pub fn soft_wrap(mut self, soft_wrap: bool) -> RichText {
        self.soft_wrap = soft_wrap;
        self
    }

    /// Dart `RichText(overflow:)`.
    pub fn overflow(mut self, overflow: TextOverflow) -> RichText {
        self.overflow = overflow;
        self
    }

    /// Dart `RichText(textScaler:)`.
    pub fn text_scaler(mut self, text_scaler: TextScaler) -> RichText {
        self.children = WidgetSpan::extract_from_inline_span(&*self.text, &text_scaler);
        self.text_scaler = text_scaler;
        self
    }

    /// Dart `RichText(maxLines:)`. Must be greater than zero.
    pub fn max_lines(mut self, max_lines: i32) -> RichText {
        debug_assert!(max_lines > 0);
        self.max_lines = Some(max_lines);
        self
    }

    /// Dart `RichText(strutStyle:)`.
    pub fn strut_style(mut self, strut_style: StrutStyle) -> RichText {
        self.strut_style = Some(strut_style);
        self
    }

    /// Dart `RichText(textWidthBasis:)`.
    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> RichText {
        self.text_width_basis = text_width_basis;
        self
    }

    /// Dart `RichText(textHeightBehavior:)`.
    pub fn text_height_behavior(mut self, text_height_behavior: TextHeightBehavior) -> RichText {
        self.text_height_behavior = Some(text_height_behavior);
        self
    }

    /// Dart `RichText(selectionRegistrar:)`.
    pub fn selection_registrar(mut self, registrar: SelectionRegistrarRef) -> RichText {
        self.selection_registrar = Some(registrar);
        self
    }

    /// Dart `RichText(selectionColor:)`.
    pub fn selection_color(mut self, color: Color) -> RichText {
        self.selection_color = Some(color);
        self
    }

    /// Dart's `_getDevicePixelRatio`.
    fn device_pixel_ratio(app: &mut App, context: BuildContext) -> f64 {
        MediaQuery::maybe_device_pixel_ratio_of(app, context)
            .or_else(|| View::maybe_of(app, context).map(|view| view.metrics().device_pixel_ratio))
            .unwrap_or(1.0)
    }
}

impl RenderObjectWidget for RichText {
    type RenderObject = RenderParagraph;

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

    fn debug_check_constructor(&self) {
        debug_assert!(self.selection_registrar.is_none() || self.selection_color.is_some());
    }

    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
        let text_direction = self
            .text_direction
            .unwrap_or_else(|| Directionality::of(app, context));
        let device_pixel_ratio = Self::device_pixel_ratio(app, context);
        let render_object = RenderParagraph::new(app, self.text.clone(), text_direction, None);
        render_object.set_text_align(app, self.text_align);
        render_object.set_soft_wrap(app, self.soft_wrap);
        render_object.set_overflow(app, self.overflow);
        render_object.set_text_scaler(app, self.text_scaler.clone());
        render_object.set_max_lines(app, self.max_lines);
        render_object.set_text_width_basis(app, self.text_width_basis);
        render_object.set_text_height_behavior(app, self.text_height_behavior);
        render_object.set_strut_style(app, self.strut_style.clone());
        render_object.set_device_pixel_ratio(app, device_pixel_ratio);
        render_object.set_registrar(app, self.selection_registrar.clone());
        render_object.set_selection_color(app, self.selection_color);
        render_object.as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        context: BuildContext,
        render_object: RenderHandle<RenderParagraph>,
    ) {
        let text_direction = self
            .text_direction
            .unwrap_or_else(|| Directionality::of(app, context));
        render_object.set_text(app, self.text.clone());
        render_object.set_text_align(app, self.text_align);
        render_object.set_text_direction(app, text_direction);
        render_object.set_soft_wrap(app, self.soft_wrap);
        render_object.set_overflow(app, self.overflow);
        render_object.set_text_scaler(app, self.text_scaler.clone());
        render_object.set_max_lines(app, self.max_lines);
        render_object.set_text_width_basis(app, self.text_width_basis);
        render_object.set_text_height_behavior(app, self.text_height_behavior);
        render_object.set_strut_style(app, self.strut_style.clone());
        let device_pixel_ratio = Self::device_pixel_ratio(app, context);
        render_object.set_device_pixel_ratio(app, device_pixel_ratio);
        render_object.set_registrar(app, self.selection_registrar.clone());
        render_object.set_selection_color(app, self.selection_color);
    }
}

impl MultiChildRenderObjectWidget for RichText {
    fn children(&self) -> &[WidgetRef] {
        &self.children
    }
}

#[cfg(test)]
mod tests {
    use waft_foundation::AppCell;

    use waft_embedder::{Color, Size, TextLeadingDistribution};
    use waft_foundation::ValueKey;
    use waft_painting::PaintingBinding;

    use crate::{PlaceholderDimensions, TextPainter};

    use super::*;
    use crate::test_harness::Harness;
    use crate::widgets::media_query::MediaQueryData;

    /// What the shell does at start-up: the app-wide fonts, here the OS fonts.
    fn install_fonts(app: &mut App) {
        let binding = PaintingBinding::instance(app);
        if !binding.has_fonts(app) {
            binding.install_fonts(app, |fonts| {
                fonts.add_source(valo_system_fonts::SystemFonts::load());
            });
        }
    }

    /// Dart tests wrap text in a `Directionality`, which `RichText` requires.
    fn ltr(child: WidgetRef) -> WidgetRef {
        Directionality::new(TextDirection::Ltr, child).into_widget()
    }

    /// Mounts `child` with fonts installed and pumps the first frame.
    fn mount(app: &mut App, child: WidgetRef) -> Harness {
        install_fonts(app);
        let harness = Harness::mount(app, ltr(child));
        harness.pump(app);
        harness
    }

    /// The `RenderParagraph` directly under the test root.
    fn paragraph_under_root(harness: &Harness, app: &App) -> RenderHandle<RenderParagraph> {
        harness
            .render_root(app)
            .child(app)
            .expect("a child")
            .as_object()
            .downcast::<RenderParagraph>(app)
            .expect("a RenderParagraph")
    }

    fn style_of(paragraph: RenderHandle<RenderParagraph>, app: &App) -> TextStyle {
        paragraph
            .text(app)
            .style()
            .cloned()
            .expect("Text always styles its span")
    }

    fn plain_text_of(paragraph: RenderHandle<RenderParagraph>, app: &App) -> String {
        paragraph.text(app).to_plain_text(true, true)
    }

    #[test]
    fn a_text_lays_out_a_paragraph_with_the_fallback_style() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = mount(&mut app, Text::new("Hello").into_widget());
        let paragraph = paragraph_under_root(&harness, &app);
        let size = paragraph.size(&app);
        assert!(size.width() > 0.0 && size.height() > 0.0);
        assert_eq!(plain_text_of(paragraph, &app), "Hello");
        assert_eq!(
            style_of(paragraph, &app),
            TextStyle::new(),
            "DefaultTextStyle::fallback"
        );
        assert_eq!(paragraph.text_direction(&app), TextDirection::Ltr);
        assert_eq!(paragraph.text_align(&app), TextAlign::Start);
        assert_eq!(paragraph.max_lines(&app), None);
        assert_eq!(paragraph.overflow(&app), TextOverflow::Clip);
    }

    #[test]
    fn a_rich_text_span_becomes_the_child_of_the_styled_span() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let span = TextSpan::new().text("Hello").into_span();
        let harness = mount(&mut app, Text::rich(span).into_widget());
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(plain_text_of(paragraph, &app), "Hello");
        assert!(paragraph.size(&app).width() > 0.0);
    }

    #[test]
    fn a_default_text_style_styles_the_text_and_notifies_on_change() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        // One Text instance, reused like a `const` widget, so only the default style decides
        // rebuilds.
        let text: WidgetRef = Text::new("Hello").into_widget();
        let styled = |font_size: f64| {
            DefaultTextStyle::new(TextStyle::new().font_size(font_size), text.clone()).into_widget()
        };
        let harness = mount(&mut app, styled(12.0));
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(style_of(paragraph, &app).font_size, Some(12.0));
        let small = paragraph.size(&app);

        harness.set_child(&mut app, ltr(styled(24.0)));
        harness.pump(&mut app);
        assert_eq!(
            paragraph_under_root(&harness, &app),
            paragraph,
            "the same paragraph is restyled"
        );
        assert_eq!(style_of(paragraph, &app).font_size, Some(24.0));
        assert!(paragraph.size(&app).height() > small.height());
    }

    #[test]
    fn an_explicit_style_merges_into_the_default_unless_it_does_not_inherit() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let red = Color::from_argb(255, 255, 0, 0);
        let under_default = |style: TextStyle| {
            DefaultTextStyle::new(
                TextStyle::new().font_size(12.0),
                Text::new("Hello").style(style),
            )
            .into_widget()
        };
        let harness = mount(&mut app, under_default(TextStyle::new().color(red)));
        let paragraph = paragraph_under_root(&harness, &app);
        let merged = style_of(paragraph, &app);
        assert_eq!(merged.font_size, Some(12.0));
        assert_eq!(merged.color, Some(red.into()));

        harness.set_child(
            &mut app,
            ltr(under_default(
                TextStyle::new().inherit(false).font_size(30.0),
            )),
        );
        harness.pump(&mut app);
        let replaced = style_of(paragraph, &app);
        assert_eq!(replaced.font_size, Some(30.0));
        assert_eq!(
            replaced.color, None,
            "a non-inheriting style replaces the default"
        );
    }

    #[test]
    fn a_new_string_updates_the_same_paragraph() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = mount(&mut app, Text::new("Hello").into_widget());
        let paragraph = paragraph_under_root(&harness, &app);
        let short = paragraph.size(&app);

        harness.set_child(&mut app, ltr(Text::new("Hello there, world").into_widget()));
        harness.pump(&mut app);
        assert_eq!(paragraph_under_root(&harness, &app), paragraph);
        assert_eq!(plain_text_of(paragraph, &app), "Hello there, world");
        assert!(paragraph.size(&app).width() > short.width());
    }

    #[test]
    fn max_lines_and_overflow_reach_the_render_object() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = mount(
            &mut app,
            Text::new("Hello")
                .max_lines(2)
                .overflow(TextOverflow::Ellipsis)
                .soft_wrap(false)
                .text_direction(TextDirection::Rtl)
                .text_align(TextAlign::End)
                .into_widget(),
        );
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(paragraph.max_lines(&app), Some(2));
        assert_eq!(paragraph.overflow(&app), TextOverflow::Ellipsis);
        assert!(!paragraph.soft_wrap(&app));
        assert_eq!(paragraph.text_direction(&app), TextDirection::Rtl);
        assert_eq!(paragraph.text_align(&app), TextAlign::End);
    }

    #[test]
    fn a_default_text_style_supplies_what_the_text_leaves_unset() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let under_default = |text: Text| {
            DefaultTextStyle::new(TextStyle::new(), text)
                .max_lines(1)
                .overflow(TextOverflow::Fade)
                .text_align(TextAlign::Center)
                .soft_wrap(false)
                .into_widget()
        };
        let harness = mount(&mut app, under_default(Text::new("Hello")));
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(paragraph.max_lines(&app), Some(1));
        assert_eq!(paragraph.overflow(&app), TextOverflow::Fade);
        assert_eq!(paragraph.text_align(&app), TextAlign::Center);
        assert!(!paragraph.soft_wrap(&app));

        harness.set_child(
            &mut app,
            ltr(under_default(Text::new("Hello").max_lines(3))),
        );
        harness.pump(&mut app);
        assert_eq!(
            paragraph.max_lines(&app),
            Some(3),
            "the Text's own value wins"
        );
    }

    #[test]
    fn the_style_overflow_beats_the_default_text_style_overflow() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = mount(
            &mut app,
            DefaultTextStyle::new(
                TextStyle::new(),
                Text::new("Hello").style(TextStyle::new().overflow(TextOverflow::Ellipsis)),
            )
            .overflow(TextOverflow::Fade)
            .into_widget(),
        );
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(paragraph.overflow(&app), TextOverflow::Ellipsis);
    }

    #[test]
    fn a_default_text_height_behavior_reaches_the_paragraph_and_notifies_on_change() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let text: WidgetRef = Text::new("Hello").into_widget();
        let under_behavior = |leading_distribution: TextLeadingDistribution| {
            DefaultTextHeightBehavior::new(
                TextHeightBehavior {
                    leading_distribution,
                    ..TextHeightBehavior::default()
                },
                text.clone(),
            )
            .into_widget()
        };
        let harness = mount(&mut app, under_behavior(TextLeadingDistribution::Even));
        let paragraph = paragraph_under_root(&harness, &app);
        let behavior = paragraph.text_height_behavior(&app).expect("inherited");
        assert_eq!(behavior.leading_distribution, TextLeadingDistribution::Even);

        harness.set_child(
            &mut app,
            ltr(under_behavior(TextLeadingDistribution::Proportional)),
        );
        harness.pump(&mut app);
        let behavior = paragraph.text_height_behavior(&app).expect("inherited");
        assert_eq!(
            behavior.leading_distribution,
            TextLeadingDistribution::Proportional
        );
    }

    #[test]
    fn a_rich_text_forwards_its_configuration_in_place() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let rich = |text: &str| {
            RichText::new(TextSpan::new().text(text).into_span())
                .text_align(TextAlign::Center)
                .text_direction(TextDirection::Rtl)
                .max_lines(1)
                .into_widget()
        };
        let harness = mount(&mut app, rich("Hello"));
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(paragraph.text_align(&app), TextAlign::Center);
        assert_eq!(paragraph.text_direction(&app), TextDirection::Rtl);
        assert_eq!(paragraph.max_lines(&app), Some(1));

        harness.set_child(&mut app, ltr(rich("Goodbye")));
        harness.pump(&mut app);
        assert_eq!(paragraph_under_root(&harness, &app), paragraph);
        assert_eq!(plain_text_of(paragraph, &app), "Goodbye");
    }

    #[test]
    fn a_changed_key_replaces_the_paragraph_where_the_same_key_keeps_it() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let keyed = |key: &str| {
            Text::new("Hello")
                .key(ValueKey::new(key.to_owned()).into())
                .into_widget()
        };
        let harness = mount(&mut app, keyed("a"));
        let paragraph = paragraph_under_root(&harness, &app);

        harness.set_child(&mut app, ltr(keyed("a")));
        harness.pump(&mut app);
        assert_eq!(paragraph_under_root(&harness, &app), paragraph);

        harness.set_child(&mut app, ltr(keyed("b")));
        harness.pump(&mut app);
        assert_ne!(paragraph_under_root(&harness, &app), paragraph);
    }

    #[test]
    fn a_media_query_bolds_scales_and_spaces_the_text() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let data = MediaQueryData::new()
            .bold_text(true)
            .text_scaler(TextScaler::linear(2.0))
            .line_height_scale_factor_override(1.5)
            .letter_spacing_override(3.0)
            .word_spacing_override(4.0);
        let harness = mount(
            &mut app,
            MediaQuery::new(data, Text::new("Hello")).into_widget(),
        );
        let paragraph = paragraph_under_root(&harness, &app);
        let style = style_of(paragraph, &app);
        assert_eq!(style.font_weight, Some(FontWeight::BOLD));
        assert_eq!(style.height, Some(1.5));
        assert_eq!(style.letter_spacing, Some(3.0));
        assert_eq!(style.word_spacing, Some(4.0));
        assert_eq!(paragraph.text_scaler(&app), TextScaler::linear(2.0));
    }

    #[test]
    fn force_strut_height_applies_to_widget_spans() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let fonts = PaintingBinding::instance(&mut app).install_flutter_test_fonts(&mut app);
        let span = TextSpan::new()
            .children(vec![
                WidgetSpan::new(crate::widgets::basic::SizedBox::new()).into_span(),
            ])
            .into_span();
        let mut painter = TextPainter::new();
        painter.set_text(Some(span));
        painter.set_text_direction(Some(TextDirection::Ltr));
        painter.set_strut_style(Some(
            StrutStyle::new()
                .height(10.0)
                .font_size(10.0)
                .force_strut_height(true),
        ));
        painter.set_placeholder_dimensions(Some(vec![PlaceholderDimensions::new(
            Size::new(1000.0, 1000.0),
            waft_embedder::PlaceholderAlignment::Bottom,
        )]));
        painter.layout(app.get_mut(fonts), 0.0, f64::INFINITY);
        assert_eq!(painter.height(), 100.0);
    }

    #[test]
    fn text_rich_respects_the_media_query_spacing_overrides_on_its_strut() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let overridden = MediaQuery::new(
            MediaQueryData::new()
                .line_height_scale_factor_override(2.0)
                .letter_spacing_override(2.0)
                .word_spacing_override(2.0),
            Text::rich(TextSpan::new().text("Hello").into_span())
                .text_direction(TextDirection::Ltr)
                .strut_style(StrutStyle::new().height(0.9)),
        )
        .into_widget();
        let harness = mount(&mut app, overridden);
        let paragraph = paragraph_under_root(&harness, &app);
        let span_style = paragraph.text(&app).style().cloned();
        assert_eq!(
            span_style.as_ref().and_then(|style| style.height),
            Some(2.0)
        );
        assert_eq!(
            span_style.as_ref().and_then(|style| style.letter_spacing),
            Some(2.0)
        );
        assert_eq!(
            span_style.as_ref().and_then(|style| style.word_spacing),
            Some(2.0)
        );
        assert_eq!(
            paragraph
                .strut_style(&app)
                .and_then(|strut_style| strut_style.height),
            Some(2.0)
        );

        harness.set_child(
            &mut app,
            ltr(Text::rich(TextSpan::new().text("Hello").into_span())
                .text_direction(TextDirection::Ltr)
                .strut_style(StrutStyle::new().height(0.9))
                .into_widget()),
        );
        harness.pump(&mut app);
        let paragraph = paragraph_under_root(&harness, &app);
        let span_style = paragraph.text(&app).style().cloned();
        assert_eq!(span_style.as_ref().and_then(|style| style.height), None);
        assert_eq!(
            span_style.as_ref().and_then(|style| style.letter_spacing),
            None
        );
        assert_eq!(
            span_style.as_ref().and_then(|style| style.word_spacing),
            None
        );
        assert_eq!(
            paragraph
                .strut_style(&app)
                .and_then(|strut_style| strut_style.height),
            Some(0.9)
        );
    }

    #[test]
    fn rich_text_ignores_the_media_query_spacing_overrides() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let overridden = MediaQuery::new(
            MediaQueryData::new()
                .line_height_scale_factor_override(2.0)
                .letter_spacing_override(2.0)
                .word_spacing_override(2.0),
            RichText::new(TextSpan::new().text("Hello").into_span())
                .text_direction(TextDirection::Ltr)
                .strut_style(StrutStyle::new().height(0.9)),
        )
        .into_widget();
        let harness = mount(&mut app, overridden);
        let paragraph = paragraph_under_root(&harness, &app);
        let span_style = paragraph.text(&app).style().cloned();
        assert_eq!(span_style.as_ref().and_then(|style| style.height), None);
        assert_eq!(
            span_style.as_ref().and_then(|style| style.letter_spacing),
            None
        );
        assert_eq!(
            span_style.as_ref().and_then(|style| style.word_spacing),
            None
        );
        assert_eq!(
            paragraph
                .strut_style(&app)
                .and_then(|strut_style| strut_style.height),
            Some(0.9)
        );
    }
}