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