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                let mut inset = Edges::default();
652
653                if self
654                    .border_color
655                    .is_some_and(|color| !color.is_transparent())
656                {
657                    inset = self.border_widths.to_pixels(rem_size);
658                    min.x += inset.left;
659                    max.x -= inset.right;
660                    min.y += inset.top;
661                    max.y -= inset.bottom;
662                }
663
664                let bounds = match (
665                    self.overflow.x == Overflow::Visible,
666                    self.overflow.y == Overflow::Visible,
667                ) {
668                    // x and y both visible
669                    (true, true) => return None,
670                    // x visible, y hidden
671                    (true, false) => Bounds::from_corners(
672                        point(min.x, bounds.origin.y),
673                        point(max.x, bounds.bottom_right().y),
674                    ),
675                    // x hidden, y visible
676                    (false, true) => Bounds::from_corners(
677                        point(bounds.origin.x, min.y),
678                        point(bounds.bottom_right().x, max.y),
679                    ),
680                    // both hidden
681                    (false, false) => Bounds::from_corners(min, max),
682                };
683
684                // The mask curves with the element that owns it, inset by its
685                // border — a child of a rounded box is concentric with it, not
686                // pasted onto it. `clamp_radii_for_quad_size` keeps a radius
687                // past half the box from reading every fragment as outside.
688                // A corner backs off by the wider of the two borders meeting
689                // there, so the inner curve never pokes through either one.
690                let outer = self.corner_radii.to_pixels(rem_size);
691                let corner_radii = Corners {
692                    top_left: (outer.top_left - inset.left.max(inset.top)).max(px(0.)),
693                    top_right: (outer.top_right - inset.right.max(inset.top)).max(px(0.)),
694                    bottom_right: (outer.bottom_right - inset.right.max(inset.bottom)).max(px(0.)),
695                    bottom_left: (outer.bottom_left - inset.left.max(inset.bottom)).max(px(0.)),
696                }
697                .clamp_radii_for_quad_size(bounds.size);
698
699                Some(ContentMask {
700                    bounds,
701                    corner_radii,
702                })
703            }
704        }
705    }
706
707    /// Paints the background of an element styled with this style.
708    pub fn paint(
709        &self,
710        bounds: Bounds<Pixels>,
711        window: &mut Window,
712        cx: &mut App,
713        continuation: impl FnOnce(&mut Window, &mut App),
714    ) {
715        #[cfg(debug_assertions)]
716        if self.debug_below {
717            cx.set_global(DebugBelow)
718        }
719
720        #[cfg(debug_assertions)]
721        if self.debug || cx.has_global::<DebugBelow>() {
722            window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
723        }
724
725        let rem_size = window.rem_size();
726        let corner_radii = self
727            .corner_radii
728            .to_pixels(rem_size)
729            .clamp_radii_for_quad_size(bounds.size);
730
731        window.paint_drop_shadows(bounds, corner_radii, &self.box_shadow);
732
733        let background_color = self.background.as_ref().and_then(Fill::color);
734        if background_color.is_some_and(|color| !color.is_transparent()) {
735            let mut border_color = match background_color {
736                Some(color) => match color.tag {
737                    BackgroundTag::Solid
738                    | BackgroundTag::PatternSlash
739                    | BackgroundTag::Checkerboard => color.solid,
740
741                    BackgroundTag::LinearGradient => color
742                        .colors
743                        .first()
744                        .map(|stop| stop.color)
745                        .unwrap_or_default(),
746                },
747                None => Hsla::default(),
748            };
749            border_color.a = 0.;
750            window.paint_quad(quad(
751                bounds,
752                corner_radii,
753                background_color.unwrap_or_default(),
754                Edges::default(),
755                border_color,
756                self.border_style,
757            ));
758        }
759
760        window.paint_inset_shadows(bounds, corner_radii, &self.box_shadow);
761
762        continuation(window, cx);
763
764        if self.is_border_visible() {
765            let border_widths = self.border_widths.to_pixels(rem_size);
766            let mut background = self.border_color.unwrap_or_default();
767            background.a = 0.;
768            window.paint_quad(quad(
769                bounds,
770                corner_radii,
771                background,
772                border_widths,
773                self.border_color.unwrap_or_default(),
774                self.border_style,
775            ));
776        }
777
778        #[cfg(debug_assertions)]
779        if self.debug_below {
780            cx.remove_global::<DebugBelow>();
781        }
782    }
783
784    fn is_border_visible(&self) -> bool {
785        self.border_color
786            .is_some_and(|color| !color.is_transparent())
787            && self.border_widths.any(|length| !length.is_zero())
788    }
789}
790
791impl Default for Style {
792    fn default() -> Self {
793        Style {
794            display: Display::Block,
795            visibility: Visibility::Visible,
796            overflow: Point {
797                x: Overflow::Visible,
798                y: Overflow::Visible,
799            },
800            allow_concurrent_scroll: false,
801            restrict_scroll_to_axis: false,
802            scrollbar_width: AbsoluteLength::default(),
803            position: Position::Relative,
804            inset: Edges::auto(),
805            margin: Edges::<Length>::zero(),
806            padding: Edges::<DefiniteLength>::zero(),
807            border_widths: Edges::<AbsoluteLength>::zero(),
808            size: Size::auto(),
809            min_size: Size::auto(),
810            max_size: Size::auto(),
811            aspect_ratio: None,
812            gap: Size::default(),
813            // Alignment
814            align_items: None,
815            align_self: None,
816            align_content: None,
817            justify_content: None,
818            // Flexbox
819            flex_direction: FlexDirection::Row,
820            flex_wrap: FlexWrap::NoWrap,
821            flex_grow: 0.0,
822            flex_shrink: 1.0,
823            flex_basis: Length::Auto,
824            background: None,
825            border_color: None,
826            border_style: BorderStyle::default(),
827            corner_radii: Corners::default(),
828            box_shadow: Default::default(),
829            text: TextStyleRefinement::default(),
830            mouse_cursor: None,
831            opacity: None,
832            grid_rows: None,
833            grid_cols: None,
834            grid_location: None,
835
836            #[cfg(debug_assertions)]
837            debug: false,
838            #[cfg(debug_assertions)]
839            debug_below: false,
840        }
841    }
842}
843
844/// The properties that can be applied to an underline.
845#[derive(
846    Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
847)]
848pub struct UnderlineStyle {
849    /// The thickness of the underline.
850    pub thickness: Pixels,
851
852    /// The color of the underline.
853    pub color: Option<Hsla>,
854
855    /// Whether the underline should be wavy, like in a spell checker.
856    pub wavy: bool,
857}
858
859/// The properties that can be applied to a strikethrough.
860#[derive(
861    Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
862)]
863pub struct StrikethroughStyle {
864    /// The thickness of the strikethrough.
865    pub thickness: Pixels,
866
867    /// The color of the strikethrough.
868    pub color: Option<Hsla>,
869}
870
871/// The kinds of fill that can be applied to a shape.
872#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
873pub enum Fill {
874    /// A solid color fill.
875    Color(Background),
876}
877
878impl Fill {
879    /// Unwrap this fill into a solid color, if it is one.
880    ///
881    /// If the fill is not a solid color, this method returns `None`.
882    pub fn color(&self) -> Option<Background> {
883        match self {
884            Fill::Color(color) => Some(*color),
885        }
886    }
887}
888
889impl Default for Fill {
890    fn default() -> Self {
891        Self::Color(Background::default())
892    }
893}
894
895impl From<Hsla> for Fill {
896    fn from(color: Hsla) -> Self {
897        Self::Color(color.into())
898    }
899}
900
901impl From<Rgba> for Fill {
902    fn from(color: Rgba) -> Self {
903        Self::Color(color.into())
904    }
905}
906
907impl From<Background> for Fill {
908    fn from(background: Background) -> Self {
909        Self::Color(background)
910    }
911}
912
913impl From<TextStyle> for HighlightStyle {
914    fn from(other: TextStyle) -> Self {
915        Self::from(&other)
916    }
917}
918
919impl From<&TextStyle> for HighlightStyle {
920    fn from(other: &TextStyle) -> Self {
921        Self {
922            color: Some(other.color),
923            font_weight: Some(other.font_weight),
924            font_style: Some(other.font_style),
925            background_color: other.background_color,
926            underline: other.underline,
927            strikethrough: other.strikethrough,
928            fade_out: None,
929        }
930    }
931}
932
933impl HighlightStyle {
934    /// Create a highlight style with just a color
935    pub fn color(color: Hsla) -> Self {
936        Self {
937            color: Some(color),
938            ..Default::default()
939        }
940    }
941    /// Blend this highlight style with another.
942    /// Non-continuous properties, like font_weight and font_style, are overwritten.
943    #[must_use]
944    pub fn highlight(self, other: HighlightStyle) -> Self {
945        Self {
946            color: other
947                .color
948                .map(|other_color| {
949                    if let Some(color) = self.color {
950                        color.blend(other_color)
951                    } else {
952                        other_color
953                    }
954                })
955                .or(self.color),
956            font_weight: other.font_weight.or(self.font_weight),
957            font_style: other.font_style.or(self.font_style),
958            background_color: other.background_color.or(self.background_color),
959            underline: other.underline.or(self.underline),
960            strikethrough: other.strikethrough.or(self.strikethrough),
961            fade_out: other
962                .fade_out
963                .map(|source_fade| {
964                    self.fade_out
965                        .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
966                        .unwrap_or(source_fade)
967                })
968                .or(self.fade_out),
969        }
970    }
971}
972
973impl From<Hsla> for HighlightStyle {
974    fn from(color: Hsla) -> Self {
975        Self {
976            color: Some(color),
977            ..Default::default()
978        }
979    }
980}
981
982impl From<FontWeight> for HighlightStyle {
983    fn from(font_weight: FontWeight) -> Self {
984        Self {
985            font_weight: Some(font_weight),
986            ..Default::default()
987        }
988    }
989}
990
991impl From<FontStyle> for HighlightStyle {
992    fn from(font_style: FontStyle) -> Self {
993        Self {
994            font_style: Some(font_style),
995            ..Default::default()
996        }
997    }
998}
999
1000impl From<Rgba> for HighlightStyle {
1001    fn from(color: Rgba) -> Self {
1002        Self {
1003            color: Some(color.into()),
1004            ..Default::default()
1005        }
1006    }
1007}
1008
1009/// Combine and merge the highlights and ranges in the two iterators.
1010pub fn combine_highlights(
1011    a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
1012    b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
1013) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
1014    let mut endpoints = Vec::new();
1015    let mut highlights = Vec::new();
1016    for (range, highlight) in a.into_iter().chain(b) {
1017        if !range.is_empty() {
1018            let highlight_id = highlights.len();
1019            endpoints.push((range.start, highlight_id, true));
1020            endpoints.push((range.end, highlight_id, false));
1021            highlights.push(highlight);
1022        }
1023    }
1024    endpoints.sort_unstable_by_key(|(position, _, _)| *position);
1025    let mut endpoints = endpoints.into_iter().peekable();
1026
1027    let mut active_styles = HashSet::default();
1028    let mut ix = 0;
1029    iter::from_fn(move || {
1030        while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
1031            let prev_index = mem::replace(&mut ix, *endpoint_ix);
1032            if ix > prev_index && !active_styles.is_empty() {
1033                let current_style = active_styles
1034                    .iter()
1035                    .fold(HighlightStyle::default(), |acc, highlight_id| {
1036                        acc.highlight(highlights[*highlight_id])
1037                    });
1038                return Some((prev_index..ix, current_style));
1039            }
1040
1041            if *is_start {
1042                active_styles.insert(*highlight_id);
1043            } else {
1044                active_styles.remove(highlight_id);
1045            }
1046            endpoints.next();
1047        }
1048        None
1049    })
1050}
1051
1052/// Used to control how child nodes are aligned.
1053/// For Flexbox it controls alignment in the cross axis
1054/// For Grid it controls alignment in the block axis
1055///
1056/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items)
1057#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1058// Copy of taffy::style type of the same name, to derive JsonSchema.
1059pub enum AlignItems {
1060    /// Items are packed toward the start of the axis
1061    Start,
1062    /// Items are packed toward the end of the axis
1063    End,
1064    /// Items are packed towards the flex-relative start of the axis.
1065    ///
1066    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1067    /// to End. In all other cases it is equivalent to Start.
1068    FlexStart,
1069    /// Items are packed towards the flex-relative end of the axis.
1070    ///
1071    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1072    /// to Start. In all other cases it is equivalent to End.
1073    FlexEnd,
1074    /// Items are packed along the center of the cross axis
1075    Center,
1076    /// Items are aligned such as their baselines align
1077    Baseline,
1078    /// Stretch to fill the container
1079    Stretch,
1080}
1081/// Used to control how child nodes are aligned.
1082/// Does not apply to Flexbox, and will be ignored if specified on a flex container
1083/// For Grid it controls alignment in the inline axis
1084///
1085/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)
1086pub type JustifyItems = AlignItems;
1087/// Used to control how the specified nodes is aligned.
1088/// Overrides the parent Node's `AlignItems` property.
1089/// For Flexbox it controls alignment in the cross axis
1090/// For Grid it controls alignment in the block axis
1091///
1092/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self)
1093pub type AlignSelf = AlignItems;
1094/// Used to control how the specified nodes is aligned.
1095/// Overrides the parent Node's `JustifyItems` property.
1096/// Does not apply to Flexbox, and will be ignored if specified on a flex child
1097/// For Grid it controls alignment in the inline axis
1098///
1099/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self)
1100pub type JustifySelf = AlignItems;
1101
1102/// Sets the distribution of space between and around content items
1103/// For Flexbox it controls alignment in the cross axis
1104/// For Grid it controls alignment in the block axis
1105///
1106/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)
1107#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1108// Copy of taffy::style type of the same name, to derive JsonSchema.
1109pub enum AlignContent {
1110    /// Items are packed toward the start of the axis
1111    Start,
1112    /// Items are packed toward the end of the axis
1113    End,
1114    /// Items are packed towards the flex-relative start of the axis.
1115    ///
1116    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1117    /// to End. In all other cases it is equivalent to Start.
1118    FlexStart,
1119    /// Items are packed towards the flex-relative end of the axis.
1120    ///
1121    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1122    /// to Start. In all other cases it is equivalent to End.
1123    FlexEnd,
1124    /// Items are centered around the middle of the axis
1125    Center,
1126    /// Items are stretched to fill the container
1127    Stretch,
1128    /// The first and last items are aligned flush with the edges of the container (no gap)
1129    /// The gap between items is distributed evenly.
1130    SpaceBetween,
1131    /// The gap between the first and last items is exactly THE SAME as the gap between items.
1132    /// The gaps are distributed evenly
1133    SpaceEvenly,
1134    /// The gap between the first and last items is exactly HALF the gap between items.
1135    /// The gaps are distributed evenly in proportion to these ratios.
1136    SpaceAround,
1137}
1138
1139/// Sets the distribution of space between and around content items
1140/// For Flexbox it controls alignment in the main axis
1141/// For Grid it controls alignment in the inline axis
1142///
1143/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content)
1144pub type JustifyContent = AlignContent;
1145
1146/// Sets the layout used for the children of this node
1147///
1148/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Grid, Block, None.
1149#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1150// Copy of taffy::style type of the same name, to derive JsonSchema.
1151pub enum Display {
1152    /// The children will follow the block layout algorithm
1153    Block,
1154    /// The children will follow the flexbox layout algorithm
1155    #[default]
1156    Flex,
1157    /// The children will follow the CSS Grid layout algorithm
1158    Grid,
1159    /// The children will not be laid out, and will follow absolute positioning
1160    None,
1161}
1162
1163/// Controls whether flex items are forced onto one line or can wrap onto multiple lines.
1164///
1165/// Defaults to [`FlexWrap::NoWrap`]
1166///
1167/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-wrap-property)
1168#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1169// Copy of taffy::style type of the same name, to derive JsonSchema.
1170pub enum FlexWrap {
1171    /// Items will not wrap and stay on a single line
1172    #[default]
1173    NoWrap,
1174    /// Items will wrap according to this item's [`FlexDirection`]
1175    Wrap,
1176    /// Items will wrap in the opposite direction to this item's [`FlexDirection`]
1177    WrapReverse,
1178}
1179
1180/// The direction of the flexbox layout main axis.
1181///
1182/// There are always two perpendicular layout axes: main (or primary) and cross (or secondary).
1183/// Adding items will cause them to be positioned adjacent to each other along the main axis.
1184/// By varying this value throughout your tree, you can create complex axis-aligned layouts.
1185///
1186/// Items are always aligned relative to the cross axis, and justified relative to the main axis.
1187///
1188/// The default behavior is [`FlexDirection::Row`].
1189///
1190/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-direction-property)
1191#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1192// Copy of taffy::style type of the same name, to derive JsonSchema.
1193pub enum FlexDirection {
1194    /// Defines +x as the main axis
1195    ///
1196    /// Items will be added from left to right in a row.
1197    #[default]
1198    Row,
1199    /// Defines +y as the main axis
1200    ///
1201    /// Items will be added from top to bottom in a column.
1202    Column,
1203    /// Defines -x as the main axis
1204    ///
1205    /// Items will be added from right to left in a row.
1206    RowReverse,
1207    /// Defines -y as the main axis
1208    ///
1209    /// Items will be added from bottom to top in a column.
1210    ColumnReverse,
1211}
1212
1213/// How children overflowing their container should affect layout
1214///
1215/// In CSS the primary effect of this property is to control whether contents of a parent container that overflow that container should
1216/// be displayed anyway, be clipped, or trigger the container to become a scroll container. However it also has secondary effects on layout,
1217/// the main ones being:
1218///
1219///   - The automatic minimum size Flexbox/CSS Grid items with non-`Visible` overflow is `0` rather than being content based
1220///   - `Overflow::Scroll` nodes have space in the layout reserved for a scrollbar (width controlled by the `scrollbar_width` property)
1221///
1222/// In Taffy, we only implement the layout related secondary effects as we are not concerned with drawing/painting. The amount of space reserved for
1223/// a scrollbar is controlled by the `scrollbar_width` property. If this is `0` then `Scroll` behaves identically to `Hidden`.
1224///
1225/// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow>
1226#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1227// Copy of taffy::style type of the same name, to derive JsonSchema.
1228pub enum Overflow {
1229    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1230    /// Content that overflows this node *should* contribute to the scroll region of its parent.
1231    #[default]
1232    Visible,
1233    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1234    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1235    Clip,
1236    /// The automatic minimum size of this node as a flexbox/grid item should be `0`.
1237    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1238    Hidden,
1239    /// The automatic minimum size of this node as a flexbox/grid item should be `0`. Additionally, space should be reserved
1240    /// for a scrollbar. The amount of space reserved is controlled by the `scrollbar_width` property.
1241    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1242    Scroll,
1243}
1244
1245/// The positioning strategy for this item.
1246///
1247/// This controls both how the origin is determined for the [`Style::position`] field,
1248/// and whether or not the item will be controlled by flexbox's layout algorithm.
1249///
1250/// WARNING: this enum follows the behavior of [CSS's `position` property](https://developer.mozilla.org/en-US/docs/Web/CSS/position),
1251/// which can be unintuitive.
1252///
1253/// [`Position::Relative`] is the default value, in contrast to the default behavior in CSS.
1254#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1255// Copy of taffy::style type of the same name, to derive JsonSchema.
1256pub enum Position {
1257    /// The offset is computed relative to the final position given by the layout algorithm.
1258    /// Offsets do not affect the position of any other items; they are effectively a correction factor applied at the end.
1259    #[default]
1260    Relative,
1261    /// The offset is computed relative to this item's closest positioned ancestor, if any.
1262    /// Otherwise, it is placed relative to the origin.
1263    /// No space is created for the item in the page layout, and its size will not be altered.
1264    ///
1265    /// WARNING: to opt-out of layouting entirely, you must use [`Display::None`] instead on your [`Style`] object.
1266    Absolute,
1267}
1268
1269impl From<AlignItems> for taffy::style::AlignItems {
1270    fn from(value: AlignItems) -> Self {
1271        match value {
1272            AlignItems::Start => Self::START,
1273            AlignItems::End => Self::END,
1274            AlignItems::FlexStart => Self::FLEX_START,
1275            AlignItems::FlexEnd => Self::FLEX_END,
1276            AlignItems::Center => Self::CENTER,
1277            AlignItems::Baseline => Self::BASELINE,
1278            AlignItems::Stretch => Self::STRETCH,
1279        }
1280    }
1281}
1282
1283impl From<AlignContent> for taffy::style::AlignContent {
1284    fn from(value: AlignContent) -> Self {
1285        match value {
1286            AlignContent::Start => Self::START,
1287            AlignContent::End => Self::END,
1288            AlignContent::FlexStart => Self::FLEX_START,
1289            AlignContent::FlexEnd => Self::FLEX_END,
1290            AlignContent::Center => Self::CENTER,
1291            AlignContent::Stretch => Self::STRETCH,
1292            AlignContent::SpaceBetween => Self::SPACE_BETWEEN,
1293            AlignContent::SpaceEvenly => Self::SPACE_EVENLY,
1294            AlignContent::SpaceAround => Self::SPACE_AROUND,
1295        }
1296    }
1297}
1298
1299impl From<Display> for taffy::style::Display {
1300    fn from(value: Display) -> Self {
1301        match value {
1302            Display::Block => Self::Block,
1303            Display::Flex => Self::Flex,
1304            Display::Grid => Self::Grid,
1305            Display::None => Self::None,
1306        }
1307    }
1308}
1309
1310impl From<FlexWrap> for taffy::style::FlexWrap {
1311    fn from(value: FlexWrap) -> Self {
1312        match value {
1313            FlexWrap::NoWrap => Self::NoWrap,
1314            FlexWrap::Wrap => Self::Wrap,
1315            FlexWrap::WrapReverse => Self::WrapReverse,
1316        }
1317    }
1318}
1319
1320impl From<FlexDirection> for taffy::style::FlexDirection {
1321    fn from(value: FlexDirection) -> Self {
1322        match value {
1323            FlexDirection::Row => Self::Row,
1324            FlexDirection::Column => Self::Column,
1325            FlexDirection::RowReverse => Self::RowReverse,
1326            FlexDirection::ColumnReverse => Self::ColumnReverse,
1327        }
1328    }
1329}
1330
1331impl From<Overflow> for taffy::style::Overflow {
1332    fn from(value: Overflow) -> Self {
1333        match value {
1334            Overflow::Visible => Self::Visible,
1335            Overflow::Clip => Self::Clip,
1336            Overflow::Hidden => Self::Hidden,
1337            Overflow::Scroll => Self::Scroll,
1338        }
1339    }
1340}
1341
1342impl From<Position> for taffy::style::Position {
1343    fn from(value: Position) -> Self {
1344        match value {
1345            Position::Relative => Self::Relative,
1346            Position::Absolute => Self::Absolute,
1347        }
1348    }
1349}
1350
1351#[cfg(test)]
1352mod tests {
1353    use crate::{blue, green, px, red, yellow};
1354
1355    use super::*;
1356
1357    use util_macros::perf;
1358
1359    #[perf]
1360    fn test_basic_highlight_style_combination() {
1361        let style_a = HighlightStyle::default();
1362        let style_b = HighlightStyle::default();
1363        let style_a = style_a.highlight(style_b);
1364        assert_eq!(
1365            style_a,
1366            HighlightStyle::default(),
1367            "Combining empty styles should not produce a non-empty style."
1368        );
1369
1370        let mut style_b = HighlightStyle {
1371            color: Some(red()),
1372            strikethrough: Some(StrikethroughStyle {
1373                thickness: px(2.),
1374                color: Some(blue()),
1375            }),
1376            fade_out: Some(0.),
1377            font_style: Some(FontStyle::Italic),
1378            font_weight: Some(FontWeight(300.)),
1379            background_color: Some(yellow()),
1380            underline: Some(UnderlineStyle {
1381                thickness: px(2.),
1382                color: Some(red()),
1383                wavy: true,
1384            }),
1385        };
1386        let expected_style = style_b;
1387
1388        let style_a = style_a.highlight(style_b);
1389        assert_eq!(
1390            style_a, expected_style,
1391            "Blending an empty style with another style should return the other style"
1392        );
1393
1394        let style_b = style_b.highlight(Default::default());
1395        assert_eq!(
1396            style_b, expected_style,
1397            "Blending a style with an empty style should not change the style."
1398        );
1399
1400        let mut style_c = expected_style;
1401
1402        let style_d = HighlightStyle {
1403            color: Some(blue().alpha(0.7)),
1404            strikethrough: Some(StrikethroughStyle {
1405                thickness: px(4.),
1406                color: Some(crate::red()),
1407            }),
1408            fade_out: Some(0.),
1409            font_style: Some(FontStyle::Oblique),
1410            font_weight: Some(FontWeight(800.)),
1411            background_color: Some(green()),
1412            underline: Some(UnderlineStyle {
1413                thickness: px(4.),
1414                color: None,
1415                wavy: false,
1416            }),
1417        };
1418
1419        let expected_style = HighlightStyle {
1420            color: Some(red().blend(blue().alpha(0.7))),
1421            strikethrough: Some(StrikethroughStyle {
1422                thickness: px(4.),
1423                color: Some(red()),
1424            }),
1425            // TODO this does not seem right
1426            fade_out: Some(0.),
1427            font_style: Some(FontStyle::Oblique),
1428            font_weight: Some(FontWeight(800.)),
1429            background_color: Some(green()),
1430            underline: Some(UnderlineStyle {
1431                thickness: px(4.),
1432                color: None,
1433                wavy: false,
1434            }),
1435        };
1436
1437        let style_c = style_c.highlight(style_d);
1438        assert_eq!(
1439            style_c, expected_style,
1440            "Blending styles should blend properties where possible and override all others"
1441        );
1442    }
1443
1444    #[perf]
1445    fn test_combine_highlights() {
1446        assert_eq!(
1447            combine_highlights(
1448                [
1449                    (0..5, green().into()),
1450                    (4..10, FontWeight::BOLD.into()),
1451                    (15..20, yellow().into()),
1452                ],
1453                [
1454                    (2..6, FontStyle::Italic.into()),
1455                    (1..3, blue().into()),
1456                    (21..23, red().into()),
1457                ]
1458            )
1459            .collect::<Vec<_>>(),
1460            [
1461                (
1462                    0..1,
1463                    HighlightStyle {
1464                        color: Some(green()),
1465                        ..Default::default()
1466                    }
1467                ),
1468                (
1469                    1..2,
1470                    HighlightStyle {
1471                        color: Some(blue()),
1472                        ..Default::default()
1473                    }
1474                ),
1475                (
1476                    2..3,
1477                    HighlightStyle {
1478                        color: Some(blue()),
1479                        font_style: Some(FontStyle::Italic),
1480                        ..Default::default()
1481                    }
1482                ),
1483                (
1484                    3..4,
1485                    HighlightStyle {
1486                        color: Some(green()),
1487                        font_style: Some(FontStyle::Italic),
1488                        ..Default::default()
1489                    }
1490                ),
1491                (
1492                    4..5,
1493                    HighlightStyle {
1494                        color: Some(green()),
1495                        font_weight: Some(FontWeight::BOLD),
1496                        font_style: Some(FontStyle::Italic),
1497                        ..Default::default()
1498                    }
1499                ),
1500                (
1501                    5..6,
1502                    HighlightStyle {
1503                        font_weight: Some(FontWeight::BOLD),
1504                        font_style: Some(FontStyle::Italic),
1505                        ..Default::default()
1506                    }
1507                ),
1508                (
1509                    6..10,
1510                    HighlightStyle {
1511                        font_weight: Some(FontWeight::BOLD),
1512                        ..Default::default()
1513                    }
1514                ),
1515                (
1516                    15..20,
1517                    HighlightStyle {
1518                        color: Some(yellow()),
1519                        ..Default::default()
1520                    }
1521                ),
1522                (
1523                    21..23,
1524                    HighlightStyle {
1525                        color: Some(red()),
1526                        ..Default::default()
1527                    }
1528                )
1529            ]
1530        );
1531    }
1532
1533    #[perf]
1534    fn test_text_style_refinement() {
1535        let mut style = Style::default();
1536        style.refine(&StyleRefinement::default().text_size(px(20.0)));
1537        style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
1538
1539        assert_eq!(
1540            Some(AbsoluteLength::from(px(20.0))),
1541            style.text_style().unwrap().font_size
1542        );
1543
1544        assert_eq!(
1545            Some(FontWeight::SEMIBOLD),
1546            style.text_style().unwrap().font_weight
1547        );
1548    }
1549}