bevy_text 0.19.0-rc.2

Provides text functionality for Bevy Engine
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
use crate::{Font, TextBrush, TextLayoutInfo, TextSection};
use bevy_asset::Handle;
use bevy_color::Color;
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{prelude::*, reflect::ReflectComponent};
use bevy_math::Vec2;
use bevy_reflect::prelude::*;
use bevy_utils::{default, once};
use core::fmt::{Debug, Formatter};
use core::str::from_utf8;
use parley::setting::Tag;
use parley::{FontFeature, FontVariation, Layout};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use smol_str::SmolStr;
use tracing::warn;

/// A sub-entity of a [`ComputedTextBlock`].
///
/// Returned by [`ComputedTextBlock::entities`].
#[derive(Debug, Copy, Clone, Reflect)]
#[reflect(Debug, Clone)]
pub struct TextEntity {
    /// The entity.
    pub entity: Entity,
    /// Records the hierarchy depth of the entity within a `TextLayout`.
    pub depth: usize,
    /// Antialiasing method to use when rendering the text.
    pub font_smoothing: FontSmoothing,
}

/// Computed information for a text block.
///
/// See [`TextLayout`].
///
/// Automatically updated by 2d and UI text systems.
#[derive(Component, Clone, Reflect)]
#[reflect(Component, Debug, Default, Clone)]
pub struct ComputedTextBlock {
    /// Text layout, used to generate [`TextLayoutInfo`].
    #[reflect(ignore, clone)]
    pub(crate) layout: Layout<TextBrush>,
    /// Entities for all text spans in the block, including the root-level text.
    ///
    /// The [`TextEntity::depth`] field can be used to reconstruct the hierarchy.
    pub(crate) entities: SmallVec<[TextEntity; 1]>,
    /// Flag set when any change has been made to this block that should cause it to be rerendered.
    ///
    /// Includes:
    /// - [`TextLayout`] changes.
    /// - [`TextFont`] or `Text2d`/`Text`/`TextSpan` changes anywhere in the block's entity hierarchy.
    // TODO: This encompasses both structural changes like font size or justification and non-structural
    // changes like text color and font smoothing. This field currently causes UI to 'remeasure' text, even if
    // the actual changes are non-structural and can be handled by only rerendering and not remeasuring. A full
    // solution would probably require splitting TextLayout and TextFont into structural/non-structural
    // components for more granular change detection. A cost/benefit analysis is needed.
    pub(crate) needs_rerender: bool,
    // Flag set by `TextPipeline::update_buffer` if any text section in the block has a viewport font size value.
    //
    // Used by dependents to determine if they should update a text block on changes to
    // the viewport size.
    pub(crate) uses_viewport_sizes: bool,
    // Flag set by `TextPipeline::update_buffer` if any text section in the block has a rem font size value.
    //
    // Used by dependents to determine if they should update a text block on changes to
    // the rem size.
    pub(crate) uses_rem_sizes: bool,
}

impl Debug for ComputedTextBlock {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ComputedTextBlock")
            .field("layout", &"Layout(..)")
            .field("entities", &self.entities)
            .field("needs_rerender", &self.needs_rerender)
            .field("uses_viewport_sizes", &self.uses_viewport_sizes)
            .field("uses_rem_sizes", &self.uses_rem_sizes)
            .finish()
    }
}

impl ComputedTextBlock {
    /// Accesses entities in this block.
    ///
    /// Can be used to look up [`TextFont`] components for glyphs in [`TextLayoutInfo`] using the `section_index`
    /// stored there.
    pub fn entities(&self) -> &[TextEntity] {
        &self.entities
    }

    /// Indicates if the text needs to be refreshed in [`TextLayoutInfo`].
    ///
    /// Updated automatically by [`detect_text_needs_rerender`] and cleared
    /// by [`TextPipeline`](crate::TextPipeline) methods.
    pub fn needs_rerender(
        &self,
        is_viewport_size_changed: bool,
        is_rem_size_changed: bool,
    ) -> bool {
        self.needs_rerender
            || (is_viewport_size_changed && self.uses_viewport_sizes)
            || (is_rem_size_changed && self.uses_rem_sizes)
    }

    /// Accesses the shaped layout buffer.
    pub fn buffer(&self) -> &Layout<TextBrush> {
        &self.layout
    }
}

impl Default for ComputedTextBlock {
    fn default() -> Self {
        Self {
            layout: Layout::new(),
            entities: SmallVec::default(),
            needs_rerender: true,
            uses_rem_sizes: false,
            uses_viewport_sizes: false,
        }
    }
}

/// Component with text format settings for a block of text.
///
/// A block of text is composed of text spans, which each have a separate string value and [`TextFont`]. Text
/// spans associated with a text block are collected into [`ComputedTextBlock`] for layout, and then inserted
/// to [`TextLayoutInfo`] for rendering.
///
/// See `Text2d` in `bevy_sprite` for the core component of 2d text, and `Text` in `bevy_ui` for UI text.
#[derive(Component, Debug, Copy, Clone, Default, Reflect)]
#[reflect(Component, Default, Debug, Clone)]
#[require(ComputedTextBlock, TextLayoutInfo)]
pub struct TextLayout {
    /// The text's internal alignment.
    /// Should not affect its position within a container.
    pub justify: Justify,
    /// How the text should linebreak when running out of the bounds determined by `max_size`.
    pub linebreak: LineBreak,
}

impl TextLayout {
    /// Makes a new [`TextLayout`].
    pub const fn new(justify: Justify, linebreak: LineBreak) -> Self {
        Self { justify, linebreak }
    }

    /// Makes a new [`TextLayout`] with the specified [`Justify`].
    pub fn justify(justify: Justify) -> Self {
        Self::default().with_justify(justify)
    }

