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