Skip to main content

gpui/
style.rs

1use std::{
2    hash::{Hash, Hasher},
3    iter, mem,
4    ops::Range,
5};
6
7use crate::{
8    AbsoluteLength, App, Background, BackgroundTag, BorderStyle, Bounds, ContentMask, Corners,
9    CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges, EdgesRefinement, Font,
10    FontFallbacks, FontFeatures, FontStyle, FontWeight, GridLocation, Hsla, Length, Pixels, Point,
11    PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, Window, black, phi,
12    point, px, quad, rems, size,
13};
14use collections::HashSet;
15use refineable::Refineable;
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19/// Use this struct for interfacing with the 'debug_below' styling from your own elements.
20/// If a parent element has this style set on it, then this struct will be set as a global in
21/// GPUI.
22#[cfg(debug_assertions)]
23pub struct DebugBelow;
24
25#[cfg(debug_assertions)]
26impl crate::Global for DebugBelow {}
27
28/// How to fit the image into the bounds of the element.
29pub enum ObjectFit {
30    /// The image will be stretched to fill the bounds of the element.
31    Fill,
32    /// The image will be scaled to fit within the bounds of the element.
33    Contain,
34    /// The image will be scaled to cover the bounds of the element.
35    Cover,
36    /// The image will be scaled down to fit within the bounds of the element.
37    ScaleDown,
38    /// The image will maintain its original size.
39    None,
40}
41
42impl ObjectFit {
43    /// Get the bounds of the image within the given bounds.
44    pub fn get_bounds(
45        &self,
46        bounds: Bounds<Pixels>,
47        image_size: Size<DevicePixels>,
48    ) -> Bounds<Pixels> {
49        let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
50        let image_ratio = image_size.width / image_size.height;
51        let bounds_ratio = bounds.size.width / bounds.size.height;
52
53        match self {
54            ObjectFit::Fill => bounds,
55            ObjectFit::Contain => {
56                let new_size = if bounds_ratio > image_ratio {
57                    size(
58                        image_size.width * (bounds.size.height / image_size.height),
59                        bounds.size.height,
60                    )
61                } else {
62                    size(
63                        bounds.size.width,
64                        image_size.height * (bounds.size.width / image_size.width),
65                    )
66                };
67
68                Bounds {
69                    origin: point(
70                        bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
71                        bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
72                    ),
73                    size: new_size,
74                }
75            }
76            ObjectFit::ScaleDown => {
77                // Check if the image is larger than the bounds in either dimension.
78                if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
79                    // If the image is larger, use the same logic as Contain to scale it down.
80                    let new_size = if bounds_ratio > image_ratio {
81                        size(
82                            image_size.width * (bounds.size.height / image_size.height),
83                            bounds.size.height,
84                        )
85                    } else {
86                        size(
87                            bounds.size.width,
88                            image_size.height * (bounds.size.width / image_size.width),
89                        )
90                    };
91
92                    Bounds {
93                        origin: point(
94                            bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
95                            bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
96                        ),
97                        size: new_size,
98                    }
99                } else {
100                    // If the image is smaller than or equal to the container, display it at its original size,
101                    // centered within the container.
102                    let original_size = size(image_size.width, image_size.height);
103                    Bounds {
104                        origin: point(
105                            bounds.origin.x + (bounds.size.width - original_size.width) / 2.0,
106                            bounds.origin.y + (bounds.size.height - original_size.height) / 2.0,
107                        ),
108                        size: original_size,
109                    }
110                }
111            }
112            ObjectFit::Cover => {
113                let new_size = if bounds_ratio > image_ratio {
114                    size(
115                        bounds.size.width,
116                        image_size.height * (bounds.size.width / image_size.width),
117                    )
118                } else {
119                    size(
120                        image_size.width * (bounds.size.height / image_size.height),
121                        bounds.size.height,
122                    )
123                };
124
125                Bounds {
126                    origin: point(
127                        bounds.origin.x + (bounds.size.width - new_size.width) / 2.0,
128                        bounds.origin.y + (bounds.size.height - new_size.height) / 2.0,
129                    ),
130                    size: new_size,
131                }
132            }
133            ObjectFit::None => Bounds {
134                origin: bounds.origin,
135                size: image_size,
136            },
137        }
138    }
139}
140
141/// The minimum size of a column or row in a grid layout
142#[derive(
143    Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, JsonSchema, Serialize, Deserialize,
144)]
145pub enum GridTemplateMinSize {
146    /// The column or row size may be 0
147    #[default]
148    Zero,
149    /// The column or row size can be determined by the min content
150    MinContent,
151    /// The column or row size can be determined by the max content
152    MaxContent,
153}
154
155/// A simplified representation of the grid-template-* value
156#[derive(
157    Copy,
158    Clone,
159    Refineable,
160    PartialEq,
161    Eq,
162    PartialOrd,
163    Ord,
164    Debug,
165    Default,
166    JsonSchema,
167    Serialize,
168    Deserialize,
169)]
170pub struct GridTemplate {
171    /// How this template directive should be repeated
172    pub repeat: u16,
173    /// The minimum size in the repeat(<>, minmax(_, 1fr)) equation
174    pub min_size: GridTemplateMinSize,
175}
176
177/// The CSS styling that can be applied to an element via the `Styled` trait
178#[derive(Clone, Refineable, Debug)]
179#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
180pub struct Style {
181    /// What layout strategy should be used?
182    pub display: Display,
183
184    /// Should the element be painted on screen?
185    pub visibility: Visibility,
186
187    // Overflow properties
188    /// How children overflowing their container should affect layout
189    #[refineable]
190    pub overflow: Point<Overflow>,
191    /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
192    pub scrollbar_width: AbsoluteLength,
193    /// Whether both x and y axis should be scrollable at the same time.
194    pub allow_concurrent_scroll: bool,
195    /// Whether scrolling should be restricted to the input gesture's axis.
196    ///
197    /// Pixel-based scroll gestures are locked to their initially dominant axis. The lock may be
198    /// released when the gesture changes direction strongly. Touch phases delimit gestures when
199    /// available, with a timeout fallback for platforms that only emit moved events.
200    ///
201    /// This also prevents input from being remapped to another axis. For example, horizontal input
202    /// will not scroll a container that only has vertical overflow enabled. Mouse wheel platforms
203    /// typically report ordinary wheel input on the Y axis and Shift-modified input on the X axis.
204    ///
205    /// ## Motivation
206    ///
207    /// On the web when scrolling with the mouse wheel, scrolling up and down will always scroll the Y axis, even when
208    /// the mouse is over a horizontally-scrollable element.
209    ///
210    /// The only way to scroll horizontally is to hold down `Shift` while scrolling, which then changes the scroll axis
211    /// to the X axis.
212    ///
213    /// Currently, GPUI operates differently from the web in that it will scroll an element in either the X or Y axis
214    /// when scrolling with just the mouse wheel. This causes problems when scrolling in a vertical list that contains
215    /// horizontally-scrollable elements, as when you get to the horizontally-scrollable elements the scroll will be
216    /// hijacked.
217    ///
218    /// Ideally we would match the web's behavior and not have a need for this, but right now we're adding this opt-in
219    /// style property to limit the potential blast radius.
220    pub restrict_scroll_to_axis: bool,
221
222    // Position properties
223    /// What should the `position` value of this struct use as a base offset?
224    pub position: Position,
225    /// How should the position of this element be tweaked relative to the layout defined?
226    #[refineable]
227    pub inset: Edges<Length>,
228
229    // Size properties
230    /// Sets the initial size of the item
231    #[refineable]
232    pub size: Size<Length>,
233    /// Controls the minimum size of the item
234    #[refineable]
235    pub min_size: Size<Length>,
236    /// Controls the maximum size of the item
237    #[refineable]
238    pub max_size: Size<Length>,
239    /// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
240    pub aspect_ratio: Option<f32>,
241
242    // Spacing Properties
243    /// How large should the margin be on each side?
244    #[refineable]
245    pub margin: Edges<Length>,
246    /// How large should the padding be on each side?
247    #[refineable]
248    pub padding: Edges<DefiniteLength>,
249    /// How large should the border be on each side?
250    #[refineable]
251    pub border_widths: Edges<AbsoluteLength>,
252
253    // Alignment properties
254    /// How this node's children aligned in the cross/block axis?
255    pub align_items: Option<AlignItems>,
256    /// How this node should be aligned in the cross/block axis. Falls back to the parents [`AlignItems`] if not set
257    pub align_self: Option<AlignSelf>,
258    /// How should content contained within this item be aligned in the cross/block axis
259    pub align_content: Option<AlignContent>,
260    /// How should contained within this item be aligned in the main/inline axis
261    pub justify_content: Option<JustifyContent>,
262    /// How large should the gaps between items in a flex container be?
263    #[refineable]
264    pub gap: Size<DefiniteLength>,
265
266    // Flexbox properties
267    /// Which direction does the main axis flow in?
268    pub flex_direction: FlexDirection,
269    /// Should elements wrap, or stay in a single line?
270    pub flex_wrap: FlexWrap,
271    /// Sets the initial main axis size of the item
272    pub flex_basis: Length,
273    /// The relative rate at which this item grows when it is expanding to fill space, 0.0 is the default value, and this value must be positive.
274    pub flex_grow: f32,
275    /// The relative rate at which this item shrinks when it is contracting to fit into space, 1.0 is the default value, and this value must be positive.
276    pub flex_shrink: f32,
277
278    /// The fill color of this element
279    pub background: Option<Fill>,
280
281    /// The border color of this element
282    pub border_color: Option<Hsla>,
283
284    /// The border style of this element
285    pub border_style: BorderStyle,
286
287    /// The radius of the corners of this element
288    #[refineable]
289    pub corner_radii: Corners<AbsoluteLength>,
290
291    /// Box shadow of the element
292    pub box_shadow: Vec<BoxShadow>,
293
294    /// The text style of this element
295    #[refineable]
296    pub text: TextStyleRefinement,
297
298    /// The mouse cursor style shown when the mouse pointer is over an element.
299    pub mouse_cursor: Option<CursorStyle>,
300
301    /// The opacity of this element
302    pub opacity: Option<f32>,
303
304    /// The grid columns of this element
305    /// Roughly equivalent to the Tailwind `grid-cols-<number>`
306    pub grid_cols: Option<GridTemplate>,
307
308    /// The row span of this element
309    /// Equivalent to the Tailwind `grid-rows-<number>`
310    pub grid_rows: Option<GridTemplate>,
311
312    /// The grid location of this element
313    pub grid_location: Option<GridLocation>,
314
315    /// Whether to draw a red debugging outline around this element
316    #[cfg(debug_assertions)]
317    pub debug: bool,
318
319    /// Whether to draw a red debugging outline around this element and all of its conforming children
320    #[cfg(debug_assertions)]
321    pub debug_below: bool,
322}
323
324impl Styled for StyleRefinement {
325    fn style(&mut self) -> &mut StyleRefinement {
326        self
327    }
328}
329
330impl StyleRefinement {
331    /// The grid location of this element
332    pub fn grid_location_mut(&mut self) -> &mut GridLocation {
333        self.grid_location.get_or_insert_default()
334    }
335}
336
337/// The value of the visibility property, similar to the CSS property `visibility`
338#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
339pub enum Visibility {
340    /// The element should be drawn as normal.
341    #[default]
342    Visible,
343    /// The element should not be drawn, but should still take up space in the layout.
344    Hidden,
345}
346
347/// The possible values of the box-shadow property
348#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
349pub struct BoxShadow {
350    /// What color should the shadow have?
351    pub color: Hsla,
352    /// How should it be offset from its element?
353    pub offset: Point<Pixels>,
354    /// How much should the shadow be blurred?
355    pub blur_radius: Pixels,
356    /// How much should the shadow spread?
357    pub spread_radius: Pixels,
358    /// Whether this is an inset shadow (drawn inside the element's bounds).
359    pub inset: bool,
360}
361
362impl BoxShadow {
363    /// Creates a new [`BoxShadow`] with the given offset and color, matching the order
364    /// of the CSS `box-shadow` property. Use the builder methods to set blur radius,
365    /// spread radius, and inset.
366    pub fn new(offset_x: Pixels, offset_y: Pixels, color: Hsla) -> Self {
367        Self {
368            color,
369            offset: point(offset_x, offset_y),
370            blur_radius: px(0.),
371            spread_radius: px(0.),
372            inset: false,
373        }
374    }
375
376    /// Sets the shadow blur radius.
377    pub fn blur_radius(mut self, blur_radius: Pixels) -> Self {
378        self.blur_radius = blur_radius;
379        self
380    }
381
382    /// Sets the shadow spread radius.
383    pub fn spread_radius(mut self, spread_radius: Pixels) -> Self {
384        self.spread_radius = spread_radius;
385        self
386    }
387
388    /// Marks the shadow as inset (drawn inside the element's bounds).
389    pub fn inset(mut self) -> Self {
390        self.inset = true;
391        self
392    }
393}
394
395/// How to handle whitespace in text
396#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
397pub enum WhiteSpace {
398    /// Normal line wrapping when text overflows the width of the element
399    #[default]
400    Normal,
401    /// No line wrapping, text will overflow the width of the element
402    Nowrap,
403}
404
405/// How to truncate text that overflows the width of the element
406#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
407pub enum TextOverflow {
408    /// Truncate the text at the end when it doesn't fit, and represent this truncation by
409    /// displaying the provided string (e.g., "very long te…").
410    Truncate(SharedString),
411    /// Truncate the text at the start when it doesn't fit, and represent this truncation by
412    /// displaying the provided string at the beginning (e.g., "…ong text here").
413    /// Typically more adequate for file paths where the end is more important than the beginning.
414    TruncateStart(SharedString),
415    /// Truncate the text in the middle when it doesn't fit, preserving both the start and end
416    /// of the string (e.g., "long fi…name.rs"). Useful for filenames where both the prefix
417    /// and the extension are important context.
418    TruncateMiddle(SharedString),
419}
420
421/// How to align text within the element
422#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
423pub enum TextAlign {
424    /// Align the text to the left of the element
425    #[default]
426    Left,
427
428    /// Center the text within the element
429    Center,
430
431    /// Align the text to the right of the element
432    Right,
433}
434
435/// The properties that can be used to style text in GPUI
436#[derive(Refineable, Clone, Debug, PartialEq)]
437#[refineable(Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
438pub struct TextStyle {
439    /// The color of the text
440    pub color: Hsla,
441
442    /// The font family to use
443    pub font_family: SharedString,
444
445    /// The font features to use
446    pub font_features: FontFeatures,
447
448    /// The fallback fonts to use
449    pub font_fallbacks: Option<FontFallbacks>,
450
451    /// The font size to use, in pixels or rems.
452    pub font_size: AbsoluteLength,
453
454    /// The line height to use, in pixels or fractions
455    pub line_height: DefiniteLength,
456
457    /// The font weight, e.g. bold
458    pub font_weight: FontWeight,
459
460    /// The font style, e.g. italic
461    pub font_style: FontStyle,
462
463    /// The background color of the text
464    pub background_color: Option<Hsla>,
465
466    /// The underline style of the text
467    pub underline: Option<UnderlineStyle>,
468
469    /// The strikethrough style of the text
470    pub strikethrough: Option<StrikethroughStyle>,
471
472    /// How to handle whitespace in the text
473    pub white_space: WhiteSpace,
474
475    /// The text should be truncated if it overflows the width of the element
476    pub text_overflow: Option<TextOverflow>,
477
478    /// How the text should be aligned within the element
479    pub text_align: TextAlign,
480
481    /// The number of lines to display before truncating the text
482    pub line_clamp: Option<usize>,
483}
484
485impl Default for TextStyle {
486    fn default() -> Self {
487        TextStyle {
488            color: black(),
489            // todo(linux) make this configurable or choose better default
490            font_family: ".SystemUIFont".into(),
491            font_features: FontFeatures::default(),
492            font_fallbacks: None,
493            font_size: rems(1.).into(),
494            line_height: phi(),
495            font_weight: FontWeight::default(),
496            font_style: FontStyle::default(),
497            background_color: None,
498            underline: None,
499            strikethrough: None,
500            white_space: WhiteSpace::Normal,
501            text_overflow: None,
502            text_align: TextAlign::default(),
503            line_clamp: None,
504        }
505    }
506}
507
508impl TextStyle {
509    /// Create a new text style with the given highlighting applied.
510    pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
511        let style = style.into();
512        if let Some(weight) = style.font_weight {
513            self.font_weight = weight;
514        }
515        if let Some(style) = style.font_style {
516            self.font_style = style;
517        }
518
519        if let Some(color) = style.color {
520            self.color = self.color.blend(color);
521        }
522
523        if let Some(factor) = style.fade_out {
524            self.color.fade_out(factor);
525        }
526
527        if let Some(background_color) = style.background_color {
528            self.background_color = Some(background_color);
529        }
530
531        if let Some(underline) = style.underline {
532            self.underline = Some(underline);
533        }
534
535        if let Some(strikethrough) = style.strikethrough {
536            self.strikethrough = Some(strikethrough);
537        }
538
539        self
540    }
541
542    /// Get the font configured for this text style.
543    pub fn font(&self) -> Font {
544        Font {
545            family: self.font_family.clone(),
546            features: self.font_features.clone(),
547            fallbacks: self.font_fallbacks.clone(),
548            weight: self.font_weight,
549            style: self.font_style,
550        }
551    }
552
553    /// Returns the rounded line height in pixels.
554    pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
555        self.line_height.to_pixels(self.font_size, rem_size).round()
556    }
557
558    /// Convert this text style into a [`TextRun`], for the given length of the text.
559    pub fn to_run(&self, len: usize) -> TextRun {
560        TextRun {
561            len,
562            font: Font {
563                family: self.font_family.clone(),
564                features: self.font_features.clone(),
565                fallbacks: self.font_fallbacks.clone(),
566                weight: self.font_weight,
567                style: self.font_style,
568            },
569            color: self.color,
570            background_color: self.background_color,
571            underline: self.underline,
572            strikethrough: self.strikethrough,
573        }
574    }
575}
576
577/// A highlight style to apply, similar to a `TextStyle` except
578/// for a single font, uniformly sized and spaced text.
579#[derive(Copy, Clone, Debug, Default, PartialEq)]
580pub struct HighlightStyle {
581    /// The color of the text
582    pub color: Option<Hsla>,
583
584    /// The font weight, e.g. bold
585    pub font_weight: Option<FontWeight>,
586
587    /// The font style, e.g. italic
588    pub font_style: Option<FontStyle>,
589
590    /// The background color of the text
591    pub background_color: Option<Hsla>,
592
593    /// The underline style of the text
594    pub underline: Option<UnderlineStyle>,
595
596    /// The underline style of the text
597    pub strikethrough: Option<StrikethroughStyle>,
598
599    /// Similar to the CSS `opacity` property, this will cause the text to be less vibrant.
600    pub fade_out: Option<f32>,
601}
602
603impl Eq for HighlightStyle {}
604
605impl Hash for HighlightStyle {
606    fn hash<H: Hasher>(&self, state: &mut H) {
607        self.color.hash(state);
608        self.font_weight.hash(state);
609        self.font_style.hash(state);
610        self.background_color.hash(state);
611        self.underline.hash(state);
612        self.strikethrough.hash(state);
613        state.write_u32(u32::from_be_bytes(
614            self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
615        ));
616    }
617}
618
619impl Style {
620    /// Returns true if the style is visible and the background is opaque.
621    pub fn has_opaque_background(&self) -> bool {
622        self.background
623            .as_ref()
624            .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
625    }
626
627    /// Get the text style in this element style.
628    pub fn text_style(&self) -> Option<&TextStyleRefinement> {
629        if self.text.is_some() {
630            Some(&self.text)
631        } else {
632            None
633        }
634    }
635
636    /// Get the content mask for this element style, based on the given bounds.
637    /// If the element does not hide its overflow, this will return `None`.
638    pub fn overflow_mask(
639        &self,
640        bounds: Bounds<Pixels>,
641        rem_size: Pixels,
642    ) -> Option<ContentMask<Pixels>> {
643        match self.overflow {
644            Point {
645                x: Overflow::Visible,
646                y: Overflow::Visible,
647            } => None,
648            _ => {
649                let mut min = bounds.origin;
650                let mut max = bounds.bottom_right();
651
652                if self
653                    .border_color
654                    .is_some_and(|color| !color.is_transparent())
655                {
656                    min.x += self.border_widths.left.to_pixels(rem_size);
657                    max.x -= self.border_widths.right.to_pixels(rem_size);
658                    min.y += self.border_widths.top.to_pixels(rem_size);
659                    max.y -= self.border_widths.bottom.to_pixels(rem_size);
660                }
661
662                let bounds = match (
663                    self.overflow.x == Overflow::Visible,
664                    self.overflow.y == Overflow::Visible,
665                ) {
666                    // x and y both visible
667                    (true, true) => return None,
668                    // x visible, y hidden
669                    (true, false) => Bounds::from_corners(
670                        point(min.x, bounds.origin.y),
671                        point(max.x, bounds.bottom_right().y),
672                    ),
673                    // x hidden, y visible
674                    (false, true) => Bounds::from_corners(
675                        point(bounds.origin.x, min.y),
676                        point(bounds.bottom_right().x, max.y),
677                    ),
678                    // both hidden
679                    (false, false) => Bounds::from_corners(min, max),
680                };
681
682                Some(ContentMask { bounds })
683            }
684        }
685    }
686
687    /// Paints the background of an element styled with this style.
688    pub fn paint(
689        &self,
690        bounds: Bounds<Pixels>,
691        window: &mut Window,
692        cx: &mut App,
693        continuation: impl FnOnce(&mut Window, &mut App),
694    ) {
695        #[cfg(debug_assertions)]
696        if self.debug_below {
697            cx.set_global(DebugBelow)
698        }
699
700        #[cfg(debug_assertions)]
701        if self.debug || cx.has_global::<DebugBelow>() {
702            window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
703        }
704
705        let rem_size = window.rem_size();
706        let corner_radii = self
707            .corner_radii
708            .to_pixels(rem_size)
709            .clamp_radii_for_quad_size(bounds.size);
710
711        window.paint_drop_shadows(bounds, corner_radii, &self.box_shadow);
712
713        let background_color = self.background.as_ref().and_then(Fill::color);
714        if background_color.is_some_and(|color| !color.is_transparent()) {
715            let mut border_color = match background_color {
716                Some(color) => match color.tag {
717                    BackgroundTag::Solid
718                    | BackgroundTag::PatternSlash
719                    | BackgroundTag::Checkerboard => color.solid,
720
721                    BackgroundTag::LinearGradient => color
722                        .colors
723                        .first()
724                        .map(|stop| stop.color)
725                        .unwrap_or_default(),
726                },
727                None => Hsla::default(),
728            };
729            border_color.a = 0.;
730            window.paint_quad(quad(
731                bounds,
732                corner_radii,
733                background_color.unwrap_or_default(),
734                Edges::default(),
735                border_color,
736                self.border_style,
737            ));
738        }
739
740        window.paint_inset_shadows(bounds, corner_radii, &self.box_shadow);
741
742        continuation(window, cx);
743
744        if self.is_border_visible() {
745            let border_widths = self.border_widths.to_pixels(rem_size);
746            let mut background = self.border_color.unwrap_or_default();
747            background.a = 0.;
748            window.paint_quad(quad(
749                bounds,
750                corner_radii,
751                background,
752                border_widths,
753                self.border_color.unwrap_or_default(),
754                self.border_style,
755            ));
756        }
757
758        #[cfg(debug_assertions)]
759        if self.debug_below {
760            cx.remove_global::<DebugBelow>();
761        }
762    }
763
764    fn is_border_visible(&self) -> bool {
765        self.border_color
766            .is_some_and(|color| !color.is_transparent())
767            && self.border_widths.any(|length| !length.is_zero())
768    }
769}
770
771impl Default for Style {
772    fn default() -> Self {
773        Style {
774            display: Display::Block,
775            visibility: Visibility::Visible,
776            overflow: Point {
777                x: Overflow::Visible,
778                y: Overflow::Visible,
779            },
780            allow_concurrent_scroll: false,
781            restrict_scroll_to_axis: false,
782            scrollbar_width: AbsoluteLength::default(),
783            position: Position::Relative,
784            inset: Edges::auto(),
785            margin: Edges::<Length>::zero(),
786            padding: Edges::<DefiniteLength>::zero(),
787            border_widths: Edges::<AbsoluteLength>::zero(),
788            size: Size::auto(),
789            min_size: Size::auto(),
790            max_size: Size::auto(),
791            aspect_ratio: None,
792            gap: Size::default(),
793            // Alignment
794            align_items: None,
795            align_self: None,
796            align_content: None,
797            justify_content: None,
798            // Flexbox
799            flex_direction: FlexDirection::Row,
800            flex_wrap: FlexWrap::NoWrap,
801            flex_grow: 0.0,
802            flex_shrink: 1.0,
803            flex_basis: Length::Auto,
804            background: None,
805            border_color: None,
806            border_style: BorderStyle::default(),
807            corner_radii: Corners::default(),
808            box_shadow: Default::default(),
809            text: TextStyleRefinement::default(),
810            mouse_cursor: None,
811            opacity: None,
812            grid_rows: None,
813            grid_cols: None,
814            grid_location: None,
815
816            #[cfg(debug_assertions)]
817            debug: false,
818            #[cfg(debug_assertions)]
819            debug_below: false,
820        }
821    }
822}
823
824/// The properties that can be applied to an underline.
825#[derive(
826    Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
827)]
828pub struct UnderlineStyle {
829    /// The thickness of the underline.
830    pub thickness: Pixels,
831
832    /// The color of the underline.
833    pub color: Option<Hsla>,
834
835    /// Whether the underline should be wavy, like in a spell checker.
836    pub wavy: bool,
837}
838
839/// The properties that can be applied to a strikethrough.
840#[derive(
841    Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
842)]
843pub struct StrikethroughStyle {
844    /// The thickness of the strikethrough.
845    pub thickness: Pixels,
846
847    /// The color of the strikethrough.
848    pub color: Option<Hsla>,
849}
850
851/// The kinds of fill that can be applied to a shape.
852#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
853pub enum Fill {
854    /// A solid color fill.
855    Color(Background),
856}
857
858impl Fill {
859    /// Unwrap this fill into a solid color, if it is one.
860    ///
861    /// If the fill is not a solid color, this method returns `None`.
862    pub fn color(&self) -> Option<Background> {
863        match self {
864            Fill::Color(color) => Some(*color),
865        }
866    }
867}
868
869impl Default for Fill {
870    fn default() -> Self {
871        Self::Color(Background::default())
872    }
873}
874
875impl From<Hsla> for Fill {
876    fn from(color: Hsla) -> Self {
877        Self::Color(color.into())
878    }
879}
880
881impl From<Rgba> for Fill {
882    fn from(color: Rgba) -> Self {
883        Self::Color(color.into())
884    }
885}
886
887impl From<Background> for Fill {
888    fn from(background: Background) -> Self {
889        Self::Color(background)
890    }
891}
892
893impl From<TextStyle> for HighlightStyle {
894    fn from(other: TextStyle) -> Self {
895        Self::from(&other)
896    }
897}
898
899impl From<&TextStyle> for HighlightStyle {
900    fn from(other: &TextStyle) -> Self {
901        Self {
902            color: Some(other.color),
903            font_weight: Some(other.font_weight),
904            font_style: Some(other.font_style),
905            background_color: other.background_color,
906            underline: other.underline,
907            strikethrough: other.strikethrough,
908            fade_out: None,
909        }
910    }
911}
912
913impl HighlightStyle {
914    /// Create a highlight style with just a color
915    pub fn color(color: Hsla) -> Self {
916        Self {
917            color: Some(color),
918            ..Default::default()
919        }
920    }
921    /// Blend this highlight style with another.
922    /// Non-continuous properties, like font_weight and font_style, are overwritten.
923    #[must_use]
924    pub fn highlight(self, other: HighlightStyle) -> Self {
925        Self {
926            color: other
927                .color
928                .map(|other_color| {
929                    if let Some(color) = self.color {
930                        color.blend(other_color)
931                    } else {
932                        other_color
933                    }
934                })
935                .or(self.color),
936            font_weight: other.font_weight.or(self.font_weight),
937            font_style: other.font_style.or(self.font_style),
938            background_color: other.background_color.or(self.background_color),
939            underline: other.underline.or(self.underline),
940            strikethrough: other.strikethrough.or(self.strikethrough),
941            fade_out: other
942                .fade_out
943                .map(|source_fade| {
944                    self.fade_out
945                        .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
946                        .unwrap_or(source_fade)
947                })
948                .or(self.fade_out),
949        }
950    }
951}
952
953impl From<Hsla> for HighlightStyle {
954    fn from(color: Hsla) -> Self {
955        Self {
956            color: Some(color),
957            ..Default::default()
958        }
959    }
960}
961
962impl From<FontWeight> for HighlightStyle {
963    fn from(font_weight: FontWeight) -> Self {
964        Self {
965            font_weight: Some(font_weight),
966            ..Default::default()
967        }
968    }
969}
970
971impl From<FontStyle> for HighlightStyle {
972    fn from(font_style: FontStyle) -> Self {
973        Self {
974            font_style: Some(font_style),
975            ..Default::default()
976        }
977    }
978}
979
980impl From<Rgba> for HighlightStyle {
981    fn from(color: Rgba) -> Self {
982        Self {
983            color: Some(color.into()),
984            ..Default::default()
985        }
986    }
987}
988
989/// Combine and merge the highlights and ranges in the two iterators.
990pub fn combine_highlights(
991    a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
992    b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
993) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
994    let mut endpoints = Vec::new();
995    let mut highlights = Vec::new();
996    for (range, highlight) in a.into_iter().chain(b) {
997        if !range.is_empty() {
998            let highlight_id = highlights.len();
999            endpoints.push((range.start, highlight_id, true));
1000            endpoints.push((range.end, highlight_id, false));
1001            highlights.push(highlight);
1002        }
1003    }
1004    endpoints.sort_unstable_by_key(|(position, _, _)| *position);
1005    let mut endpoints = endpoints.into_iter().peekable();
1006
1007    let mut active_styles = HashSet::default();
1008    let mut ix = 0;
1009    iter::from_fn(move || {
1010        while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
1011            let prev_index = mem::replace(&mut ix, *endpoint_ix);
1012            if ix > prev_index && !active_styles.is_empty() {
1013                let current_style = active_styles
1014                    .iter()
1015                    .fold(HighlightStyle::default(), |acc, highlight_id| {
1016                        acc.highlight(highlights[*highlight_id])
1017                    });
1018                return Some((prev_index..ix, current_style));
1019            }
1020
1021            if *is_start {
1022                active_styles.insert(*highlight_id);
1023            } else {
1024                active_styles.remove(highlight_id);
1025            }
1026            endpoints.next();
1027        }
1028        None
1029    })
1030}
1031
1032/// Used to control how child nodes are aligned.
1033/// For Flexbox it controls alignment in the cross axis
1034/// For Grid it controls alignment in the block axis
1035///
1036/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items)
1037#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1038// Copy of taffy::style type of the same name, to derive JsonSchema.
1039pub enum AlignItems {
1040    /// Items are packed toward the start of the axis
1041    Start,
1042    /// Items are packed toward the end of the axis
1043    End,
1044    /// Items are packed towards the flex-relative start of the axis.
1045    ///
1046    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1047    /// to End. In all other cases it is equivalent to Start.
1048    FlexStart,
1049    /// Items are packed towards the flex-relative end of the axis.
1050    ///
1051    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1052    /// to Start. In all other cases it is equivalent to End.
1053    FlexEnd,
1054    /// Items are packed along the center of the cross axis
1055    Center,
1056    /// Items are aligned such as their baselines align
1057    Baseline,
1058    /// Stretch to fill the container
1059    Stretch,
1060}
1061/// Used to control how child nodes are aligned.
1062/// Does not apply to Flexbox, and will be ignored if specified on a flex container
1063/// For Grid it controls alignment in the inline axis
1064///
1065/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)
1066pub type JustifyItems = AlignItems;
1067/// Used to control how the specified nodes is aligned.
1068/// Overrides the parent Node's `AlignItems` property.
1069/// For Flexbox it controls alignment in the cross axis
1070/// For Grid it controls alignment in the block axis
1071///
1072/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self)
1073pub type AlignSelf = AlignItems;
1074/// Used to control how the specified nodes is aligned.
1075/// Overrides the parent Node's `JustifyItems` property.
1076/// Does not apply to Flexbox, and will be ignored if specified on a flex child
1077/// For Grid it controls alignment in the inline axis
1078///
1079/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self)
1080pub type JustifySelf = AlignItems;
1081
1082/// Sets the distribution of space between and around content items
1083/// For Flexbox it controls alignment in the cross axis
1084/// For Grid it controls alignment in the block axis
1085///
1086/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)
1087#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1088// Copy of taffy::style type of the same name, to derive JsonSchema.
1089pub enum AlignContent {
1090    /// Items are packed toward the start of the axis
1091    Start,
1092    /// Items are packed toward the end of the axis
1093    End,
1094    /// Items are packed towards the flex-relative start of the axis.
1095    ///
1096    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1097    /// to End. In all other cases it is equivalent to Start.
1098    FlexStart,
1099    /// Items are packed towards the flex-relative end of the axis.
1100    ///
1101    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1102    /// to Start. In all other cases it is equivalent to End.
1103    FlexEnd,
1104    /// Items are centered around the middle of the axis
1105    Center,
1106    /// Items are stretched to fill the container
1107    Stretch,
1108    /// The first and last items are aligned flush with the edges of the container (no gap)
1109    /// The gap between items is distributed evenly.
1110    SpaceBetween,
1111    /// The gap between the first and last items is exactly THE SAME as the gap between items.
1112    /// The gaps are distributed evenly
1113    SpaceEvenly,
1114    /// The gap between the first and last items is exactly HALF the gap between items.
1115    /// The gaps are distributed evenly in proportion to these ratios.
1116    SpaceAround,
1117}
1118
1119/// Sets the distribution of space between and around content items
1120/// For Flexbox it controls alignment in the main axis
1121/// For Grid it controls alignment in the inline axis
1122///
1123/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content)
1124pub type JustifyContent = AlignContent;
1125
1126/// Sets the layout used for the children of this node
1127///
1128/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Grid, Block, None.
1129#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1130// Copy of taffy::style type of the same name, to derive JsonSchema.
1131pub enum Display {
1132    /// The children will follow the block layout algorithm
1133    Block,
1134    /// The children will follow the flexbox layout algorithm
1135    #[default]
1136    Flex,
1137    /// The children will follow the CSS Grid layout algorithm
1138    Grid,
1139    /// The children will not be laid out, and will follow absolute positioning
1140    None,
1141}
1142
1143/// Controls whether flex items are forced onto one line or can wrap onto multiple lines.
1144///
1145/// Defaults to [`FlexWrap::NoWrap`]
1146///
1147/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-wrap-property)
1148#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1149// Copy of taffy::style type of the same name, to derive JsonSchema.
1150pub enum FlexWrap {
1151    /// Items will not wrap and stay on a single line
1152    #[default]
1153    NoWrap,
1154    /// Items will wrap according to this item's [`FlexDirection`]
1155    Wrap,
1156    /// Items will wrap in the opposite direction to this item's [`FlexDirection`]
1157    WrapReverse,
1158}
1159
1160/// The direction of the flexbox layout main axis.
1161///
1162/// There are always two perpendicular layout axes: main (or primary) and cross (or secondary).
1163/// Adding items will cause them to be positioned adjacent to each other along the main axis.
1164/// By varying this value throughout your tree, you can create complex axis-aligned layouts.
1165///
1166/// Items are always aligned relative to the cross axis, and justified relative to the main axis.
1167///
1168/// The default behavior is [`FlexDirection::Row`].
1169///
1170/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-direction-property)
1171#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1172// Copy of taffy::style type of the same name, to derive JsonSchema.
1173pub enum FlexDirection {
1174    /// Defines +x as the main axis
1175    ///
1176    /// Items will be added from left to right in a row.
1177    #[default]
1178    Row,
1179    /// Defines +y as the main axis
1180    ///
1181    /// Items will be added from top to bottom in a column.
1182    Column,
1183    /// Defines -x as the main axis
1184    ///
1185    /// Items will be added from right to left in a row.
1186    RowReverse,
1187    /// Defines -y as the main axis
1188    ///
1189    /// Items will be added from bottom to top in a column.
1190    ColumnReverse,
1191}
1192
1193/// How children overflowing their container should affect layout
1194///
1195/// In CSS the primary effect of this property is to control whether contents of a parent container that overflow that container should
1196/// be displayed anyway, be clipped, or trigger the container to become a scroll container. However it also has secondary effects on layout,
1197/// the main ones being:
1198///
1199///   - The automatic minimum size Flexbox/CSS Grid items with non-`Visible` overflow is `0` rather than being content based
1200///   - `Overflow::Scroll` nodes have space in the layout reserved for a scrollbar (width controlled by the `scrollbar_width` property)
1201///
1202/// In Taffy, we only implement the layout related secondary effects as we are not concerned with drawing/painting. The amount of space reserved for
1203/// a scrollbar is controlled by the `scrollbar_width` property. If this is `0` then `Scroll` behaves identically to `Hidden`.
1204///
1205/// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow>
1206#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1207// Copy of taffy::style type of the same name, to derive JsonSchema.
1208pub enum Overflow {
1209    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1210    /// Content that overflows this node *should* contribute to the scroll region of its parent.
1211    #[default]
1212    Visible,
1213    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1214    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1215    Clip,
1216    /// The automatic minimum size of this node as a flexbox/grid item should be `0`.
1217    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1218    Hidden,
1219    /// The automatic minimum size of this node as a flexbox/grid item should be `0`. Additionally, space should be reserved
1220    /// for a scrollbar. The amount of space reserved is controlled by the `scrollbar_width` property.
1221    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1222    Scroll,
1223}
1224
1225/// The positioning strategy for this item.
1226///
1227/// This controls both how the origin is determined for the [`Style::position`] field,
1228/// and whether or not the item will be controlled by flexbox's layout algorithm.
1229///
1230/// WARNING: this enum follows the behavior of [CSS's `position` property](https://developer.mozilla.org/en-US/docs/Web/CSS/position),
1231/// which can be unintuitive.
1232///
1233/// [`Position::Relative`] is the default value, in contrast to the default behavior in CSS.
1234#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1235// Copy of taffy::style type of the same name, to derive JsonSchema.
1236pub enum Position {
1237    /// The offset is computed relative to the final position given by the layout algorithm.
1238    /// Offsets do not affect the position of any other items; they are effectively a correction factor applied at the end.
1239    #[default]
1240    Relative,
1241    /// The offset is computed relative to this item's closest positioned ancestor, if any.
1242    /// Otherwise, it is placed relative to the origin.
1243    /// No space is created for the item in the page layout, and its size will not be altered.
1244    ///
1245    /// WARNING: to opt-out of layouting entirely, you must use [`Display::None`] instead on your [`Style`] object.
1246    Absolute,
1247}
1248
1249impl From<AlignItems> for taffy::style::AlignItems {
1250    fn from(value: AlignItems) -> Self {
1251        match value {
1252            AlignItems::Start => Self::START,
1253            AlignItems::End => Self::END,
1254            AlignItems::FlexStart => Self::FLEX_START,
1255            AlignItems::FlexEnd => Self::FLEX_END,
1256            AlignItems::Center => Self::CENTER,
1257            AlignItems::Baseline => Self::BASELINE,
1258            AlignItems::Stretch => Self::STRETCH,
1259        }
1260    }
1261}
1262
1263impl From<AlignContent> for taffy::style::AlignContent {
1264    fn from(value: AlignContent) -> Self {
1265        match value {
1266            AlignContent::Start => Self::START,
1267            AlignContent::End => Self::END,
1268            AlignContent::FlexStart => Self::FLEX_START,
1269            AlignContent::FlexEnd => Self::FLEX_END,
1270            AlignContent::Center => Self::CENTER,
1271            AlignContent::Stretch => Self::STRETCH,
1272            AlignContent::SpaceBetween => Self::SPACE_BETWEEN,
1273            AlignContent::SpaceEvenly => Self::SPACE_EVENLY,
1274            AlignContent::SpaceAround => Self::SPACE_AROUND,
1275        }
1276    }
1277}
1278
1279impl From<Display> for taffy::style::Display {
1280    fn from(value: Display) -> Self {
1281        match value {
1282            Display::Block => Self::Block,
1283            Display::Flex => Self::Flex,
1284            Display::Grid => Self::Grid,
1285            Display::None => Self::None,
1286        }
1287    }
1288}
1289
1290impl From<FlexWrap> for taffy::style::FlexWrap {
1291    fn from(value: FlexWrap) -> Self {
1292        match value {
1293            FlexWrap::NoWrap => Self::NoWrap,
1294            FlexWrap::Wrap => Self::Wrap,
1295            FlexWrap::WrapReverse => Self::WrapReverse,
1296        }
1297    }
1298}
1299
1300impl From<FlexDirection> for taffy::style::FlexDirection {
1301    fn from(value: FlexDirection) -> Self {
1302        match value {
1303            FlexDirection::Row => Self::Row,
1304            FlexDirection::Column => Self::Column,
1305            FlexDirection::RowReverse => Self::RowReverse,
1306            FlexDirection::ColumnReverse => Self::ColumnReverse,
1307        }
1308    }
1309}
1310
1311impl From<Overflow> for taffy::style::Overflow {
1312    fn from(value: Overflow) -> Self {
1313        match value {
1314            Overflow::Visible => Self::Visible,
1315            Overflow::Clip => Self::Clip,
1316            Overflow::Hidden => Self::Hidden,
1317            Overflow::Scroll => Self::Scroll,
1318        }
1319    }
1320}
1321
1322impl From<Position> for taffy::style::Position {
1323    fn from(value: Position) -> Self {
1324        match value {
1325            Position::Relative => Self::Relative,
1326            Position::Absolute => Self::Absolute,
1327        }
1328    }
1329}
1330
1331#[cfg(test)]
1332mod tests {
1333    use crate::{blue, green, px, red, yellow};
1334
1335    use super::*;
1336
1337    use util_macros::perf;
1338
1339    #[perf]
1340    fn test_basic_highlight_style_combination() {
1341        let style_a = HighlightStyle::default();
1342        let style_b = HighlightStyle::default();
1343        let style_a = style_a.highlight(style_b);
1344        assert_eq!(
1345            style_a,
1346            HighlightStyle::default(),
1347            "Combining empty styles should not produce a non-empty style."
1348        );
1349
1350        let mut style_b = HighlightStyle {
1351            color: Some(red()),
1352            strikethrough: Some(StrikethroughStyle {
1353                thickness: px(2.),
1354                color: Some(blue()),
1355            }),
1356            fade_out: Some(0.),
1357            font_style: Some(FontStyle::Italic),
1358            font_weight: Some(FontWeight(300.)),
1359            background_color: Some(yellow()),
1360            underline: Some(UnderlineStyle {
1361                thickness: px(2.),
1362                color: Some(red()),
1363                wavy: true,
1364            }),
1365        };
1366        let expected_style = style_b;
1367
1368        let style_a = style_a.highlight(style_b);
1369        assert_eq!(
1370            style_a, expected_style,
1371            "Blending an empty style with another style should return the other style"
1372        );
1373
1374        let style_b = style_b.highlight(Default::default());
1375        assert_eq!(
1376            style_b, expected_style,
1377            "Blending a style with an empty style should not change the style."
1378        );
1379
1380        let mut style_c = expected_style;
1381
1382        let style_d = HighlightStyle {
1383            color: Some(blue().alpha(0.7)),
1384            strikethrough: Some(StrikethroughStyle {
1385                thickness: px(4.),
1386                color: Some(crate::red()),
1387            }),
1388            fade_out: Some(0.),
1389            font_style: Some(FontStyle::Oblique),
1390            font_weight: Some(FontWeight(800.)),
1391            background_color: Some(green()),
1392            underline: Some(UnderlineStyle {
1393                thickness: px(4.),
1394                color: None,
1395                wavy: false,
1396            }),
1397        };
1398
1399        let expected_style = HighlightStyle {
1400            color: Some(red().blend(blue().alpha(0.7))),
1401            strikethrough: Some(StrikethroughStyle {
1402                thickness: px(4.),
1403                color: Some(red()),
1404            }),
1405            // TODO this does not seem right
1406            fade_out: Some(0.),
1407            font_style: Some(FontStyle::Oblique),
1408            font_weight: Some(FontWeight(800.)),
1409            background_color: Some(green()),
1410            underline: Some(UnderlineStyle {
1411                thickness: px(4.),
1412                color: None,
1413                wavy: false,
1414            }),
1415        };
1416
1417        let style_c = style_c.highlight(style_d);
1418        assert_eq!(
1419            style_c, expected_style,
1420            "Blending styles should blend properties where possible and override all others"
1421        );
1422    }
1423
1424    #[perf]
1425    fn test_combine_highlights() {
1426        assert_eq!(
1427            combine_highlights(
1428                [
1429                    (0..5, green().into()),
1430                    (4..10, FontWeight::BOLD.into()),
1431                    (15..20, yellow().into()),
1432                ],
1433                [
1434                    (2..6, FontStyle::Italic.into()),
1435                    (1..3, blue().into()),
1436                    (21..23, red().into()),
1437                ]
1438            )
1439            .collect::<Vec<_>>(),
1440            [
1441                (
1442                    0..1,
1443                    HighlightStyle {
1444                        color: Some(green()),
1445                        ..Default::default()
1446                    }
1447                ),
1448                (
1449                    1..2,
1450                    HighlightStyle {
1451                        color: Some(blue()),
1452                        ..Default::default()
1453                    }
1454                ),
1455                (
1456                    2..3,
1457                    HighlightStyle {
1458                        color: Some(blue()),
1459                        font_style: Some(FontStyle::Italic),
1460                        ..Default::default()
1461                    }
1462                ),
1463                (
1464                    3..4,
1465                    HighlightStyle {
1466                        color: Some(green()),
1467                        font_style: Some(FontStyle::Italic),
1468                        ..Default::default()
1469                    }
1470                ),
1471                (
1472                    4..5,
1473                    HighlightStyle {
1474                        color: Some(green()),
1475                        font_weight: Some(FontWeight::BOLD),
1476                        font_style: Some(FontStyle::Italic),
1477                        ..Default::default()
1478                    }
1479                ),
1480                (
1481                    5..6,
1482                    HighlightStyle {
1483                        font_weight: Some(FontWeight::BOLD),
1484                        font_style: Some(FontStyle::Italic),
1485                        ..Default::default()
1486                    }
1487                ),
1488                (
1489                    6..10,
1490                    HighlightStyle {
1491                        font_weight: Some(FontWeight::BOLD),
1492                        ..Default::default()
1493                    }
1494                ),
1495                (
1496                    15..20,
1497                    HighlightStyle {
1498                        color: Some(yellow()),
1499                        ..Default::default()
1500                    }
1501                ),
1502                (
1503                    21..23,
1504                    HighlightStyle {
1505                        color: Some(red()),
1506                        ..Default::default()
1507                    }
1508                )
1509            ]
1510        );
1511    }
1512
1513    #[perf]
1514    fn test_text_style_refinement() {
1515        let mut style = Style::default();
1516        style.refine(&StyleRefinement::default().text_size(px(20.0)));
1517        style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
1518
1519        assert_eq!(
1520            Some(AbsoluteLength::from(px(20.0))),
1521            style.text_style().unwrap().font_size
1522        );
1523
1524        assert_eq!(
1525            Some(FontWeight::SEMIBOLD),
1526            style.text_style().unwrap().font_weight
1527        );
1528    }
1529}