    /// Makes a new [`TextLayout`] with the specified [`LineBreak`].
    pub fn linebreak(linebreak: LineBreak) -> Self {
        Self::default().with_linebreak(linebreak)
    }

    /// Makes a new [`TextLayout`] with soft wrapping disabled.
    /// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, will still occur.
    pub fn no_wrap() -> Self {
        Self::default().with_no_wrap()
    }

    /// Returns this [`TextLayout`] with the specified [`Justify`].
    pub const fn with_justify(mut self, justify: Justify) -> Self {
        self.justify = justify;
        self
    }

    /// Returns this [`TextLayout`] with the specified [`LineBreak`].
    pub const fn with_linebreak(mut self, linebreak: LineBreak) -> Self {
        self.linebreak = linebreak;
        self
    }

    /// Returns this [`TextLayout`] with soft wrapping disabled.
    /// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, will still occur.
    pub const fn with_no_wrap(mut self) -> Self {
        self.linebreak = LineBreak::NoWrap;
        self
    }
}

/// A span of text in a tree of spans.
///
/// A `TextSpan` is only valid when it exists as a child of a parent that has either `Text` or
/// `Text2d`. The parent's `Text` / `Text2d` component contains the base text content. Any children
/// with `TextSpan` extend this text by appending their content to the parent's text in sequence to
/// form a [`ComputedTextBlock`]. The parent's [`TextLayout`] determines the layout of the block
/// but each node has its own [`TextFont`] and [`TextColor`].
#[derive(Component, Debug, Default, Clone, Deref, DerefMut, Reflect)]
#[reflect(Component, Default, Debug, Clone)]
#[require(TextFont, TextColor, LineHeight, LetterSpacing)]
pub struct TextSpan(pub String);

impl TextSpan {
    /// Makes a new text span component.
    pub fn new(text: impl Into<String>) -> Self {
        Self(text.into())
    }
}

impl TextSection for TextSpan {
    fn get_text(&self) -> &str {
        self.as_str()
    }
    fn get_text_mut(&mut self) -> &mut String {
        &mut *self
    }
}

impl From<&str> for TextSpan {
    fn from(value: &str) -> Self {
        Self(String::from(value))
    }
}

impl From<String> for TextSpan {
    fn from(value: String) -> Self {
        Self(value)
    }
}

/// Describes the horizontal alignment of multiple lines of text relative to each other.
///
/// This only affects the internal positioning of the lines of text within a text entity and
/// does not affect the text entity's position.
///
/// _Has no affect on a single line text entity_, unless used together with a
/// [`TextBounds`](super::bounds::TextBounds) component with an explicit `width` value.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[reflect(Serialize, Deserialize, Clone, PartialEq, Hash)]
#[doc(alias = "JustifyText")]
pub enum Justify {
    /// Leftmost character is immediately to the right of the render position.
    /// Bounds start from the render position and advance rightwards.
    #[default]
    Left,
    /// Leftmost & rightmost characters are equidistant to the render position.
    /// Bounds start from the render position and advance equally left & right.
    Center,
    /// Rightmost character is immediately to the left of the render position.
    /// Bounds start from the render position and advance leftwards.
    Right,
    /// Words are spaced so that leftmost & rightmost characters
    /// align with their margins.
    /// Bounds start from the render position and advance equally left & right.
    Justified,
    /// `TextAlignment::Left` for LTR text and `TextAlignment::Right` for RTL text.
    Start,
    /// `TextAlignment::Left` for RTL text and `TextAlignment::Right` for LTR text.
    End,
}

impl From<Justify> for parley::Alignment {
    fn from(justify: Justify) -> Self {
        match justify {
            Justify::Start => parley::Alignment::Start,
            Justify::End => parley::Alignment::End,
            Justify::Left => parley::Alignment::Left,
            Justify::Center => parley::Alignment::Center,
            Justify::Right => parley::Alignment::Right,
            Justify::Justified => parley::Alignment::Justify,
        }
    }
}

#[derive(Clone, Debug, Reflect, PartialEq, FromTemplate)]
/// Determines how the font face for a text sections is selected.
///
/// A [`FontSource`] can be a handle to a font asset, a font family name,
/// or a generic font category that is resolved using Parley's font database.
///
/// Font family fallback (selection of a font when the requested font is not found)
/// is automatically handled by [`parley::fontique`].
/// Be sure to enable the `parley/system` feature for automatic discovery of system fonts.
///
/// Generally speaking, these fallbacks are OS-specific,
/// and do not require manual configuration.
///
/// You can check which font family is used for a given [`FontSource`]
/// by calling [`FontCx::get_family`](crate::FontCx::get_family).
pub enum FontSource {
    /// Use a specific font face referenced by a [`Font`] asset handle.
    ///
    /// If the default font handle is used, then
    /// * if `default_font` feature is enabled (enabled by default in `bevy` crate),
    ///   `FiraMono-subset.ttf` compiled into the library is used.
    /// * otherwise no text will be rendered, unless a custom font is loaded into the default font
    ///   handle.
    #[default]
    Handle(Handle<Font>),
    /// Resolve the font by family name using the font database.
    Family(SmolStr),
    /// Fonts with serifs — small decorative strokes at the ends of letterforms.
    ///
    /// Serif fonts are typically used for long passages of text and represent
    /// a more traditional or formal typographic style.
    Serif,
    /// Fonts without serifs.
    ///
    /// Sans-serif fonts generally have low stroke contrast and plain stroke
    /// endings, making them common for UI text and on-screen reading.
    SansSerif,
    /// Fonts that use a cursive or handwritten style.
    ///
    /// Glyphs often resemble connected or flowing pen or brush strokes rather
    /// than printed letterforms.
    Cursive,
    /// Decorative or expressive fonts.
    ///
    /// Fantasy fonts are primarily intended for display purposes and may
    /// prioritize visual style over readability.
    Fantasy,
    /// Fonts in which all glyphs have the same fixed advance width.
    ///
    /// Monospace fonts are commonly used for code, tabular data, and text
    /// where vertical alignment is important.
    Monospace,
    /// The default user interface system font.
    SystemUi,
    /// Alternative serif font for user interfaces.
    UiSerif,
    /// Alternative sans-erif font for user interfaces.
    UiSansSerif,
    /// Alternative monospace font for user interfaces.
    UiMonospace,
    /// Fonts that have rounded features.
    UiRounded,
    /// Fonts that are specifically designed to render emoji.
    Emoji,
    /// This is for the particular stylistic concerns of representing
    /// mathematics: superscript and subscript, brackets that cross several
    /// lines, nesting expressions, and double struck glyphs with distinct
    /// meanings.
    Math,
    /// A particular style of Chinese characters that are between serif-style
    /// Song and cursive-style Kai forms. This style is often used for
    /// government documents.
    FangSong,
}

