Skip to main content

whisker_engine/
text.rs

1//! Plain-text lowering shared by the future Text element provider and tests.
2
3use std::{
4    collections::hash_map::DefaultHasher,
5    hash::{Hash, Hasher},
6};
7
8use whisker_protocol::{
9    FontFeature, FontOpticalSizing, FontTag, FontVariation, MeasureFontFamily, MeasureFontStyle,
10    MeasureLineHeight, MeasureTextAlignment, MeasureTextDirection, MeasureTextIndent,
11    MeasureTextOverflow, MeasureTextWordBreak, MeasureTextWrap, MeasurementPayload,
12    MeasurementSpec, PendingMeasurePolicy, TextContent, TextMeasurePayload, TextMeasureStyle,
13    TextPaint, TextShadow, TextStyleSnapshot,
14};
15use whisker_style::{
16    ComputedLineHeight, ComputedStyle, ComputedTextIndent, DirectionValue, FontFamilyValue,
17    FontOpticalSizingValue, FontStyleValue, TextAlignValue, TextDecorationLineValue,
18    TextDecorationStyleValue, TextOverflowValue, WhiteSpaceValue, WordBreakValue,
19};
20
21use crate::paint::lower_color;
22
23/// Plain UTF-8 text and element inputs not supplied by computed style.
24#[derive(Clone, Debug, PartialEq)]
25pub struct PlainTextInput {
26    /// UTF-8 text after application-level transformations.
27    pub text: String,
28    /// Optional BCP-47 locale hint.
29    pub locale: Option<String>,
30    /// Maximum visible line count.
31    pub max_lines: Option<u32>,
32    /// Layout behavior if the Host cannot answer synchronously.
33    pub pending_policy: PendingMeasurePolicy,
34}
35
36mod paragraph;
37pub use paragraph::{InlineAttachmentInput, ResolvedTextRun, lower_rich_text};
38
39impl PlainTextInput {
40    /// Creates ordinary wrapping text that blocks presentation until measured.
41    pub fn new(text: impl Into<String>) -> Self {
42        Self {
43            text: text.into(),
44            locale: None,
45            max_lines: None,
46            pending_policy: PendingMeasurePolicy::Block,
47        }
48    }
49}
50
51/// Measurement and presentation values produced from one plain-text input.
52#[derive(Clone, Debug, PartialEq)]
53pub struct LoweredPlainText {
54    content: TextContent,
55    measurement: MeasurementSpec,
56}
57
58impl LoweredPlainText {
59    /// Returns the final presentation before a prepared Host object is known.
60    pub const fn content(&self) -> &TextContent {
61        &self.content
62    }
63
64    /// Returns the intrinsic-measurement registration for the node.
65    pub const fn measurement(&self) -> &MeasurementSpec {
66        &self.measurement
67    }
68
69    pub(crate) fn into_parts(self) -> (TextContent, MeasurementSpec) {
70        (self.content, self.measurement)
71    }
72}
73
74/// Lowers computed inherited text style into the shared Host measurement model.
75pub fn lower_plain_text(input: &PlainTextInput, style: &ComputedStyle) -> LoweredPlainText {
76    let inherited = style.inherited_text();
77    let payload = TextMeasurePayload {
78        runs: Vec::new(),
79        attachments: Vec::new(),
80        text: input.text.clone(),
81        style: TextMeasureStyle {
82            font_families: vec![match inherited.font_family() {
83                FontFamilyValue::System => MeasureFontFamily::System,
84                FontFamilyValue::Named(name) => MeasureFontFamily::Named(name.clone()),
85            }],
86            font_size: inherited.font_size(),
87            font_weight: inherited.font_weight().get(),
88            font_style: match inherited.font_style() {
89                FontStyleValue::Normal => MeasureFontStyle::Normal,
90                FontStyleValue::Italic => MeasureFontStyle::Italic,
91                FontStyleValue::Oblique => MeasureFontStyle::Oblique,
92            },
93            line_height: match inherited.line_height() {
94                ComputedLineHeight::Normal => MeasureLineHeight::Normal,
95                ComputedLineHeight::LogicalPixels(value) => {
96                    MeasureLineHeight::LogicalPixels(value.get())
97                }
98            },
99            letter_spacing: inherited.letter_spacing(),
100            features: inherited
101                .font_features()
102                .iter()
103                .map(|feature| FontFeature {
104                    tag: FontTag::new(feature.tag.get()).expect("style tags are validated"),
105                    value: feature.value,
106                })
107                .collect(),
108            variations: inherited
109                .font_variations()
110                .iter()
111                .map(|variation| FontVariation {
112                    tag: FontTag::new(variation.tag.get()).expect("style tags are validated"),
113                    value: variation.value.get(),
114                })
115                .collect(),
116            optical_sizing: match inherited.font_optical_sizing() {
117                FontOpticalSizingValue::Auto => FontOpticalSizing::Auto,
118                FontOpticalSizingValue::None => FontOpticalSizing::None,
119            },
120        },
121        locale: input.locale.clone(),
122        direction: match style.layout().direction {
123            DirectionValue::Ltr => MeasureTextDirection::LeftToRight,
124            DirectionValue::Rtl => MeasureTextDirection::RightToLeft,
125        },
126        alignment: match inherited.text_align() {
127            TextAlignValue::Start => MeasureTextAlignment::Start,
128            TextAlignValue::End => MeasureTextAlignment::End,
129            TextAlignValue::Left => MeasureTextAlignment::Left,
130            TextAlignValue::Right => MeasureTextAlignment::Right,
131            TextAlignValue::Center => MeasureTextAlignment::Center,
132        },
133        indent: match style.text_indent() {
134            ComputedTextIndent::LogicalPixels(value) => MeasureTextIndent {
135                logical_pixels: value.get(),
136                percentage: 0.0,
137            },
138            ComputedTextIndent::Percentage(value) => MeasureTextIndent {
139                logical_pixels: 0.0,
140                percentage: value.get(),
141            },
142            ComputedTextIndent::LengthPercentage {
143                logical_pixels,
144                percentage,
145            } => MeasureTextIndent {
146                logical_pixels: logical_pixels.get(),
147                percentage: percentage.get(),
148            },
149        },
150        wrap: match style.white_space() {
151            WhiteSpaceValue::PreWrap => MeasureTextWrap::PreserveWhitespace,
152            WhiteSpaceValue::Normal => MeasureTextWrap::Wrap,
153            WhiteSpaceValue::NoWrap => MeasureTextWrap::NoWrap,
154        },
155        word_break: match style.word_break() {
156            WordBreakValue::Normal => MeasureTextWordBreak::Normal,
157            WordBreakValue::BreakAll => MeasureTextWordBreak::BreakAll,
158            WordBreakValue::KeepAll => MeasureTextWordBreak::KeepAll,
159        },
160        max_lines: input.max_lines,
161        overflow: match style.text_overflow() {
162            TextOverflowValue::Clip => MeasureTextOverflow::Clip,
163            TextOverflowValue::Ellipsis => MeasureTextOverflow::Ellipsis,
164        },
165    };
166    let measurement = MeasurementSpec {
167        content_hash: content_hash(&input.text),
168        style_hash: metric_style_hash(input, style),
169        payload: MeasurementPayload::Text(payload.clone()),
170        pending_policy: input.pending_policy,
171    };
172    LoweredPlainText {
173        content: TextContent {
174            paragraph: None,
175            runs: Vec::new(),
176            payload,
177            paint: TextPaint {
178                foreground: lower_color(inherited.color()),
179                decoration: whisker_protocol::TextDecoration {
180                    lines: whisker_protocol::TextDecorationLines {
181                        underline: matches!(
182                            inherited.text_decoration().line(),
183                            TextDecorationLineValue::Underline
184                        ),
185                        overline: false,
186                        line_through: matches!(
187                            inherited.text_decoration().line(),
188                            TextDecorationLineValue::LineThrough
189                        ),
190                    },
191                    color: lower_color(inherited.text_decoration().color()),
192                    style: match inherited.text_decoration().style() {
193                        TextDecorationStyleValue::Solid => {
194                            whisker_protocol::TextDecorationStyle::Solid
195                        }
196                        TextDecorationStyleValue::Double => {
197                            whisker_protocol::TextDecorationStyle::Double
198                        }
199                        TextDecorationStyleValue::Dotted => {
200                            whisker_protocol::TextDecorationStyle::Dotted
201                        }
202                        TextDecorationStyleValue::Dashed => {
203                            whisker_protocol::TextDecorationStyle::Dashed
204                        }
205                        TextDecorationStyleValue::Wavy => {
206                            whisker_protocol::TextDecorationStyle::Wavy
207                        }
208                    },
209                    thickness: whisker_protocol::TextDecorationThickness::Auto,
210                },
211                shadows: inherited
212                    .text_shadow()
213                    .into_iter()
214                    .map(|shadow| TextShadow {
215                        offset_x: shadow.offset_x(),
216                        offset_y: shadow.offset_y(),
217                        blur_radius: shadow.blur_radius(),
218                        color: lower_color(shadow.color()),
219                    })
220                    .collect(),
221            },
222            prepared_content: None,
223        },
224        measurement,
225    }
226}
227
228/// Lowers inherited text values for a native text-capable element without
229/// creating plain-text content or a measurement registration.
230pub fn lower_text_style(style: &ComputedStyle) -> TextStyleSnapshot {
231    TextStyleSnapshot::from(lower_plain_text(&PlainTextInput::new(""), style).content())
232}
233
234fn content_hash(text: &str) -> u64 {
235    let mut hasher = DefaultHasher::new();
236    text.hash(&mut hasher);
237    hasher.finish()
238}
239
240fn metric_style_hash(input: &PlainTextInput, style: &ComputedStyle) -> u64 {
241    let mut hasher = DefaultHasher::new();
242    let inherited = style.inherited_text();
243    hash_font_metrics(inherited, &mut hasher);
244    inherited.line_height().hash(&mut hasher);
245    inherited.text_align().hash(&mut hasher);
246    style.text_indent().hash(&mut hasher);
247    input.locale.hash(&mut hasher);
248    style.layout().direction.hash(&mut hasher);
249    style.white_space().hash(&mut hasher);
250    style.word_break().hash(&mut hasher);
251    input.max_lines.hash(&mut hasher);
252    style.text_overflow().hash(&mut hasher);
253    hasher.finish()
254}
255
256fn hash_font_metrics(inherited: &whisker_style::InheritedStyle, hasher: &mut impl Hasher) {
257    inherited.font_family().hash(hasher);
258    inherited.font_features().hash(hasher);
259    inherited.font_variations().hash(hasher);
260    inherited.font_optical_sizing().hash(hasher);
261    inherited.font_size().to_bits().hash(hasher);
262    inherited.font_weight().hash(hasher);
263    inherited.font_style().hash(hasher);
264    inherited.letter_spacing().to_bits().hash(hasher);
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use whisker_protocol::PaintColor;
271    use whisker_style::{
272        CalcExpression, ColorValue, FontFeatureValue, FontOpticalSizingValue, FontVariationValue,
273        FontWeightValue, LengthPercentageValue, LengthUnit, LengthValue, LineHeightValue,
274        OpenTypeTagValue, SpecifiedStyle, StyleDeclaration, StyleEnvironment, StyleNumber,
275        StyleProperty, StyleValue, TextDecorationValue, TextShadowValue, resolve_style,
276    };
277
278    fn resolved(declarations: Vec<StyleDeclaration>) -> whisker_style::ResolvedNodeStyle {
279        let specified =
280            declarations
281                .into_iter()
282                .fold(SpecifiedStyle::new(), |style, declaration| {
283                    let (property, value) = declaration.into_parts();
284                    style.push(property, value)
285                });
286        resolve_style(&specified, None, StyleEnvironment::default()).expect("valid text style")
287    }
288
289    #[test]
290    fn defaults_lower_to_plain_text_measurement_and_presentation() {
291        let style = resolved(Vec::new());
292        let input = PlainTextInput::new("hello");
293        let lowered = lower_plain_text(&input, style.computed());
294
295        assert_eq!(lowered.content().payload.text, "hello");
296        assert_eq!(
297            lowered.content().payload.style.font_families,
298            vec![MeasureFontFamily::System]
299        );
300        assert_eq!(lowered.content().payload.style.font_size, 14.0);
301        assert_eq!(lowered.content().prepared_content, None);
302        assert_eq!(
303            lowered.measurement().pending_policy,
304            PendingMeasurePolicy::Block
305        );
306        assert_eq!(
307            lowered.measurement().payload,
308            MeasurementPayload::Text(lowered.content().payload.clone())
309        );
310        assert_eq!(
311            lower_text_style(style.computed()),
312            TextStyleSnapshot::from(lowered.content())
313        );
314
315        let same = lower_plain_text(&input, style.computed());
316        assert_eq!(lowered, same);
317        let changed = lower_plain_text(&PlainTextInput::new("different"), style.computed());
318        assert_ne!(
319            lowered.measurement().content_hash,
320            changed.measurement().content_hash
321        );
322    }
323
324    #[test]
325    fn resolved_metric_variants_and_options_reach_the_host_payload() {
326        let style = resolved(vec![
327            StyleDeclaration::new(
328                StyleProperty::FontFamily,
329                StyleValue::FontFamily(FontFamilyValue::Named("Inter".into())),
330            ),
331            StyleDeclaration::new(
332                StyleProperty::FontSize,
333                StyleValue::LengthPercentage(LengthPercentageValue::Length(
334                    LengthValue::Dimension {
335                        value: StyleNumber::new(18.0),
336                        unit: LengthUnit::Px,
337                    },
338                )),
339            ),
340            StyleDeclaration::new(
341                StyleProperty::FontWeight,
342                StyleValue::FontWeight(FontWeightValue::BOLD),
343            ),
344            StyleDeclaration::new(
345                StyleProperty::FontStyle,
346                StyleValue::FontStyle(FontStyleValue::Italic),
347            ),
348            StyleDeclaration::new(
349                StyleProperty::LineHeight,
350                StyleValue::LineHeight(LineHeightValue::Number(StyleNumber::new(1.5))),
351            ),
352            StyleDeclaration::new(
353                StyleProperty::LetterSpacing,
354                StyleValue::Length(LengthValue::Dimension {
355                    value: StyleNumber::new(1.0),
356                    unit: LengthUnit::Px,
357                }),
358            ),
359            StyleDeclaration::new(
360                StyleProperty::WhiteSpace,
361                StyleValue::WhiteSpace(WhiteSpaceValue::NoWrap),
362            ),
363            StyleDeclaration::new(
364                StyleProperty::TextOverflow,
365                StyleValue::TextOverflow(TextOverflowValue::Ellipsis),
366            ),
367            StyleDeclaration::new(
368                StyleProperty::Direction,
369                StyleValue::Direction(DirectionValue::Rtl),
370            ),
371        ]);
372        let input = PlainTextInput {
373            text: "مرحبا".into(),
374            locale: Some("ar".into()),
375            max_lines: Some(1),
376            pending_policy: PendingMeasurePolicy::RetainPrevious,
377        };
378        let lowered = lower_plain_text(&input, style.computed());
379        let payload = &lowered.content().payload;
380
381        assert_eq!(
382            payload.style.font_families,
383            vec![MeasureFontFamily::Named("Inter".into())]
384        );
385        assert_eq!(payload.style.font_size, 18.0);
386        assert_eq!(payload.style.font_weight, 700);
387        assert_eq!(payload.style.font_style, MeasureFontStyle::Italic);
388        assert_eq!(
389            payload.style.line_height,
390            MeasureLineHeight::LogicalPixels(27.0)
391        );
392        assert_eq!(payload.style.letter_spacing, 1.0);
393        assert_eq!(payload.locale.as_deref(), Some("ar"));
394        assert_eq!(payload.direction, MeasureTextDirection::RightToLeft);
395        assert_eq!(payload.wrap, MeasureTextWrap::NoWrap);
396        assert_eq!(payload.word_break, MeasureTextWordBreak::Normal);
397        assert_eq!(payload.max_lines, Some(1));
398        assert_eq!(payload.overflow, MeasureTextOverflow::Ellipsis);
399    }
400
401    #[test]
402    fn extended_font_settings_reach_measurement_presentation_and_metric_key() {
403        let tag = |value| OpenTypeTagValue::new(value).unwrap();
404        let style = resolved(vec![
405            StyleDeclaration::new(
406                StyleProperty::FontFeatureSettings,
407                StyleValue::FontFeatures(vec![FontFeatureValue {
408                    tag: tag(*b"kern"),
409                    value: 0,
410                }]),
411            ),
412            StyleDeclaration::new(
413                StyleProperty::FontVariationSettings,
414                StyleValue::FontVariations(vec![FontVariationValue {
415                    tag: tag(*b"wght"),
416                    value: StyleNumber::new(650.0),
417                }]),
418            ),
419            StyleDeclaration::new(
420                StyleProperty::FontOpticalSizing,
421                StyleValue::FontOpticalSizing(FontOpticalSizingValue::Auto),
422            ),
423        ]);
424        let input = PlainTextInput::new("typography");
425        let lowered = lower_plain_text(&input, style.computed());
426        assert_eq!(
427            lowered.content().payload.style.features,
428            [FontFeature {
429                tag: FontTag::new(*b"kern").unwrap(),
430                value: 0,
431            }]
432        );
433        assert_eq!(
434            lowered.content().payload.style.variations,
435            [FontVariation {
436                tag: FontTag::new(*b"wght").unwrap(),
437                value: 650.0,
438            }]
439        );
440        assert_eq!(
441            lowered.content().payload.style.optical_sizing,
442            FontOpticalSizing::Auto
443        );
444        assert_eq!(
445            lowered.measurement().payload,
446            MeasurementPayload::Text(lowered.content().payload.clone())
447        );
448        let initial = lower_plain_text(&input, resolved(Vec::new()).computed());
449        assert_ne!(
450            lowered.measurement().style_hash,
451            initial.measurement().style_hash
452        );
453    }
454
455    #[test]
456    fn every_supported_text_alignment_reaches_the_host_payload_and_metric_key() {
457        for (value, expected) in [
458            (TextAlignValue::Start, MeasureTextAlignment::Start),
459            (TextAlignValue::End, MeasureTextAlignment::End),
460            (TextAlignValue::Left, MeasureTextAlignment::Left),
461            (TextAlignValue::Right, MeasureTextAlignment::Right),
462            (TextAlignValue::Center, MeasureTextAlignment::Center),
463        ] {
464            let style = resolved(vec![StyleDeclaration::new(
465                StyleProperty::TextAlign,
466                StyleValue::TextAlign(value),
467            )]);
468            let lowered = lower_plain_text(&PlainTextInput::new("alignment"), style.computed());
469            assert_eq!(lowered.content().payload.alignment, expected);
470            if value != TextAlignValue::Start {
471                let initial = lower_plain_text(
472                    &PlainTextInput::new("alignment"),
473                    resolved(Vec::new()).computed(),
474                );
475                assert_ne!(
476                    lowered.measurement().style_hash,
477                    initial.measurement().style_hash
478                );
479            }
480        }
481    }
482
483    #[test]
484    fn every_supported_word_break_reaches_the_host_payload_and_metric_key() {
485        for (value, expected) in [
486            (WordBreakValue::Normal, MeasureTextWordBreak::Normal),
487            (WordBreakValue::BreakAll, MeasureTextWordBreak::BreakAll),
488            (WordBreakValue::KeepAll, MeasureTextWordBreak::KeepAll),
489        ] {
490            let style = resolved(vec![StyleDeclaration::new(
491                StyleProperty::WordBreak,
492                StyleValue::WordBreak(value),
493            )]);
494            let lowered = lower_plain_text(&PlainTextInput::new("breaking"), style.computed());
495            assert_eq!(lowered.content().payload.word_break, expected);
496            if value != WordBreakValue::Normal {
497                let initial = lower_plain_text(
498                    &PlainTextInput::new("breaking"),
499                    resolved(Vec::new()).computed(),
500                );
501                assert_ne!(
502                    lowered.measurement().style_hash,
503                    initial.measurement().style_hash
504                );
505            }
506        }
507    }
508
509    #[test]
510    fn text_indent_reaches_the_host_payload_and_metric_key() {
511        let input = PlainTextInput::new("indent");
512        let initial = resolved(Vec::new());
513        let initial = lower_plain_text(&input, initial.computed());
514        let length = resolved(vec![StyleDeclaration::new(
515            StyleProperty::TextIndent,
516            StyleValue::LengthPercentage(LengthPercentageValue::Length(LengthValue::Dimension {
517                value: StyleNumber::new(12.0),
518                unit: LengthUnit::Px,
519            })),
520        )]);
521        let length = lower_plain_text(&input, length.computed());
522        assert_eq!(length.content().payload.indent.logical_pixels, 12.0);
523        assert_eq!(length.content().payload.indent.percentage, 0.0);
524        assert_ne!(
525            length.measurement().style_hash,
526            initial.measurement().style_hash
527        );
528
529        let percentage = resolved(vec![StyleDeclaration::new(
530            StyleProperty::TextIndent,
531            StyleValue::LengthPercentage(LengthPercentageValue::Percentage(StyleNumber::new(15.0))),
532        )]);
533        let percentage = lower_plain_text(&input, percentage.computed());
534        assert_eq!(percentage.content().payload.indent.logical_pixels, 0.0);
535        assert_eq!(percentage.content().payload.indent.percentage, 15.0);
536
537        let calculated = resolved(vec![StyleDeclaration::new(
538            StyleProperty::TextIndent,
539            StyleValue::LengthPercentage(LengthPercentageValue::Calc(Box::new(
540                CalcExpression::Add(
541                    Box::new(CalcExpression::Value(Box::new(
542                        LengthPercentageValue::Length(LengthValue::Dimension {
543                            value: StyleNumber::new(4.0),
544                            unit: LengthUnit::Px,
545                        }),
546                    ))),
547                    Box::new(CalcExpression::Value(Box::new(
548                        LengthPercentageValue::Percentage(StyleNumber::new(10.0)),
549                    ))),
550                ),
551            ))),
552        )]);
553        let calculated = lower_plain_text(&input, calculated.computed());
554        assert_eq!(calculated.content().payload.indent.logical_pixels, 4.0);
555        assert_eq!(calculated.content().payload.indent.percentage, 10.0);
556    }
557
558    #[test]
559    fn oblique_and_left_to_right_variants_are_lowered() {
560        let style = resolved(vec![
561            StyleDeclaration::new(
562                StyleProperty::FontStyle,
563                StyleValue::FontStyle(FontStyleValue::Oblique),
564            ),
565            StyleDeclaration::new(
566                StyleProperty::Direction,
567                StyleValue::Direction(DirectionValue::Ltr),
568            ),
569        ]);
570        let input = PlainTextInput::new("variants");
571        let lowered = lower_plain_text(&input, style.computed());
572
573        assert_eq!(
574            lowered.content().payload.style.font_style,
575            MeasureFontStyle::Oblique
576        );
577        assert_eq!(
578            lowered.content().payload.direction,
579            MeasureTextDirection::LeftToRight
580        );
581    }
582
583    #[test]
584    fn named_and_hsl_text_paint_are_lowered_without_affecting_metrics() {
585        let input = PlainTextInput::new("paint");
586        let named = resolved(vec![StyleDeclaration::new(
587            StyleProperty::Color,
588            StyleValue::Color(ColorValue::Named("rebeccapurple".into())),
589        )]);
590        let named = lower_plain_text(&input, named.computed());
591        assert_eq!(
592            named.content().paint.foreground,
593            PaintColor::Srgba {
594                red: 102,
595                green: 51,
596                blue: 153,
597                alpha: 1.0,
598            }
599        );
600
601        let hsla = resolved(vec![StyleDeclaration::new(
602            StyleProperty::Color,
603            StyleValue::Color(ColorValue::Hsla {
604                hue_degrees: StyleNumber::new(210.0),
605                saturation: StyleNumber::new(80.0),
606                lightness: StyleNumber::new(40.0),
607                alpha: StyleNumber::new(0.5),
608            }),
609        )]);
610        let hsla = lower_plain_text(&input, hsla.computed());
611        assert_eq!(
612            hsla.content().paint.foreground,
613            PaintColor::Hsla {
614                hue_degrees: 210.0,
615                saturation: 80.0,
616                lightness: 40.0,
617                alpha: 0.5,
618            }
619        );
620        assert_eq!(named.measurement(), hsla.measurement());
621    }
622
623    #[test]
624    fn inherited_single_shadow_lowers_to_paint_without_changing_measurement() {
625        let input = PlainTextInput::new("shadow");
626        let plain = resolved(Vec::new());
627        let shadowed = resolved(vec![StyleDeclaration::new(
628            StyleProperty::TextShadow,
629            StyleValue::TextShadow(TextShadowValue::Shadow {
630                offset_x: LengthValue::Dimension {
631                    value: StyleNumber::new(1.0),
632                    unit: LengthUnit::Em,
633                }
634                .into(),
635                offset_y: LengthValue::Dimension {
636                    value: StyleNumber::new(2.0),
637                    unit: LengthUnit::Px,
638                }
639                .into(),
640                blur_radius: LengthValue::Dimension {
641                    value: StyleNumber::new(3.0),
642                    unit: LengthUnit::Px,
643                }
644                .into(),
645                color: ColorValue::Named("red".into()).into(),
646            }),
647        )]);
648        let plain = lower_plain_text(&input, plain.computed());
649        let shadowed = lower_plain_text(&input, shadowed.computed());
650        assert_eq!(plain.measurement(), shadowed.measurement());
651        assert_eq!(
652            shadowed.content().paint.shadows,
653            vec![TextShadow {
654                offset_x: 14.0,
655                offset_y: 2.0,
656                blur_radius: 3.0,
657                color: PaintColor::Srgba {
658                    red: 255,
659                    green: 0,
660                    blue: 0,
661                    alpha: 1.0,
662                },
663            }]
664        );
665    }
666
667    #[test]
668    fn text_decoration_lowers_to_paint_without_changing_measurement() {
669        let input = PlainTextInput::new("decoration");
670        let plain = lower_plain_text(&input, resolved(Vec::new()).computed());
671        let decorated = resolved(vec![StyleDeclaration::new(
672            StyleProperty::TextDecoration,
673            StyleValue::TextDecoration(TextDecorationValue {
674                line: TextDecorationLineValue::LineThrough,
675                style: TextDecorationStyleValue::Wavy,
676                color: Some(ColorValue::Named("red".into()).into()),
677            }),
678        )]);
679        let decorated = lower_plain_text(&input, decorated.computed());
680        assert_eq!(plain.measurement(), decorated.measurement());
681        assert!(decorated.content().paint.decoration.lines.line_through);
682        assert!(!decorated.content().paint.decoration.lines.underline);
683        assert_eq!(
684            decorated.content().paint.decoration.style,
685            whisker_protocol::TextDecorationStyle::Wavy
686        );
687        assert_eq!(
688            decorated.content().paint.decoration.color,
689            PaintColor::Srgba {
690                red: 255,
691                green: 0,
692                blue: 0,
693                alpha: 1.0,
694            }
695        );
696        for (style, expected) in [
697            (
698                TextDecorationStyleValue::Double,
699                whisker_protocol::TextDecorationStyle::Double,
700            ),
701            (
702                TextDecorationStyleValue::Dotted,
703                whisker_protocol::TextDecorationStyle::Dotted,
704            ),
705            (
706                TextDecorationStyleValue::Dashed,
707                whisker_protocol::TextDecorationStyle::Dashed,
708            ),
709        ] {
710            let resolved = resolved(vec![StyleDeclaration::new(
711                StyleProperty::TextDecoration,
712                StyleValue::TextDecoration(TextDecorationValue {
713                    line: TextDecorationLineValue::Underline,
714                    style,
715                    color: None,
716                }),
717            )]);
718            assert_eq!(
719                lower_plain_text(&input, resolved.computed())
720                    .content()
721                    .paint
722                    .decoration
723                    .style,
724                expected
725            );
726        }
727    }
728}