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