impl Default for FontSource {
    fn default() -> Self {
        Self::Handle(Handle::default())
    }
}

impl From<Handle<Font>> for FontSource {
    fn from(handle: Handle<Font>) -> Self {
        Self::Handle(handle)
    }
}

impl From<&Handle<Font>> for FontSource {
    fn from(handle: &Handle<Font>) -> Self {
        Self::Handle(handle.clone())
    }
}

impl From<SmolStr> for FontSource {
    fn from(family: SmolStr) -> Self {
        FontSource::Family(family)
    }
}

impl From<&str> for FontSource {
    fn from(family: &str) -> Self {
        FontSource::Family(family.into())
    }
}

/// `TextFont` determines the style of a text span within a [`ComputedTextBlock`], specifically
/// the font face, the font size, the line height, and the antialiasing method.
#[derive(Component, Clone, Debug, Reflect, PartialEq, FromTemplate)]
#[reflect(Component, Default, Debug, Clone)]
pub struct TextFont {
    /// Specifies the font face used for this text section.
    ///
    /// A `FontSource` can be a handle to a font asset, a font family name,
    /// or a generic font category that is resolved using Parley's
    /// [`FontContext`](`parley::FontContext`) which is accessible through the
    /// [`FontCx`](`crate::FontCx`) resource.
    pub font: FontSource,
    /// The vertical height of rasterized glyphs in the font atlas in pixels.
    ///
    /// This is multiplied by the window scale factor and `UiScale`, but not the text entity's
    /// transform or camera projection. Then, the scaled font size is rounded to the nearest pixel
    /// to produce the final font size used during glyph layout.
    ///
    /// A new font atlas is generated for every combination of font handle and scaled font size
    /// which can have a strong performance impact.
    pub font_size: FontSize,
    /// How thick or bold the strokes of a font appear.
    ///
    /// Font weights can be any value between 1 and 1000, inclusive.
    ///
    /// Only supports variable weight fonts.
    pub weight: FontWeight,
    /// How condensed or expanded the glyphs appear horizontally.
    pub width: FontWidth,
    /// The slant style of a font face: normal, italic, or oblique.
    pub style: FontStyle,
    /// The antialiasing method to use when rendering text.
    pub font_smoothing: FontSmoothing,
    /// OpenType features for .otf fonts that support them.
    pub font_features: FontFeatures,
    /// OpenType variations for variable fonts that support them.
    pub font_variations: FontVariations,
}

impl TextFont {
    /// Returns a new [`TextFont`] with the specified font size.
    pub fn from_font_size(font_size: impl Into<FontSize>) -> Self {
        Self::default().with_font_size(font_size)
    }

    /// Returns a new [`TextFont`] with the specified font weight
    pub fn from_font_weight(weight: impl Into<FontWeight>) -> Self {
        Self::default().with_font_weight(weight)
    }

    /// Returns this [`TextFont`] with the specified font face handle.
    pub fn with_font(mut self, font: Handle<Font>) -> Self {
        self.font = FontSource::Handle(font);
        self
    }

    /// Returns this [`TextFont`] with the specified font family.
    pub fn with_family(mut self, family: impl Into<SmolStr>) -> Self {
        self.font = FontSource::Family(family.into());
        self
    }

    /// Returns this [`TextFont`] with the specified font size.
    pub fn with_font_size(mut self, font_size: impl Into<FontSize>) -> Self {
        self.font_size = font_size.into();
        self
    }

    /// Returns this [`TextFont`] with the specified [`FontSmoothing`].
    pub const fn with_font_smoothing(mut self, font_smoothing: FontSmoothing) -> Self {
        self.font_smoothing = font_smoothing;
        self
    }

    /// Returns this [`TextFont`] with the specified [`FontWeight`].
    pub fn with_font_weight(mut self, weight: impl Into<FontWeight>) -> Self {
        self.weight = weight.into();
        self
    }
}

impl<T: Into<FontSource>> From<T> for TextFont {
    fn from(source: T) -> Self {
        Self {
            font: source.into(),
            ..default()
        }
    }
}

impl Default for TextFont {
    fn default() -> Self {
        Self {
            font: Default::default(),
            font_size: FontSize::from(20.),
            style: FontStyle::Normal,
            weight: FontWeight::NORMAL,
            width: FontWidth::NORMAL,
            font_features: FontFeatures::default(),
            font_variations: FontVariations::default(),
            font_smoothing: Default::default(),
        }
    }
}

