Skip to main content

waft_material/
text_theme.rs

1//! Flutter counterpart: material_ui's `text_theme.dart`.
2
3use waft_embedder::{Color, FontFeature, FontVariation, TextDecoration, TextDecorationStyle};
4use waft_foundation::{App, DiagnosticsProperty};
5use waft_painting::TextStyle;
6use waft_widgets::BuildContext;
7
8use crate::theme::Theme;
9
10/// Material design text theme.
11///
12/// Definitions for the various typographical styles found in Material Design
13/// (e.g., label_large, body_small). Rather than creating a [`TextTheme`] directly,
14/// you can obtain an instance as `Typography.black` or `Typography.white`.
15///
16/// To obtain the current text theme, call [`TextTheme::of`] with the current
17/// `BuildContext`. This is equivalent to calling `Theme::of` and reading
18/// the `ThemeData.text_theme` property.
19///
20/// The names of the TextTheme properties match this table from the
21/// [Material Design spec](https://m3.material.io/styles/typography/tokens).
22///
23/// ![](https://lh3.googleusercontent.com/Yvngs5mQSjXa_9T4X3JDucO62c5hdZHPDa7qeRH6DsJQvGr_q7EBrTkhkPiQd9OeR1v_Uk38Cjd9nUpP3nevDyHpKWuXSfQ1Gq78bOnBN7sr=s0)
24///
25/// The Material Design typography scheme was significantly changed in the
26/// current (2021) version of the specification
27/// ([https://m3.material.io/styles/typography/tokens](https://m3.material.io/styles/typography/tokens)).
28///
29/// The **2021** spec has fifteen text styles:
30///
31/// | NAME           | SIZE |  HEIGHT |  WEIGHT |  SPACING |             |
32/// |----------------|------|---------|---------|----------|-------------|
33/// | displayLarge   | 57.0 |   64.0  | regular | -0.25    |             |
34/// | displayMedium  | 45.0 |   52.0  | regular |  0.0     |             |
35/// | displaySmall   | 36.0 |   44.0  | regular |  0.0     |             |
36/// | headlineLarge  | 32.0 |   40.0  | regular |  0.0     |             |
37/// | headlineMedium | 28.0 |   36.0  | regular |  0.0     |             |
38/// | headlineSmall  | 24.0 |   32.0  | regular |  0.0     |             |
39/// | titleLarge     | 22.0 |   28.0  | regular |  0.0     |             |
40/// | titleMedium    | 16.0 |   24.0  | medium  |  0.15    |             |
41/// | titleSmall     | 14.0 |   20.0  | medium  |  0.1     |             |
42/// | bodyLarge      | 16.0 |   24.0  | regular |  0.5     |             |
43/// | bodyMedium     | 14.0 |   20.0  | regular |  0.25    |             |
44/// | bodySmall      | 12.0 |   16.0  | regular |  0.4     |             |
45/// | labelLarge     | 14.0 |   20.0  | medium  |  0.1     |             |
46/// | labelMedium    | 12.0 |   16.0  | medium  |  0.5     |             |
47/// | labelSmall     | 11.0 |   16.0  | medium  |  0.5     |             |
48///
49/// ...where "regular" is `FontWeight.w400` and "medium" is `FontWeight.w500`.
50///
51/// The names of the 2018 TextTheme properties match this table from the
52/// [Material Design spec](https://material.io/design/typography/the-type-system.html#type-scale)
53/// with a few exceptions: the styles called H1-H6 in the spec are
54/// displayLarge-titleLarge in the API chart, body1,body2 are called
55/// bodyLarge and bodyMedium, caption is now bodySmall, button is labelLarge,
56/// and overline is now labelSmall.
57///
58/// The **2018** spec has thirteen text styles:
59///
60/// | NAME           | SIZE |  WEIGHT |  SPACING |             |
61/// |----------------|------|---------|----------|-------------|
62/// | displayLarge   | 96.0 | light   | -1.5     |             |
63/// | displayMedium  | 60.0 | light   | -0.5     |             |
64/// | displaySmall   | 48.0 | regular |  0.0     |             |
65/// | headlineMedium | 34.0 | regular |  0.25    |             |
66/// | headlineSmall  | 24.0 | regular |  0.0     |             |
67/// | titleLarge     | 20.0 | medium  |  0.15    |             |
68/// | titleMedium    | 16.0 | regular |  0.15    |             |
69/// | titleSmall     | 14.0 | medium  |  0.1     |             |
70/// | bodyLarge      | 16.0 | regular |  0.5     |             |
71/// | bodyMedium     | 14.0 | regular |  0.25    |             |
72/// | bodySmall      | 12.0 | regular |  0.4     |             |
73/// | labelLarge     | 14.0 | medium  |  1.25    |             |
74/// | labelSmall     | 10.0 | regular |  1.5     |             |
75///
76/// ...where "light" is `FontWeight.w300`, "regular" is `FontWeight.w400` and
77/// "medium" is `FontWeight.w500`.
78///
79/// By default, text styles are initialized to match the 2018 Material Design
80/// specification as listed above. To provide backwards compatibility, the 2014
81/// specification is also available.
82///
83/// To explicitly configure a `Theme` for the 2018 sizes, weights, and letter
84/// spacings, you can initialize its `ThemeData.typography` value using
85/// `Typography.material2018`. The `Typography` constructor defaults to this
86/// configuration. To configure a `Theme` for the 2014 sizes, weights, and letter
87/// spacings, initialize its `ThemeData.typography` value using
88/// `Typography.material2014`.
89///
90/// See also:
91///
92///  * `Typography`, the class that generates [`TextTheme`]s appropriate for a platform.
93///  * `Theme`, for other aspects of a Material Design application that can be
94///    globally adjusted, such as the color scheme.
95///  * <https://material.io/design/typography/>
96#[derive(Clone, Debug, Default, PartialEq)]
97pub struct TextTheme {
98    /// Largest of the display styles.
99    ///
100    /// As the largest text on the screen, display styles are reserved for short,
101    /// important text or numerals. They work best on large screens.
102    pub display_large: Option<TextStyle>,
103    /// Middle size of the display styles.
104    ///
105    /// As the largest text on the screen, display styles are reserved for short,
106    /// important text or numerals. They work best on large screens.
107    pub display_medium: Option<TextStyle>,
108    /// Smallest of the display styles.
109    ///
110    /// As the largest text on the screen, display styles are reserved for short,
111    /// important text or numerals. They work best on large screens.
112    pub display_small: Option<TextStyle>,
113    /// Largest of the headline styles.
114    ///
115    /// Headline styles are smaller than display styles. They're best-suited for
116    /// short, high-emphasis text on smaller screens.
117    pub headline_large: Option<TextStyle>,
118    /// Middle size of the headline styles.
119    ///
120    /// Headline styles are smaller than display styles. They're best-suited for
121    /// short, high-emphasis text on smaller screens.
122    pub headline_medium: Option<TextStyle>,
123    /// Smallest of the headline styles.
124    ///
125    /// Headline styles are smaller than display styles. They're best-suited for
126    /// short, high-emphasis text on smaller screens.
127    pub headline_small: Option<TextStyle>,
128    /// Largest of the title styles.
129    ///
130    /// Titles are smaller than headline styles and should be used for shorter,
131    /// medium-emphasis text.
132    pub title_large: Option<TextStyle>,
133    /// Middle size of the title styles.
134    ///
135    /// Titles are smaller than headline styles and should be used for shorter,
136    /// medium-emphasis text.
137    pub title_medium: Option<TextStyle>,
138    /// Smallest of the title styles.
139    ///
140    /// Titles are smaller than headline styles and should be used for shorter,
141    /// medium-emphasis text.
142    pub title_small: Option<TextStyle>,
143    /// Largest of the body styles.
144    ///
145    /// Body styles are used for longer passages of text.
146    pub body_large: Option<TextStyle>,
147    /// Middle size of the body styles.
148    ///
149    /// Body styles are used for longer passages of text.
150    ///
151    /// The default text style for `Material`.
152    pub body_medium: Option<TextStyle>,
153    /// Smallest of the body styles.
154    ///
155    /// Body styles are used for longer passages of text.
156    pub body_small: Option<TextStyle>,
157    /// Largest of the label styles.
158    ///
159    /// Label styles are smaller, utilitarian styles, used for areas of the UI
160    /// such as text inside of components or very small supporting text in the
161    /// content body, like captions.
162    ///
163    /// Used for text on `ElevatedButton`, `TextButton` and `OutlinedButton`.
164    pub label_large: Option<TextStyle>,
165    /// Middle size of the label styles.
166    ///
167    /// Label styles are smaller, utilitarian styles, used for areas of the UI
168    /// such as text inside of components or very small supporting text in the
169    /// content body, like captions.
170    pub label_medium: Option<TextStyle>,
171    /// Smallest of the label styles.
172    ///
173    /// Label styles are smaller, utilitarian styles, used for areas of the UI
174    /// such as text inside of components or very small supporting text in the
175    /// content body, like captions.
176    pub label_small: Option<TextStyle>,
177}
178
179impl TextTheme {
180    /// Creates a text theme that uses the given values.
181    ///
182    /// Rather than creating a new text theme, consider using `Typography.black`
183    /// or `Typography.white`, which implement the typography styles in the
184    /// Material Design specification:
185    ///
186    /// <https://material.io/design/typography/#type-scale>
187    ///
188    /// If you do decide to create your own text theme, consider using one of
189    /// those predefined themes as a starting point for [`copy_with`](Self::copy_with) or
190    /// [`apply`](Self::apply).
191    ///
192    /// The 2018 styles cannot be mixed with the 2021 styles. Only one or the
193    /// other is allowed in this constructor. The 2018 styles are deprecated and
194    /// will eventually be removed.
195    pub fn new() -> TextTheme {
196        TextTheme::default()
197    }
198
199    /// Dart `TextTheme(displayLarge:)`.
200    pub fn display_large(mut self, display_large: TextStyle) -> TextTheme {
201        self.display_large = Some(display_large);
202        self
203    }
204
205    /// Dart `TextTheme(displayMedium:)`.
206    pub fn display_medium(mut self, display_medium: TextStyle) -> TextTheme {
207        self.display_medium = Some(display_medium);
208        self
209    }
210
211    /// Dart `TextTheme(displaySmall:)`.
212    pub fn display_small(mut self, display_small: TextStyle) -> TextTheme {
213        self.display_small = Some(display_small);
214        self
215    }
216
217    /// Dart `TextTheme(headlineLarge:)`.
218    pub fn headline_large(mut self, headline_large: TextStyle) -> TextTheme {
219        self.headline_large = Some(headline_large);
220        self
221    }
222
223    /// Dart `TextTheme(headlineMedium:)`.
224    pub fn headline_medium(mut self, headline_medium: TextStyle) -> TextTheme {
225        self.headline_medium = Some(headline_medium);
226        self
227    }
228
229    /// Dart `TextTheme(headlineSmall:)`.
230    pub fn headline_small(mut self, headline_small: TextStyle) -> TextTheme {
231        self.headline_small = Some(headline_small);
232        self
233    }
234
235    /// Dart `TextTheme(titleLarge:)`.
236    pub fn title_large(mut self, title_large: TextStyle) -> TextTheme {
237        self.title_large = Some(title_large);
238        self
239    }
240
241    /// Dart `TextTheme(titleMedium:)`.
242    pub fn title_medium(mut self, title_medium: TextStyle) -> TextTheme {
243        self.title_medium = Some(title_medium);
244        self
245    }
246
247    /// Dart `TextTheme(titleSmall:)`.
248    pub fn title_small(mut self, title_small: TextStyle) -> TextTheme {
249        self.title_small = Some(title_small);
250        self
251    }
252
253    /// Dart `TextTheme(bodyLarge:)`.
254    pub fn body_large(mut self, body_large: TextStyle) -> TextTheme {
255        self.body_large = Some(body_large);
256        self
257    }
258
259    /// Dart `TextTheme(bodyMedium:)`.
260    pub fn body_medium(mut self, body_medium: TextStyle) -> TextTheme {
261        self.body_medium = Some(body_medium);
262        self
263    }
264
265    /// Dart `TextTheme(bodySmall:)`.
266    pub fn body_small(mut self, body_small: TextStyle) -> TextTheme {
267        self.body_small = Some(body_small);
268        self
269    }
270
271    /// Dart `TextTheme(labelLarge:)`.
272    pub fn label_large(mut self, label_large: TextStyle) -> TextTheme {
273        self.label_large = Some(label_large);
274        self
275    }
276
277    /// Dart `TextTheme(labelMedium:)`.
278    pub fn label_medium(mut self, label_medium: TextStyle) -> TextTheme {
279        self.label_medium = Some(label_medium);
280        self
281    }
282
283    /// Dart `TextTheme(labelSmall:)`.
284    pub fn label_small(mut self, label_small: TextStyle) -> TextTheme {
285        self.label_small = Some(label_small);
286        self
287    }
288
289    /// Creates a copy of this text theme but with the given fields replaced with
290    /// the new values.
291    ///
292    /// Consider using `Typography.black` or `Typography.white`, which implement
293    /// the typography styles in the Material Design specification, as a starting
294    /// point.
295    ///
296    /// Dart's named arguments are the setters on the copy:
297    /// `theme.copy_with().title_large(style)`.
298    ///
299    /// See also:
300    ///
301    ///  * [`merge`](Self::merge) is used instead of [`copy_with`](Self::copy_with) when you
302    ///    want to merge all of the fields of a TextTheme instead of individual fields.
303    pub fn copy_with(&self) -> TextTheme {
304        self.clone()
305    }
306
307    /// Creates a new [`TextTheme`] where each text style from this object has been
308    /// merged with the matching text style from the `other` object.
309    ///
310    /// The merging is done by calling [`TextStyle::merge`] on each respective pair
311    /// of text styles from this and the `other` text themes and is subject to
312    /// the value of [`TextStyle::inherit`] flag. For more details, see the
313    /// documentation on [`TextStyle::merge`] and [`TextStyle::inherit`].
314    ///
315    /// If this theme, or the `other` theme has members that are null, then the
316    /// non-null one (if any) is used. If the `other` theme is itself null, then
317    /// this [`TextTheme`] is returned unchanged. If values in both are set, then
318    /// the values are merged using [`TextStyle::merge`].
319    ///
320    /// This is particularly useful if one [`TextTheme`] defines one set of
321    /// properties and another defines a different set, e.g. having colors
322    /// defined in one text theme and font sizes in another, or when one
323    /// [`TextTheme`] has only some fields defined, and you want to define the rest
324    /// by merging it with a default theme.
325    ///
326    /// See also:
327    ///
328    ///  * [`copy_with`](Self::copy_with) is used instead of [`merge`](Self::merge) when you
329    ///    wish to override individual fields in the [`TextTheme`] instead of merging all of
330    ///    the fields of two [`TextTheme`]s.
331    pub fn merge(&self, other: Option<&TextTheme>) -> TextTheme {
332        let Some(other) = other else {
333            return self.clone();
334        };
335
336        fn merge_styles(
337            style: &Option<TextStyle>,
338            other_style: &Option<TextStyle>,
339        ) -> Option<TextStyle> {
340            match style {
341                Some(style) => Some(style.merge(other_style.as_ref())),
342                None => other_style.clone(),
343            }
344        }
345
346        TextTheme {
347            display_large: merge_styles(&self.display_large, &other.display_large),
348            display_medium: merge_styles(&self.display_medium, &other.display_medium),
349            display_small: merge_styles(&self.display_small, &other.display_small),
350            headline_large: merge_styles(&self.headline_large, &other.headline_large),
351            headline_medium: merge_styles(&self.headline_medium, &other.headline_medium),
352            headline_small: merge_styles(&self.headline_small, &other.headline_small),
353            title_large: merge_styles(&self.title_large, &other.title_large),
354            title_medium: merge_styles(&self.title_medium, &other.title_medium),
355            title_small: merge_styles(&self.title_small, &other.title_small),
356            body_large: merge_styles(&self.body_large, &other.body_large),
357            body_medium: merge_styles(&self.body_medium, &other.body_medium),
358            body_small: merge_styles(&self.body_small, &other.body_small),
359            label_large: merge_styles(&self.label_large, &other.label_large),
360            label_medium: merge_styles(&self.label_medium, &other.label_medium),
361            label_small: merge_styles(&self.label_small, &other.label_small),
362        }
363    }
364
365    /// Creates a copy of this text theme but with the given field replaced in
366    /// each of the individual text styles.
367    ///
368    /// The `display_color` is applied to [`display_large`](Self::display_large),
369    /// [`display_medium`](Self::display_medium), [`display_small`](Self::display_small),
370    /// [`headline_large`](Self::headline_large), [`headline_medium`](Self::headline_medium),
371    /// and [`body_small`](Self::body_small). The `body_color` is applied to the remaining
372    /// text styles.
373    ///
374    /// Consider using `Typography.black` or `Typography.white`, which implement
375    /// the typography styles in the Material Design specification, as a starting
376    /// point.
377    ///
378    /// Chain the named arguments, then [`TextThemeApply::into_text_theme`];
379    /// `theme.apply()` with no further setters is Dart `apply()` with defaults.
380    pub fn apply(&self) -> TextThemeApply<'_> {
381        TextThemeApply::new(self)
382    }
383
384    /// Linearly interpolate between two text themes.
385    ///
386    /// {@macro dart.ui.shadow.lerp}
387    pub fn lerp(a: Option<&TextTheme>, b: Option<&TextTheme>, t: f64) -> TextTheme {
388        if let (Some(a), Some(b)) = (a, b)
389            && std::ptr::eq(a, b)
390        {
391            return a.clone();
392        }
393        let lerp = |style: fn(&TextTheme) -> Option<&TextStyle>| {
394            TextStyle::lerp(a.and_then(style), b.and_then(style), t)
395        };
396        TextTheme {
397            display_large: lerp(|theme| theme.display_large.as_ref()),
398            display_medium: lerp(|theme| theme.display_medium.as_ref()),
399            display_small: lerp(|theme| theme.display_small.as_ref()),
400            headline_large: lerp(|theme| theme.headline_large.as_ref()),
401            headline_medium: lerp(|theme| theme.headline_medium.as_ref()),
402            headline_small: lerp(|theme| theme.headline_small.as_ref()),
403            title_large: lerp(|theme| theme.title_large.as_ref()),
404            title_medium: lerp(|theme| theme.title_medium.as_ref()),
405            title_small: lerp(|theme| theme.title_small.as_ref()),
406            body_large: lerp(|theme| theme.body_large.as_ref()),
407            body_medium: lerp(|theme| theme.body_medium.as_ref()),
408            body_small: lerp(|theme| theme.body_small.as_ref()),
409            label_large: lerp(|theme| theme.label_large.as_ref()),
410            label_medium: lerp(|theme| theme.label_medium.as_ref()),
411            label_small: lerp(|theme| theme.label_small.as_ref()),
412        }
413    }
414
415    /// The `ThemeData.text_theme` property of the ambient `Theme`.
416    ///
417    /// Equivalent to `Theme::of(app, context).text_theme`.
418    ///
419    /// See also:
420    /// * [`TextTheme::primary_of`], which returns the `ThemeData.primary_text_theme` property
421    ///   of the ambient `Theme` instead.
422    pub fn of(app: &mut App, context: BuildContext) -> TextTheme {
423        Theme::of(app, context).text_theme.clone()
424    }
425
426    /// The `ThemeData.primary_text_theme` property of the ambient `Theme`.
427    ///
428    ///
429    /// Equivalent to `Theme::of(app, context).primary_text_theme`.
430    ///
431    /// See also:
432    /// * [`TextTheme::of`], which returns the `ThemeData.text_theme` property of the ambient
433    ///   `Theme` instead.
434    pub fn primary_of(app: &mut App, context: BuildContext) -> TextTheme {
435        Theme::of(app, context).primary_text_theme.clone()
436    }
437}
438
439/// Dart `TextTheme.apply` named optionals.
440pub struct TextThemeApply<'a> {
441    theme: &'a TextTheme,
442    font_family: Option<String>,
443    font_family_fallback: Option<Vec<String>>,
444    package: Option<String>,
445    font_size_factor: f64,
446    font_size_delta: f64,
447    letter_spacing_factor: f64,
448    letter_spacing_delta: f64,
449    word_spacing_factor: f64,
450    word_spacing_delta: f64,
451    height_factor: f64,
452    height_delta: f64,
453    display_color: Option<Color>,
454    body_color: Option<Color>,
455    decoration: Option<TextDecoration>,
456    decoration_color: Option<Color>,
457    decoration_style: Option<TextDecorationStyle>,
458    font_features: Option<Vec<FontFeature>>,
459    font_variations: Option<Vec<FontVariation>>,
460}
461
462impl<'a> TextThemeApply<'a> {
463    fn new(theme: &'a TextTheme) -> TextThemeApply<'a> {
464        TextThemeApply {
465            theme,
466            font_family: None,
467            font_family_fallback: None,
468            package: None,
469            font_size_factor: 1.0,
470            font_size_delta: 0.0,
471            letter_spacing_factor: 1.0,
472            letter_spacing_delta: 0.0,
473            word_spacing_factor: 1.0,
474            word_spacing_delta: 0.0,
475            height_factor: 1.0,
476            height_delta: 0.0,
477            display_color: None,
478            body_color: None,
479            decoration: None,
480            decoration_color: None,
481            decoration_style: None,
482            font_features: None,
483            font_variations: None,
484        }
485    }
486
487    /// Dart `apply(fontFamily:)`.
488    pub fn font_family(mut self, font_family: impl Into<String>) -> TextThemeApply<'a> {
489        self.font_family = Some(font_family.into());
490        self
491    }
492
493    /// Dart `apply(fontFamilyFallback:)`.
494    pub fn font_family_fallback(mut self, font_family_fallback: Vec<String>) -> TextThemeApply<'a> {
495        self.font_family_fallback = Some(font_family_fallback);
496        self
497    }
498
499    /// Dart `apply(package:)`.
500    pub fn package(mut self, package: impl Into<String>) -> TextThemeApply<'a> {
501        self.package = Some(package.into());
502        self
503    }
504
505    /// Dart `apply(fontSizeFactor:)`.
506    pub fn font_size_factor(mut self, font_size_factor: f64) -> TextThemeApply<'a> {
507        self.font_size_factor = font_size_factor;
508        self
509    }
510
511    /// Dart `apply(fontSizeDelta:)`.
512    pub fn font_size_delta(mut self, font_size_delta: f64) -> TextThemeApply<'a> {
513        self.font_size_delta = font_size_delta;
514        self
515    }
516
517    /// Dart `apply(letterSpacingFactor:)`.
518    pub fn letter_spacing_factor(mut self, letter_spacing_factor: f64) -> TextThemeApply<'a> {
519        self.letter_spacing_factor = letter_spacing_factor;
520        self
521    }
522
523    /// Dart `apply(letterSpacingDelta:)`.
524    pub fn letter_spacing_delta(mut self, letter_spacing_delta: f64) -> TextThemeApply<'a> {
525        self.letter_spacing_delta = letter_spacing_delta;
526        self
527    }
528
529    /// Dart `apply(wordSpacingFactor:)`.
530    pub fn word_spacing_factor(mut self, word_spacing_factor: f64) -> TextThemeApply<'a> {
531        self.word_spacing_factor = word_spacing_factor;
532        self
533    }
534
535    /// Dart `apply(wordSpacingDelta:)`.
536    pub fn word_spacing_delta(mut self, word_spacing_delta: f64) -> TextThemeApply<'a> {
537        self.word_spacing_delta = word_spacing_delta;
538        self
539    }
540
541    /// Dart `apply(heightFactor:)`.
542    pub fn height_factor(mut self, height_factor: f64) -> TextThemeApply<'a> {
543        self.height_factor = height_factor;
544        self
545    }
546
547    /// Dart `apply(heightDelta:)`.
548    pub fn height_delta(mut self, height_delta: f64) -> TextThemeApply<'a> {
549        self.height_delta = height_delta;
550        self
551    }
552
553    /// Dart `apply(displayColor:)`.
554    pub fn display_color(mut self, display_color: Color) -> TextThemeApply<'a> {
555        self.display_color = Some(display_color);
556        self
557    }
558
559    /// Dart `apply(bodyColor:)`.
560    pub fn body_color(mut self, body_color: Color) -> TextThemeApply<'a> {
561        self.body_color = Some(body_color);
562        self
563    }
564
565    /// Dart `apply(decoration:)`.
566    pub fn decoration(mut self, decoration: TextDecoration) -> TextThemeApply<'a> {
567        self.decoration = Some(decoration);
568        self
569    }
570
571    /// Dart `apply(decorationColor:)`.
572    pub fn decoration_color(mut self, decoration_color: Color) -> TextThemeApply<'a> {
573        self.decoration_color = Some(decoration_color);
574        self
575    }
576
577    /// Dart `apply(decorationStyle:)`.
578    pub fn decoration_style(mut self, decoration_style: TextDecorationStyle) -> TextThemeApply<'a> {
579        self.decoration_style = Some(decoration_style);
580        self
581    }
582
583    /// Dart `apply(fontFeatures:)`.
584    pub fn font_features(mut self, font_features: Vec<FontFeature>) -> TextThemeApply<'a> {
585        self.font_features = Some(font_features);
586        self
587    }
588
589    /// Dart `apply(fontVariations:)`.
590    pub fn font_variations(mut self, font_variations: Vec<FontVariation>) -> TextThemeApply<'a> {
591        self.font_variations = Some(font_variations);
592        self
593    }
594
595    /// The text theme with every style applied.
596    pub fn into_text_theme(self) -> TextTheme {
597        let theme = self.theme;
598        let display_color = self.display_color;
599        let body_color = self.body_color;
600        TextTheme {
601            display_large: self.apply_to(theme.display_large.as_ref(), display_color),
602            display_medium: self.apply_to(theme.display_medium.as_ref(), display_color),
603            display_small: self.apply_to(theme.display_small.as_ref(), display_color),
604            headline_large: self.apply_to(theme.headline_large.as_ref(), display_color),
605            headline_medium: self.apply_to(theme.headline_medium.as_ref(), display_color),
606            headline_small: self.apply_to(theme.headline_small.as_ref(), body_color),
607            title_large: self.apply_to(theme.title_large.as_ref(), body_color),
608            title_medium: self.apply_to(theme.title_medium.as_ref(), body_color),
609            title_small: self.apply_to(theme.title_small.as_ref(), body_color),
610            body_large: self.apply_to(theme.body_large.as_ref(), body_color),
611            body_medium: self.apply_to(theme.body_medium.as_ref(), body_color),
612            body_small: self.apply_to(theme.body_small.as_ref(), display_color),
613            label_large: self.apply_to(theme.label_large.as_ref(), body_color),
614            label_medium: self.apply_to(theme.label_medium.as_ref(), body_color),
615            label_small: self.apply_to(theme.label_small.as_ref(), body_color),
616        }
617    }
618
619    /// Dart's local `applyTo`.
620    fn apply_to(&self, style: Option<&TextStyle>, color: Option<Color>) -> Option<TextStyle> {
621        let mut apply = style?
622            .apply()
623            .font_size_factor(self.font_size_factor)
624            .font_size_delta(self.font_size_delta)
625            .letter_spacing_delta(self.letter_spacing_delta)
626            .letter_spacing_factor(self.letter_spacing_factor)
627            .word_spacing_delta(self.word_spacing_delta)
628            .word_spacing_factor(self.word_spacing_factor)
629            .height_factor(self.height_factor)
630            .height_delta(self.height_delta);
631        if let Some(color) = color {
632            apply = apply.color(color);
633        }
634        if let Some(decoration) = self.decoration {
635            apply = apply.decoration(decoration);
636        }
637        if let Some(decoration_color) = self.decoration_color {
638            apply = apply.decoration_color(decoration_color);
639        }
640        if let Some(decoration_style) = self.decoration_style {
641            apply = apply.decoration_style(decoration_style);
642        }
643        if let Some(font_family) = &self.font_family {
644            apply = apply.font_family(font_family.clone());
645        }
646        if let Some(font_family_fallback) = &self.font_family_fallback {
647            apply = apply.font_family_fallback(font_family_fallback.clone());
648        }
649        if let Some(package) = &self.package {
650            apply = apply.package(package.clone());
651        }
652        if let Some(font_features) = &self.font_features {
653            apply = apply.font_features(font_features.clone());
654        }
655        if let Some(font_variations) = &self.font_variations {
656            apply = apply.font_variations(font_variations.clone());
657        }
658        Some(apply.into_style())
659    }
660}
661
662impl From<TextThemeApply<'_>> for TextTheme {
663    fn from(apply: TextThemeApply<'_>) -> TextTheme {
664        apply.into_text_theme()
665    }
666}
667
668impl waft_foundation::Diagnosticable for TextTheme {
669    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
670        // Dart's `defaultTargetPlatform`; [`Typography::material2018`]'s default platform is
671        // Android. Diagnostics on another platform compare against Android's defaults.
672        let default_theme = crate::typography::Typography::material2018().build().black;
673        properties.add(
674            DiagnosticsProperty::<TextStyle>::new("displayLarge", self.display_large.clone())
675                .default_value(default_theme.display_large.clone()),
676        );
677        properties.add(
678            DiagnosticsProperty::<TextStyle>::new("displayMedium", self.display_medium.clone())
679                .default_value(default_theme.display_medium.clone()),
680        );
681        properties.add(
682            DiagnosticsProperty::<TextStyle>::new("displaySmall", self.display_small.clone())
683                .default_value(default_theme.display_small.clone()),
684        );
685        properties.add(
686            DiagnosticsProperty::<TextStyle>::new("headlineLarge", self.headline_large.clone())
687                .default_value(default_theme.headline_large.clone()),
688        );
689        properties.add(
690            DiagnosticsProperty::<TextStyle>::new("headlineMedium", self.headline_medium.clone())
691                .default_value(default_theme.headline_medium.clone()),
692        );
693        properties.add(
694            DiagnosticsProperty::<TextStyle>::new("headlineSmall", self.headline_small.clone())
695                .default_value(default_theme.headline_small.clone()),
696        );
697        properties.add(
698            DiagnosticsProperty::<TextStyle>::new("titleLarge", self.title_large.clone())
699                .default_value(default_theme.title_large.clone()),
700        );
701        properties.add(
702            DiagnosticsProperty::<TextStyle>::new("titleMedium", self.title_medium.clone())
703                .default_value(default_theme.title_medium.clone()),
704        );
705        properties.add(
706            DiagnosticsProperty::<TextStyle>::new("titleSmall", self.title_small.clone())
707                .default_value(default_theme.title_small.clone()),
708        );
709        properties.add(
710            DiagnosticsProperty::<TextStyle>::new("bodyLarge", self.body_large.clone())
711                .default_value(default_theme.body_large.clone()),
712        );
713        properties.add(
714            DiagnosticsProperty::<TextStyle>::new("bodyMedium", self.body_medium.clone())
715                .default_value(default_theme.body_medium.clone()),
716        );
717        properties.add(
718            DiagnosticsProperty::<TextStyle>::new("bodySmall", self.body_small.clone())
719                .default_value(default_theme.body_small.clone()),
720        );
721        properties.add(
722            DiagnosticsProperty::<TextStyle>::new("labelLarge", self.label_large.clone())
723                .default_value(default_theme.label_large.clone()),
724        );
725        properties.add(
726            DiagnosticsProperty::<TextStyle>::new("labelMedium", self.label_medium.clone())
727                .default_value(default_theme.label_medium.clone()),
728        );
729        properties.add(
730            DiagnosticsProperty::<TextStyle>::new("labelSmall", self.label_small.clone())
731                .default_value(default_theme.label_small.clone()),
732        );
733    }
734}
735
736impl std::fmt::Display for TextTheme {
737    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
738        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
739    }
740}
741
742#[cfg(test)]
743mod tests {
744    use waft_embedder::{Brightness, FontStyle};
745    use waft_widgets::IntoWidget;
746
747    use waft_widgets::testing::test_widgets;
748
749    use super::*;
750    use crate::colors::Colors;
751    use crate::test_support::probe;
752    use crate::theme::Theme;
753    use crate::theme_data::ThemeData;
754    use crate::typography::Typography;
755
756    fn styles(theme: &TextTheme) -> [&TextStyle; 15] {
757        [
758            &theme.display_large,
759            &theme.display_medium,
760            &theme.display_small,
761            &theme.headline_large,
762            &theme.headline_medium,
763            &theme.headline_small,
764            &theme.title_large,
765            &theme.title_medium,
766            &theme.title_small,
767            &theme.body_large,
768            &theme.body_medium,
769            &theme.body_small,
770            &theme.label_large,
771            &theme.label_medium,
772            &theme.label_small,
773        ]
774        .map(|style| style.as_ref().expect("the text theme has this style"))
775    }
776
777    fn optional_styles(theme: &TextTheme) -> [&Option<TextStyle>; 15] {
778        [
779            &theme.display_large,
780            &theme.display_medium,
781            &theme.display_small,
782            &theme.headline_large,
783            &theme.headline_medium,
784            &theme.headline_small,
785            &theme.title_large,
786            &theme.title_medium,
787            &theme.title_small,
788            &theme.body_large,
789            &theme.body_medium,
790            &theme.body_small,
791            &theme.label_large,
792            &theme.label_medium,
793            &theme.label_small,
794        ]
795    }
796
797    fn color(color: Color) -> Option<waft_painting::AnyColor> {
798        Some(color.into())
799    }
800
801    #[test]
802    fn copy_with_apply_and_merge_of_an_empty_text_theme_are_empty() {
803        assert_eq!(TextTheme::new(), TextTheme::new().copy_with());
804        assert_eq!(TextTheme::new(), TextTheme::new().apply().into_text_theme());
805        assert_eq!(TextTheme::new(), TextTheme::new().merge(None));
806    }
807
808    #[test]
809    fn lerp_special_cases() {
810        assert_eq!(TextTheme::lerp(None, None, 0.0), TextTheme::new());
811        let theme = TextTheme::new();
812        assert_eq!(TextTheme::lerp(Some(&theme), Some(&theme), 0.5), theme);
813    }
814
815    #[test]
816    fn copy_with_apply_and_merge_of_typography_black() {
817        let typography = Typography::material2018().build();
818        assert_eq!(*typography.black, typography.black.copy_with());
819        assert_eq!(
820            *typography.black,
821            typography.black.apply().into_text_theme()
822        );
823        assert_eq!(*typography.black, typography.black.merge(None));
824        assert_eq!(
825            *typography.black,
826            TextTheme::new().merge(Some(&typography.black))
827        );
828        assert_eq!(
829            *typography.black,
830            typography.black.merge(Some(&typography.black))
831        );
832        assert_eq!(
833            *typography.white,
834            typography.black.merge(Some(&typography.white))
835        );
836        assert_ne!(typography.black, typography.white);
837    }
838
839    #[test]
840    fn copy_with_replaces_every_style() {
841        let typography = Typography::material2018().build();
842        let white = &typography.white;
843        let style = |style: &Option<TextStyle>| style.clone().expect("a style");
844        let white_copy = typography
845            .black
846            .copy_with()
847            .display_large(style(&white.display_large))
848            .display_medium(style(&white.display_medium))
849            .display_small(style(&white.display_small))
850            .headline_large(style(&white.headline_large))
851            .headline_medium(style(&white.headline_medium))
852            .headline_small(style(&white.headline_small))
853            .title_large(style(&white.title_large))
854            .title_medium(style(&white.title_medium))
855            .title_small(style(&white.title_small))
856            .body_large(style(&white.body_large))
857            .body_medium(style(&white.body_medium))
858            .body_small(style(&white.body_small))
859            .label_large(style(&white.label_large))
860            .label_medium(style(&white.label_medium))
861            .label_small(style(&white.label_small));
862        assert_eq!(*typography.white, white_copy);
863    }
864
865    #[test]
866    fn merges_properly_in_the_presence_of_null_fields() {
867        test_widgets(|tester| {
868            let partial_theme =
869                TextTheme::new().title_large(TextStyle::new().color(Color::new(0xcafefeed)));
870            let full_theme = ThemeData::fallback(&tester.cell.borrow(), None)
871                .text_theme
872                .merge(Some(&partial_theme));
873            assert_eq!(
874                full_theme.title_large.and_then(|style| style.color),
875                color(Color::new(0xcafefeed))
876            );
877        });
878
879        let only_headline_small_and_title_large = TextTheme::new()
880            .headline_small(TextStyle::new().color(Color::new(0xcafefeed)))
881            .title_large(TextStyle::new().color(Color::new(0xbeefcafe)));
882        let only_body_medium_and_title_large = TextTheme::new()
883            .body_medium(TextStyle::new().color(Color::new(0xfeedfeed)))
884            .title_large(TextStyle::new().color(Color::new(0xdeadcafe)));
885        let merged =
886            only_headline_small_and_title_large.merge(Some(&only_body_medium_and_title_large));
887        assert!(merged.body_large.is_none());
888        assert_eq!(
889            merged.body_medium.and_then(|style| style.color),
890            color(Color::new(0xfeedfeed))
891        );
892        assert_eq!(
893            merged.headline_small.and_then(|style| style.color),
894            color(Color::new(0xcafefeed))
895        );
896        assert_eq!(
897            merged.title_large.and_then(|style| style.color),
898            color(Color::new(0xdeadcafe))
899        );
900
901        let merged = only_headline_small_and_title_large.merge(None);
902        assert_eq!(merged, only_headline_small_and_title_large);
903    }
904
905    #[test]
906    fn apply_applies_custom_properties() {
907        // The `displayColor` is applied to [displayLarge], [displayMedium],
908        // [displaySmall], [headlineLarge], [headlineMedium], and [bodySmall]. The
909        // `bodyColor` is applied to the remaining text styles.
910        let display_color = Color::new(0x00000001);
911        let body_color = Color::new(0x00000002);
912        let font_family = "fontFamily";
913        let font_family_fallback: Vec<String> =
914            ["font", "family", "fallback"].map(String::from).to_vec();
915        let decoration_color = Color::new(0x00000003);
916        let decoration_style = waft_embedder::TextDecorationStyle::Dashed;
917        let decoration =
918            TextDecoration::combine(&[TextDecoration::UNDERLINE, TextDecoration::LINE_THROUGH]);
919
920        let typography = Typography::material2018().build();
921        let theme = typography
922            .black
923            .apply()
924            .font_family(font_family)
925            .font_family_fallback(font_family_fallback.clone())
926            .display_color(display_color)
927            .body_color(body_color)
928            .decoration(decoration)
929            .decoration_color(decoration_color)
930            .decoration_style(decoration_style)
931            .into_text_theme();
932
933        let display = color(display_color);
934        let body = color(body_color);
935        let colors = styles(&theme).map(|style| style.color.clone());
936        assert_eq!(
937            colors,
938            [
939                display.clone(),
940                display.clone(),
941                display.clone(),
942                display.clone(),
943                display.clone(),
944                body.clone(),
945                body.clone(),
946                body.clone(),
947                body.clone(),
948                body.clone(),
949                body.clone(),
950                display,
951                body.clone(),
952                body.clone(),
953                body,
954            ]
955        );
956
957        for style in styles(&theme) {
958            assert_eq!(style.font_family.as_deref(), Some(font_family));
959            assert_eq!(
960                style.font_family_fallback_list(),
961                Some(font_family_fallback.clone())
962            );
963            assert_eq!(style.decoration_color, color(decoration_color));
964            assert_eq!(style.decoration_style, Some(decoration_style));
965            assert_eq!(style.decoration, Some(decoration));
966        }
967    }
968
969    #[test]
970    fn apply_applies_package_font_family_and_font_family_fallback() {
971        let typography = Typography::material2018().build();
972        let theme = typography
973            .black
974            .apply()
975            .font_family("fontFamily")
976            .font_family_fallback(vec!["fallback".to_string()])
977            .package("package")
978            .into_text_theme();
979
980        for style in styles(&theme) {
981            assert_eq!(
982                style.font_family.as_deref(),
983                Some("packages/package/fontFamily")
984            );
985            assert_eq!(
986                style.font_family_fallback_list(),
987                Some(vec!["packages/package/fallback".to_string()])
988            );
989        }
990    }
991
992    #[test]
993    fn apply_leaves_null_styles_null() {
994        let body_color = Color::new(0x00000002);
995        let theme = TextTheme::new()
996            .body_medium(TextStyle::new().font_size(10.0))
997            .apply()
998            .body_color(body_color)
999            .display_color(body_color)
1000            .font_family("fontFamily")
1001            .into_text_theme();
1002
1003        assert_eq!(
1004            theme,
1005            TextTheme::new().body_medium(
1006                TextStyle::new()
1007                    .font_size(10.0)
1008                    .color(body_color)
1009                    .font_family("fontFamily")
1010            )
1011        );
1012    }
1013
1014    #[test]
1015    fn apply_applies_font_features_and_font_variations() {
1016        let font_features = vec![FontFeature::enable("smcp")];
1017        let font_variations = vec![FontVariation::new("wght", 400.0)];
1018        let typography = Typography::material2018().build();
1019        let theme = typography
1020            .black
1021            .apply()
1022            .font_features(font_features.clone())
1023            .font_variations(font_variations.clone())
1024            .into_text_theme();
1025
1026        for style in styles(&theme) {
1027            assert_eq!(style.font_features, Some(font_features.clone()));
1028            assert_eq!(style.font_variations, Some(font_variations.clone()));
1029        }
1030    }
1031
1032    #[test]
1033    fn apply_without_font_features_or_font_variations_preserves_the_originals() {
1034        let font_features = vec![FontFeature::enable("smcp")];
1035        let font_variations = vec![FontVariation::new("wght", 400.0)];
1036        let typography = Typography::material2018().build();
1037        let display_large = typography
1038            .black
1039            .display_large
1040            .as_ref()
1041            .expect("a display style")
1042            .copy_with()
1043            .font_features(font_features.clone())
1044            .font_variations(font_variations.clone());
1045        let base_theme = typography.black.copy_with().display_large(display_large);
1046        let theme = base_theme.apply().into_text_theme();
1047
1048        let display_large = theme.display_large.as_ref().expect("a display style");
1049        assert_eq!(display_large.font_features, Some(font_features));
1050        assert_eq!(display_large.font_variations, Some(font_variations));
1051        let display_medium = theme.display_medium.as_ref().expect("a display style");
1052        assert!(display_medium.font_features.is_none());
1053        assert!(display_medium.font_variations.is_none());
1054    }
1055
1056    #[test]
1057    fn apply_font_size_factor_and_font_size_delta() {
1058        let typography = Typography::material2018().build();
1059        let base_theme = Typography::english_like2018().merge(Some(&typography.black));
1060        let size_theme = base_theme
1061            .apply()
1062            .font_size_factor(2.0)
1063            .font_size_delta(5.0)
1064            .into_text_theme();
1065
1066        for (sized, base) in styles(&size_theme).into_iter().zip(styles(&base_theme)) {
1067            assert_eq!(
1068                sized.font_size,
1069                Some(base.font_size.expect("a size") * 2.0 + 5.0)
1070            );
1071        }
1072    }
1073
1074    #[test]
1075    fn apply_letter_spacing_factor_and_letter_spacing_delta() {
1076        let typography = Typography::material2018().build();
1077        let base_theme = Typography::english_like2018().merge(Some(&typography.black));
1078        let size_theme = base_theme
1079            .apply()
1080            .letter_spacing_factor(2.0)
1081            .letter_spacing_delta(5.0)
1082            .into_text_theme();
1083
1084        for (sized, base) in styles(&size_theme).into_iter().zip(styles(&base_theme)) {
1085            assert_eq!(
1086                sized.letter_spacing,
1087                Some(base.letter_spacing.expect("a letter spacing") * 2.0 + 5.0)
1088            );
1089        }
1090    }
1091
1092    #[test]
1093    fn apply_word_spacing_factor_and_word_spacing_delta() {
1094        let typography = Typography::material2018().build();
1095        let base_theme = Typography::english_like2018().merge(Some(&typography.black));
1096        let with_word_spacing = |style: &Option<TextStyle>| {
1097            style
1098                .as_ref()
1099                .expect("a style")
1100                .copy_with()
1101                .word_spacing(1.0)
1102        };
1103        let mut base_theme_with_word_spacing = base_theme.copy_with();
1104        for style in [
1105            &mut base_theme_with_word_spacing.display_large,
1106            &mut base_theme_with_word_spacing.display_medium,
1107            &mut base_theme_with_word_spacing.display_small,
1108            &mut base_theme_with_word_spacing.headline_large,
1109            &mut base_theme_with_word_spacing.headline_medium,
1110            &mut base_theme_with_word_spacing.headline_small,
1111            &mut base_theme_with_word_spacing.title_large,
1112            &mut base_theme_with_word_spacing.title_medium,
1113            &mut base_theme_with_word_spacing.title_small,
1114            &mut base_theme_with_word_spacing.body_large,
1115            &mut base_theme_with_word_spacing.body_medium,
1116            &mut base_theme_with_word_spacing.body_small,
1117            &mut base_theme_with_word_spacing.label_large,
1118            &mut base_theme_with_word_spacing.label_medium,
1119            &mut base_theme_with_word_spacing.label_small,
1120        ] {
1121            *style = Some(with_word_spacing(style));
1122        }
1123        let size_theme = base_theme_with_word_spacing
1124            .apply()
1125            .word_spacing_factor(2.0)
1126            .word_spacing_delta(5.0)
1127            .into_text_theme();
1128
1129        for (sized, base) in styles(&size_theme)
1130            .into_iter()
1131            .zip(styles(&base_theme_with_word_spacing))
1132        {
1133            assert_eq!(
1134                sized.word_spacing,
1135                Some(base.word_spacing.expect("a word spacing") * 2.0 + 5.0)
1136            );
1137        }
1138    }
1139
1140    #[test]
1141    fn apply_height_factor_and_height_delta() {
1142        let typography = Typography::material2021().build();
1143        let base_theme = Typography::english_like2021().merge(Some(&typography.black));
1144        let size_theme = base_theme
1145            .apply()
1146            .height_factor(2.0)
1147            .height_delta(5.0)
1148            .into_text_theme();
1149
1150        for (sized, base) in styles(&size_theme).into_iter().zip(styles(&base_theme)) {
1151            assert_eq!(
1152                sized.height,
1153                Some(base.height.expect("a height") * 2.0 + 5.0)
1154            );
1155        }
1156    }
1157
1158    #[test]
1159    fn lerp_with_one_parameter_null_lerps_each_style_with_null() {
1160        let theme = Typography::material2018().build().black;
1161        let lerped = TextTheme::lerp(Some(&theme), None, 0.25);
1162        for (lerped, style) in optional_styles(&lerped)
1163            .into_iter()
1164            .zip(optional_styles(&theme))
1165        {
1166            assert_eq!(*lerped, TextStyle::lerp(style.as_ref(), None, 0.25));
1167        }
1168
1169        let lerped = TextTheme::lerp(None, Some(&theme), 0.25);
1170        for (lerped, style) in optional_styles(&lerped)
1171            .into_iter()
1172            .zip(optional_styles(&theme))
1173        {
1174            assert_eq!(*lerped, TextStyle::lerp(None, style.as_ref(), 0.25));
1175        }
1176    }
1177
1178    #[test]
1179    fn lerp_with_null_parameters_is_empty() {
1180        let lerped = TextTheme::lerp(None, None, 0.25);
1181        for style in optional_styles(&lerped) {
1182            assert!(style.is_none());
1183        }
1184    }
1185
1186    #[test]
1187    fn text_theme_of_and_primary_of_are_the_ambient_theme_text_themes() {
1188        test_widgets(|tester| {
1189            let (theme, text_theme, primary_text_theme) = probe(
1190                tester,
1191                |app, child| {
1192                    let data = ThemeData::builder()
1193                        .text_theme(
1194                            TextTheme::new().display_large(
1195                                TextStyle::new()
1196                                    .color(Colors::BLUE.primary())
1197                                    .font_size(30.0),
1198                            ),
1199                        )
1200                        .primary_text_theme(
1201                            TextTheme::new().display_large(
1202                                TextStyle::new()
1203                                    .background_color(Colors::GREEN.primary())
1204                                    .font_style(FontStyle::Italic),
1205                            ),
1206                        )
1207                        .build(app);
1208                    Theme::new(data, child).into_widget()
1209                },
1210                |app, context| {
1211                    (
1212                        Theme::of(app, context),
1213                        TextTheme::of(app, context),
1214                        TextTheme::primary_of(app, context),
1215                    )
1216                },
1217            );
1218            assert_eq!(text_theme, theme.text_theme);
1219            assert_eq!(primary_text_theme, theme.primary_text_theme);
1220            assert_eq!(theme.brightness(), Brightness::Light);
1221        });
1222    }
1223}