/// The vertical height of rasterized glyphs in the font atlas in pixels.
///
/// This is multiplied by the scale factor, but not the text entity
/// transform or camera projection.
///
/// The viewport variants are not supported by `Text2d`.
///
/// A new font atlas is generated for every combination of font handle and scaled font size
/// which can have a strong performance impact.
#[derive(Component, Copy, Clone, Debug, Reflect)]
pub enum FontSize {
    /// Font Size in logical pixels.
    Px(f32),
    /// Font size as a percentage of the viewport width.
    Vw(f32),
    /// Font size as a percentage of the viewport height.
    Vh(f32),
    /// Font size as a percentage of the smaller of the viewport width and height.
    VMin(f32),
    /// Font size as a percentage of the larger of the viewport width and height.
    VMax(f32),
    /// Font Size relative to the value of the `RemSize` resource.
    Rem(f32),
}

impl FontSize {
    /// Evaluate the font size to a value in logical pixels
    pub fn eval(
        self,
        // Viewport size in logical pixels
        logical_viewport_size: Vec2,
        // Base Rem size in logical pixels
        rem_size: f32,
    ) -> f32 {
        match self {
            FontSize::Px(s) => s,
            FontSize::Vw(s) => logical_viewport_size.x * s / 100.,
            FontSize::Vh(s) => logical_viewport_size.y * s / 100.,
            FontSize::VMin(s) => logical_viewport_size.min_element() * s / 100.,
            FontSize::VMax(s) => logical_viewport_size.max_element() * s / 100.,
            FontSize::Rem(s) => rem_size * s,
        }
    }
}

impl PartialEq for FontSize {
    fn eq(&self, other: &Self) -> bool {
        match (*self, *other) {
            (Self::Px(l), Self::Px(r))
            | (Self::Vw(l), Self::Vw(r))
            | (Self::Vh(l), Self::Vh(r))
            | (Self::VMin(l), Self::VMin(r))
            | (Self::VMax(l), Self::VMax(r))
            | (Self::Rem(l), Self::Rem(r)) => l == r,
            _ => false,
        }
    }
}

impl core::ops::Mul<f32> for FontSize {
    type Output = FontSize;

    fn mul(self, rhs: f32) -> Self::Output {
        match self {
            FontSize::Px(v) => FontSize::Px(v * rhs),
            FontSize::Vw(v) => FontSize::Vw(v * rhs),
            FontSize::Vh(v) => FontSize::Vh(v * rhs),
            FontSize::VMin(v) => FontSize::VMin(v * rhs),
            FontSize::VMax(v) => FontSize::VMax(v * rhs),
            FontSize::Rem(v) => FontSize::Rem(v * rhs),
        }
    }
}

impl core::ops::Mul<FontSize> for f32 {
    type Output = FontSize;

    fn mul(self, rhs: FontSize) -> Self::Output {
        rhs * self
    }
}

impl Default for FontSize {
    fn default() -> Self {
        Self::Px(20.)
    }
}

impl From<f32> for FontSize {
    fn from(value: f32) -> Self {
        Self::Px(value)
    }
}

/// Base value used to resolve `Rem` units for font sizes.
#[derive(Resource, Copy, Clone, Debug, PartialEq, Deref, DerefMut)]
pub struct RemSize(pub f32);

impl Default for RemSize {
    fn default() -> Self {
        Self(20.)
    }
}

/// How thick or bold the strokes of a font appear.
///
/// Valid font weights range from 1 to 1000, inclusive.
/// Weights above 1000 are clamped to 1000.
/// A weight of 0 is treated as [`FontWeight::DEFAULT`].
///
/// Legacy names from when most fonts weren't variable fonts
/// are included as const values, but are misleading if
/// used in documentation and examples, as valid weights
/// for variable fonts are all of the numbers from 1-1000, and
/// not all fonts which are not variable fonts have those weights
/// supplied. If you use a custom font that supplies only specific
/// weights, that will be documented where you purchased the font.
///
/// `<https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/font-weight>`
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
pub struct FontWeight(pub u16);

impl FontWeight {
    /// Weight 100.
    pub const THIN: FontWeight = FontWeight(100);

    /// Weight 200.
    pub const EXTRA_LIGHT: FontWeight = FontWeight(200);

    /// Weight 300.
    pub const LIGHT: FontWeight = FontWeight(300);

    /// Weight 400.
    pub const NORMAL: FontWeight = FontWeight(400);

    /// Weight 500.
    pub const MEDIUM: FontWeight = FontWeight(500);

    /// Weight 600.
    pub const SEMIBOLD: FontWeight = FontWeight(600);

    /// Weight 700.
    pub const BOLD: FontWeight = FontWeight(700);

    /// Weight 800
    pub const EXTRA_BOLD: FontWeight = FontWeight(800);

    /// Weight 900.
    pub const BLACK: FontWeight = FontWeight(900);

    /// Weight 950.
    pub const EXTRA_BLACK: FontWeight = FontWeight(950);

    /// The default font weight.
    pub const DEFAULT: FontWeight = Self::NORMAL;

    /// Clamp the weight value to between 1 and 1000.
    /// Values of 0 are mapped to `Weight::DEFAULT`.
    pub const fn clamp(mut self) -> Self {
        if self.0 == 0 {
            self = Self::DEFAULT;
        } else if 1000 < self.0 {
            self.0 = 1000;
        }
        Self(self.0)
    }
}

impl Default for FontWeight {
    fn default() -> Self {
        Self::DEFAULT
    }
}

impl From<FontWeight> for parley::style::FontWeight {
    fn from(value: FontWeight) -> Self {
        parley::style::FontWeight::new(value.clamp().0 as f32)
    }
}

/// `<https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass>`
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug, Hash, Reflect)]
pub struct FontWidth(u16);

impl FontWidth {
    /// 50% of normal width.
    pub const ULTRA_CONDENSED: Self = Self(1);

    /// 62.5% of normal width.
    pub const EXTRA_CONDENSED: Self = Self(2);

    /// 75% of normal width.
    pub const CONDENSED: Self = Self(3);

    /// 87.5% of normal width.
    pub const SEMI_CONDENSED: Self = Self(4);

    /// 100% of normal width. This is the default.
    pub const NORMAL: Self = Self(5);

    /// 112.5% of normal width.
    pub const SEMI_EXPANDED: Self = Self(6);

    /// 125% of normal width.
    pub const EXPANDED: Self = Self(7);

    /// 150% of normal width.
    pub const EXTRA_EXPANDED: Self = Self(8);

    /// 200% of normal width.
    pub const ULTRA_EXPANDED: Self = Self(9);
}

impl Default for FontWidth {
    fn default() -> Self {
        Self::NORMAL
    }
}

impl From<FontWidth> for parley::FontWidth {
    fn from(value: FontWidth) -> Self {
        match value.0 {
            1 => parley::FontWidth::ULTRA_CONDENSED,
            2 => parley::FontWidth::EXTRA_CONDENSED,
            3 => parley::FontWidth::CONDENSED,
            4 => parley::FontWidth::SEMI_CONDENSED,
            6 => parley::FontWidth::SEMI_EXPANDED,
            7 => parley::FontWidth::EXPANDED,
            8 => parley::FontWidth::EXTRA_EXPANDED,
            9 => parley::FontWidth::ULTRA_EXPANDED,
            _ => parley::FontWidth::NORMAL,
        }
    }
}

/// The slant style of a font face: normal, italic, or oblique.
#[derive(Clone, Copy, Default, PartialEq, Debug, Reflect)]
pub enum FontStyle {
    /// A face that is neither italic nor obliqued.
    #[default]
    Normal,
    /// A form that is generally cursive in nature.
    Italic,
    /// A typically sloped version of the regular face.
    ///
    /// The contained f32 is the slant angle of the text, in degrees.
    Oblique(Option<f32>),
}

impl From<FontStyle> for parley::FontStyle {
    fn from(value: FontStyle) -> Self {
        match value {
            FontStyle::Normal => parley::FontStyle::Normal,
            FontStyle::Italic => parley::FontStyle::Italic,
            FontStyle::Oblique(value) => parley::FontStyle::Oblique(value),
        }
    }
}

/// An OpenType font feature tag.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
pub struct FontFeatureTag([u8; 4]);

impl FontFeatureTag {
    /// Replaces character combinations like fi, fl with ligatures.
    pub const STANDARD_LIGATURES: FontFeatureTag = FontFeatureTag::new(b"liga");

    /// Enables ligatures based on character context.
    pub const CONTEXTUAL_LIGATURES: FontFeatureTag = FontFeatureTag::new(b"clig");

    /// Enables optional ligatures for stylistic use (e.g., ct, st).
    pub const DISCRETIONARY_LIGATURES: FontFeatureTag = FontFeatureTag::new(b"dlig");

    /// Adjust glyph shapes based on surrounding letters.
    pub const CONTEXTUAL_ALTERNATES: FontFeatureTag = FontFeatureTag::new(b"calt");

    /// Use alternate glyph designs.
    pub const STYLISTIC_ALTERNATES: FontFeatureTag = FontFeatureTag::new(b"salt");

    /// Replaces lowercase letters with small caps.
    pub const SMALL_CAPS: FontFeatureTag = FontFeatureTag::new(b"smcp");

    /// Replaces uppercase letters with small caps.
    pub const CAPS_TO_SMALL_CAPS: FontFeatureTag = FontFeatureTag::new(b"c2sc");

    /// Replaces characters with swash versions (often decorative).
    pub const SWASH: FontFeatureTag = FontFeatureTag::new(b"swsh");

    /// Enables alternate glyphs for large sizes or titles.
    pub const TITLING_ALTERNATES: FontFeatureTag = FontFeatureTag::new(b"titl");

    /// Converts numbers like 1/2 into true fractions (½).
    pub const FRACTIONS: FontFeatureTag = FontFeatureTag::new(b"frac");

    /// Formats characters like 1st, 2nd properly.
    pub const ORDINALS: FontFeatureTag = FontFeatureTag::new(b"ordn");

    /// Uses a slashed version of zero (0) to differentiate from O.
    pub const SLASHED_ZERO: FontFeatureTag = FontFeatureTag::new(b"zero");

    /// Replaces figures with superscript figures, e.g. for indicating footnotes.
    pub const SUPERSCRIPT: FontFeatureTag = FontFeatureTag::new(b"sups");

    /// Replaces figures with subscript figures.
    pub const SUBSCRIPT: FontFeatureTag = FontFeatureTag::new(b"subs");

    /// Changes numbers to "oldstyle" form, which fit better in the flow of sentences or other text.
    pub const OLDSTYLE_FIGURES: FontFeatureTag = FontFeatureTag::new(b"onum");

    /// Changes numbers to "lining" form, which are better suited for standalone numbers. When
    /// enabled, the bottom of all numbers will be aligned with each other.
    pub const LINING_FIGURES: FontFeatureTag = FontFeatureTag::new(b"lnum");

    /// Changes numbers to be of proportional width. When enabled, numbers may have varying widths.
    pub const PROPORTIONAL_FIGURES: FontFeatureTag = FontFeatureTag::new(b"pnum");

    /// Changes numbers to be of uniform (tabular) width. When enabled, all numbers will have the
    /// same width.
    pub const TABULAR_FIGURES: FontFeatureTag = FontFeatureTag::new(b"tnum");

    /// Varies the stroke thickness. Valid values are in the range of 1 to 1000, inclusive.
    pub const WEIGHT: FontFeatureTag = FontFeatureTag::new(b"wght");

    /// Varies the width of text from narrower to wider. Must be a value greater than 0. A value of
    /// 100 is typically considered standard width.
    pub const WIDTH: FontFeatureTag = FontFeatureTag::new(b"wdth");

    /// Varies between upright and slanted text. Must be a value greater than -90 and less than +90.
    /// A value of 0 is upright.
    pub const SLANT: FontFeatureTag = FontFeatureTag::new(b"slnt");

    /// Create a new [`FontFeatureTag`] from raw bytes.
    pub const fn new(src: &[u8; 4]) -> Self {
        Self(*src)
    }
}

impl Debug for FontFeatureTag {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        // OpenType tags are always ASCII, so this match will succeed for valid tags. This gives us
        // human-readable debug output, e.g. FontFeatureTag("liga").
        match from_utf8(&self.0) {
            Ok(s) => write!(f, "FontFeatureTag(\"{}\")", s),
            Err(_) => write!(f, "FontFeatureTag({:?})", self.0),
        }
    }
}

/// OpenType features for .otf fonts that support them.
///
/// Examples features include ligatures, small-caps, and fractional number display. For the complete
/// list of OpenType features, see the spec at
/// `<https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>`.
///
/// # Usage:
/// ```
/// use bevy_text::{FontFeatureTag, FontFeatures};
///
/// // Create using the builder
/// let font_features = FontFeatures::builder()
///   .enable(FontFeatureTag::STANDARD_LIGATURES)
///   .set(FontFeatureTag::WEIGHT, 300)
///   .build();
///
/// // Create from a list
/// let more_font_features: FontFeatures = [
///   FontFeatureTag::STANDARD_LIGATURES,
///   FontFeatureTag::OLDSTYLE_FIGURES,
///   FontFeatureTag::TABULAR_FIGURES
/// ].into();
/// ```
#[derive(Clone, Debug, Default, Reflect, PartialEq)]
pub struct FontFeatures {
    features: Vec<(FontFeatureTag, u32)>,
}

impl FontFeatures {
    /// Create a new [`FontFeaturesBuilder`].
    pub fn builder() -> FontFeaturesBuilder {
        FontFeaturesBuilder::default()
    }
}

/// A builder for [`FontFeatures`].
#[derive(Clone, Default)]
pub struct FontFeaturesBuilder {
    features: Vec<(FontFeatureTag, u32)>,
}

impl FontFeaturesBuilder {
    /// Enable an OpenType feature.
    ///
    /// Most OpenType features are on/off switches, so this is a convenience method that sets the
    /// feature's value to "1" (enabled). For non-boolean features, see [`FontFeaturesBuilder::set`].
    pub fn enable(self, feature_tag: FontFeatureTag) -> Self {
        self.set(feature_tag, 1)
    }

    /// Set an OpenType feature to a specific value.
    ///
    /// For most features, the [`FontFeaturesBuilder::enable`] method should be used instead. A few
    /// features, such as "wght", take numeric values, so this method may be used for these cases.
    pub fn set(mut self, feature_tag: FontFeatureTag, value: u32) -> Self {
        self.features.push((feature_tag, value));
        self
    }

    /// Build a [`FontFeatures`] from the values set within this builder.
    pub fn build(self) -> FontFeatures {
        FontFeatures {
            features: self.features,
        }
    }
}

/// Allow [`FontFeatures`] to be built from a list. This is suitable for the standard case when each
/// listed feature is a boolean type. If any features require a numeric value (like "wght"), use
/// [`FontFeaturesBuilder`] instead.
impl<T> From<T> for FontFeatures
where
    T: IntoIterator<Item = FontFeatureTag>,
{
    fn from(value: T) -> Self {
        FontFeatures {
            features: value.into_iter().map(|x| (x, 1)).collect(),
        }
    }
}

impl From<&FontFeatures> for parley::style::FontFeatures<'static> {
    fn from(font_features: &FontFeatures) -> Self {
        parley::style::FontFeatures::List(
            font_features
                .features
                .iter()
                .map(|(tag, value)| FontFeature {
                    tag: Tag::new(&tag.0),
                    value: *value as u16,
                })
                .collect(),
        )
    }
}

/// An OpenType font variation tag.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
pub struct FontVariationTag([u8; 4]);

impl FontVariationTag {
    /// Varies the stroke thickness. The range is typically 1 to 1000.
    pub const WEIGHT: FontVariationTag = FontVariationTag::new(b"wght");

    /// Varies the width of glyphs from narrower to wider. The range is typically 50 to 200 with
    /// 100 being standard width.
    pub const WIDTH: FontVariationTag = FontVariationTag::new(b"wdth");

    /// Varies between upright and slanted glyphs. The range is typically between -90 and +90 degrees,
    /// where 0 is upright.
    pub const SLANT: FontVariationTag = FontVariationTag::new(b"slnt");

    /// Varies the design of glyphs for different optical sizes (physical font size).
    /// The range is typically 6 to 72.
    pub const OPTICAL_SIZE: FontVariationTag = FontVariationTag::new(b"opsz");

    /// Create a new [`FontVariationTag`] from raw bytes.
    pub const fn new(src: &[u8; 4]) -> Self {
        Self(*src)
    }
}

impl Debug for FontVariationTag {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match from_utf8(&self.0) {
            Ok(s) => write!(f, "FontVariationTag(\"{}\")", s),
            Err(_) => write!(f, "FontVariationTag({:?})", self.0),
        }
    }
}

/// OpenType font variations for variable fonts that support them.
///
/// Variable fonts expose named axes (e.g. `wght`, `FILL`) that accept continuous `f32` values.
/// This is distinct from [`FontFeatures`], which mainly controls on/off OpenType layout features.
///
/// # Usage
/// ```
/// use bevy_text::{FontVariationTag, FontVariations};
///
/// let variations = FontVariations::builder()
///     .set(FontVariationTag::WEIGHT, 400.0)
///     .build();
/// ```
#[derive(Clone, Debug, Default, Reflect, PartialEq)]
pub struct FontVariations {
    variations: Vec<(FontVariationTag, f32)>,
}

impl FontVariations {
    /// Create a new [`FontVariationsBuilder`].
    pub fn builder() -> FontVariationsBuilder {
        FontVariationsBuilder::default()
    }
}

/// A builder for [`FontVariations`].
#[derive(Clone, Default)]
pub struct FontVariationsBuilder {
    variations: Vec<(FontVariationTag, f32)>,
}

impl FontVariationsBuilder {
    /// Set a font variation to a specific value.
    pub fn set(mut self, tag: FontVariationTag, value: f32) -> Self {
        self.variations.push((tag, value));
        self
    }

    /// Build a [`FontVariations`] from the values set within this builder.
    pub fn build(self) -> FontVariations {
        FontVariations {
            variations: self.variations,
        }
    }
}

impl From<&FontVariations> for parley::style::FontVariations<'static> {
    fn from(font_variations: &FontVariations) -> Self {
        parley::style::FontVariations::List(
            font_variations
                .variations
                .iter()
                .map(|(tag, value)| FontVariation {
                    tag: Tag::new(&tag.0),
                    value: *value,
                })
                .collect(),
        )
    }
}

/// Specifies the height of each line of text for `Text` and `Text2d`
///
/// Default is 1.2x the font size
#[derive(Component, Debug, Clone, Copy, PartialEq, Reflect)]
#[reflect(Component, Debug, Clone, PartialEq)]
pub enum LineHeight {
    /// Set line height to a specific number of pixels
    Px(f32),
    /// Set line height to a multiple of the font size
    RelativeToFont(f32),
}

impl LineHeight {
    /// eval a line height
    pub fn eval(self) -> parley::LineHeight {
        match self {
            LineHeight::Px(px) => parley::LineHeight::Absolute(px),
            LineHeight::RelativeToFont(scale) => parley::LineHeight::FontSizeRelative(scale),
        }
    }
}

impl Default for LineHeight {
    fn default() -> Self {
        LineHeight::RelativeToFont(1.2)
    }
}

/// Specifies the space between each letter of text for `Text` and `Text2d`
///
/// Default is 0
#[derive(Component, Debug, Clone, Copy, PartialEq, Reflect)]
#[reflect(Component, Default, Debug, Clone, PartialEq)]
pub enum LetterSpacing {
    /// Set letter spacing to a specific number of logical pixels
    Px(f32),
    /// Set letter spacing to a multiple of the font size
    Rem(f32),
}

impl LetterSpacing {
    pub(crate) fn eval(self, rem_size: f32) -> f32 {
        match self {
            LetterSpacing::Px(px) => px,
            LetterSpacing::Rem(rem) => rem * rem_size,
        }
    }
}

impl Default for LetterSpacing {
    fn default() -> Self {
        Self::Px(0.0)
    }
}

/// The color of the text for this section.
#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)]
#[reflect(Component, Default, Debug, PartialEq, Clone)]
pub struct TextColor(pub Color);

impl Default for TextColor {
    fn default() -> Self {
        Self::WHITE
    }
}

impl<T: Into<Color>> From<T> for TextColor {
    fn from(color: T) -> Self {
        Self(color.into())
    }
}

impl TextColor {
    /// Black colored text
    pub const BLACK: Self = TextColor(Color::BLACK);
    /// White colored text
    pub const WHITE: Self = TextColor(Color::WHITE);
}

/// The background color of the text for this section.
#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)]
#[reflect(Component, Default, Debug, PartialEq, Clone)]
pub struct TextBackgroundColor(pub Color);

impl Default for TextBackgroundColor {
    fn default() -> Self {
        Self(Color::BLACK)
    }
}

impl<T: Into<Color>> From<T> for TextBackgroundColor {
    fn from(color: T) -> Self {
        Self(color.into())
    }
}

impl TextBackgroundColor {
    /// Black background
    pub const BLACK: Self = TextBackgroundColor(Color::BLACK);
    /// White background
    pub const WHITE: Self = TextBackgroundColor(Color::WHITE);
}

/// Determines how lines will be broken when preventing text from running out of bounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Reflect, Serialize, Deserialize)]
#[reflect(Serialize, Deserialize, Clone, PartialEq, Hash, Default)]
pub enum LineBreak {
    /// Uses the [Unicode Line Breaking Algorithm](https://www.unicode.org/reports/tr14/).
    /// Lines will be broken up at the nearest suitable word boundary, usually a space.
    /// This behavior suits most cases, as it keeps words intact across linebreaks.
    #[default]
    WordBoundary,
    /// Lines will be broken without discrimination on any character that would leave bounds.
    /// This is closer to the behavior one might expect from text in a terminal.
    /// However it may lead to words being broken up across linebreaks.
    AnyCharacter,
    /// Wraps at the word level, or fallback to character level if a word can’t fit on a line by itself
    WordOrCharacter,
    /// No soft wrapping, where text is automatically broken up into separate lines when it overflows a boundary, will ever occur.
    /// Hard wrapping, where text contains an explicit linebreak such as the escape sequence `\n`, is still enabled.
    NoWrap,
}

/// A text entity with this component is drawn with strikethrough.
#[derive(Component, Copy, Clone, Debug, Reflect, Default, Serialize, Deserialize)]
#[reflect(Serialize, Deserialize, Clone, Default)]
pub struct Strikethrough;

/// Color for the text's strikethrough. If this component is not present, its `TextColor` will be used.
#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)]
#[reflect(Component, Default, Debug, PartialEq, Clone)]
pub struct StrikethroughColor(pub Color);

impl Default for StrikethroughColor {
    fn default() -> Self {
        Self(Color::WHITE)
    }
}

impl<T: Into<Color>> From<T> for StrikethroughColor {
    fn from(color: T) -> Self {
        Self(color.into())
    }
}

/// Add to a text entity to draw its text with underline.
#[derive(Component, Copy, Clone, Debug, Reflect, Default, Serialize, Deserialize)]
#[reflect(Serialize, Deserialize, Clone, Default)]
pub struct Underline;

/// Color for the text's underline. If this component is not present, its `TextColor` will be used.
#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, Reflect, PartialEq)]
#[reflect(Component, Default, Debug, PartialEq, Clone)]
pub struct UnderlineColor(pub Color);

impl Default for UnderlineColor {
    fn default() -> Self {
        Self(Color::WHITE)
    }
}

impl<T: Into<Color>> From<T> for UnderlineColor {
    fn from(color: T) -> Self {
        Self(color.into())
    }
}

/// Determines which antialiasing method to use when rendering text. By default, text is
/// rendered with grayscale antialiasing, but this can be changed to achieve a pixelated look.
///
/// **Note:** Subpixel antialiasing is not currently supported.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Reflect, Serialize, Deserialize)]
#[reflect(Serialize, Deserialize, Clone, PartialEq, Hash, Default)]
#[doc(alias = "antialiasing")]
#[doc(alias = "pixelated")]
pub enum FontSmoothing {
    /// No antialiasing. Useful for when you want to render text with a pixel art aesthetic.
    ///
    /// Combine this with `UiAntiAlias::Off` and `Msaa::Off` on your 2D camera for a fully pixelated look.
    ///
    /// **Note:** Due to limitations of the underlying text rendering library,
    /// this may require specially-crafted pixel fonts to look good, especially at small sizes.
    None,
    /// The default grayscale antialiasing. Produces text that looks smooth,
    /// even at small font sizes and low resolutions with modern vector fonts.
    #[default]
    AntiAliased,
    // TODO: Add subpixel antialias support
    // SubpixelAntiAliased,
}

#[derive(Component, Debug, Copy, Clone, Default, Reflect, PartialEq, Hash, Eq)]
#[reflect(Component, Default, Debug, Clone, PartialEq)]
/// Font hinting strategy, which controls the rasterization for fonts.
///
/// Font hinting specializes the vector outlines to make them more clearer / more legible at a specific font size.
/// It is particularly noticeable with small text and low resolutions.
pub enum FontHinting {
    #[default]
    /// Glyphs are rasterized without hinting.
    Disabled,
    /// Glyphs are rasterized with hinting.
    Enabled,
}

impl FontHinting {
    /// Returns true if font hinting is enabled.
    pub fn is_enabled(self) -> bool {
        matches!(self, FontHinting::Enabled)
    }
}

/// System that detects changes to text blocks and sets `ComputedTextBlock::should_rerender`.
///
/// Does not check root text components (e.g. `Text`/`Text2d`) for changes. Their systems must handle change detection.
pub fn detect_text_needs_rerender(
    changed_roots: Query<
        Entity,
        (
            Or<(
                Changed<TextFont>,
                Changed<TextLayout>,
                Changed<LineHeight>,
                Changed<LetterSpacing>,
                Changed<Children>,
            )>,
            With<TextFont>,
            With<TextLayout>,
        ),
    >,
    changed_spans: Query<
        (Entity, Option<&ChildOf>, Has<TextLayout>),
        (
            Or<(
                Changed<TextSpan>,
                Changed<TextFont>,
                Changed<LineHeight>,
                Changed<LetterSpacing>,
                Changed<Children>,
                Changed<ChildOf>, // Included to detect broken text block hierarchies.
                Added<TextLayout>,
            )>,
            With<TextSpan>,
            With<TextFont>,
        ),
    >,
    mut computed: Query<(
        Option<&ChildOf>,
        Option<&mut ComputedTextBlock>,
        Has<TextSpan>,
    )>,
) {
    // Root entity:
    // - Root component changed.
    // - TextFont on root changed.
    // - TextLayout changed.
    // - Root children changed (can include additions and removals).
    for root in changed_roots.iter() {
        let Ok((_, Some(mut computed), _)) = computed.get_mut(root) else {
            once!(warn!("found entity {} with a root text component but no ComputedTextBlock; this warning only \
                prints once", root));
            continue;
        };
        computed.needs_rerender = true;
    }

    // Span entity:
    // - Span component changed.
    // - Span TextFont changed.
    // - Span children changed (can include additions and removals).
    for (entity, maybe_span_child_of, has_text_block) in changed_spans.iter() {
        if has_text_block {
            once!(warn!("found entity {} with a TextSpan that has a TextLayout, which should only be on root \
                text entities; this warning only prints once",
                entity));
        }

        let Some(span_child_of) = maybe_span_child_of else {
            once!(warn!(
                "found entity {} with a TextSpan that has no parent; it should have an ancestor \
                with a root text component; this warning only prints once",
                entity
            ));
            continue;
        };
        let mut parent: Entity = span_child_of.parent();

        // Search for the nearest ancestor with ComputedTextBlock.
        // Note: We assume the perf cost from duplicate visits in the case that multiple spans in a block are visited
        // is outweighed by the expense of tracking visited spans.
        loop {
            let Ok((maybe_child_of, maybe_computed, has_span)) = computed.get_mut(parent) else {
                once!(warn!("found entity {} with a TextSpan that is part of a broken hierarchy with a ChildOf \
                    component that points at non-existent entity {}; this warning only prints once",
                    entity, parent));
                break;
            };
            if let Some(mut computed) = maybe_computed {
                computed.needs_rerender = true;
                break;
            }
            if !has_span {
                once!(warn!("found entity {} with a TextSpan that has an ancestor ({}) that does not have a text \
                span component or a ComputedTextBlock component; this warning only prints once",
                    entity, parent));
                break;
            }
            let Some(next_child_of) = maybe_child_of else {
                once!(warn!(
                    "found entity {} with a TextSpan that has no ancestor with the root text \
                    component; this warning only prints once",
                    entity
                ));
                break;
            };
            parent = next_child_of.parent();
        }
    }
}