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    /// 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: if cfg!(any(target_os = "linux", target_os = "freebsd")) {
 407                "FreeMono".into()
 408            } else if cfg!(target_os = "windows") {
 409                "Segoe UI".into()
 410            } else {
 411                "Helvetica".into()
 412            },
 413            font_features: FontFeatures::default(),
 414            font_fallbacks: None,
 415            font_size: rems(1.).into(),
 416            line_height: phi(),
 417            font_weight: FontWeight::default(),
 418            font_style: FontStyle::default(),
 419            background_color: None,
 420            underline: None,
 421            strikethrough: None,
 422            white_space: WhiteSpace::Normal,
 423            text_overflow: None,
 424            text_align: TextAlign::default(),
 425            line_clamp: None,
 426        }
 427    }
 428}
 429
 430impl TextStyle {
 431    /// Create a new text style with the given highlighting applied.
 432    pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
 433        let style = style.into();
 434        if let Some(weight) = style.font_weight {
 435            self.font_weight = weight;
 436        }
 437        if let Some(style) = style.font_style {
 438            self.font_style = style;
 439        }
 440
 441        if let Some(color) = style.color {
 442            self.color = self.color.blend(color);
 443        }
 444
 445        if let Some(factor) = style.fade_out {
 446            self.color.fade_out(factor);
 447        }
 448
 449        if let Some(background_color) = style.background_color {
 450            self.background_color = Some(background_color);
 451        }
 452
 453        if let Some(underline) = style.underline {
 454            self.underline = Some(underline);
 455        }
 456
 457        if let Some(strikethrough) = style.strikethrough {
 458            self.strikethrough = Some(strikethrough);
 459        }
 460
 461        self
 462    }
 463
 464    /// Get the font configured for this text style.
 465    pub fn font(&self) -> Font {
 466        Font {
 467            family: self.font_family.clone(),
 468            features: self.font_features.clone(),
 469            fallbacks: self.font_fallbacks.clone(),
 470            weight: self.font_weight,
 471            style: self.font_style,
 472        }
 473    }
 474
 475    /// Returns the rounded line height in pixels.
 476    pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
 477        self.line_height.to_pixels(self.font_size, rem_size).round()
 478    }
 479
 480    /// Convert this text style into a [`TextRun`], for the given length of the text.
 481    pub fn to_run(&self, len: usize) -> TextRun {
 482        TextRun {
 483            len,
 484            font: Font {
 485                family: self.font_family.clone(),
 486                features: self.font_features.clone(),
 487                fallbacks: self.font_fallbacks.clone(),
 488                weight: self.font_weight,
 489                style: self.font_style,
 490            },
 491            color: self.color,
 492            background_color: self.background_color,
 493            underline: self.underline,
 494            strikethrough: self.strikethrough,
 495        }
 496    }
 497}
 498
 499/// A highlight style to apply, similar to a `TextStyle` except
 500/// for a single font, uniformly sized and spaced text.
 501#[derive(Copy, Clone, Debug, Default, PartialEq)]
 502pub struct HighlightStyle {
 503    /// The color of the text
 504    pub color: Option<Hsla>,
 505
 506    /// The font weight, e.g. bold
 507    pub font_weight: Option<FontWeight>,
 508
 509    /// The font style, e.g. italic
 510    pub font_style: Option<FontStyle>,
 511
 512    /// The background color of the text
 513    pub background_color: Option<Hsla>,
 514
 515    /// The underline style of the text
 516    pub underline: Option<UnderlineStyle>,
 517
 518    /// The underline style of the text
 519    pub strikethrough: Option<StrikethroughStyle>,
 520
 521    /// Similar to the CSS `opacity` property, this will cause the text to be less vibrant.
 522    pub fade_out: Option<f32>,
 523}
 524
 525impl Eq for HighlightStyle {}
 526
 527impl Hash for HighlightStyle {
 528    fn hash<H: Hasher>(&self, state: &mut H) {
 529        self.color.hash(state);
 530        self.font_weight.hash(state);
 531        self.font_style.hash(state);
 532        self.background_color.hash(state);
 533        self.underline.hash(state);
 534        self.strikethrough.hash(state);
 535        state.write_u32(u32::from_be_bytes(
 536            self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
 537        ));
 538    }
 539}
 540
 541impl Style {
 542    /// Returns true if the style is visible and the background is opaque.
 543    pub fn has_opaque_background(&self) -> bool {
 544        self.background
 545            .as_ref()
 546            .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
 547    }
 548
 549    /// Get the text style in this element style.
 550    pub fn text_style(&self) -> Option<&TextStyleRefinement> {
 551        if self.text.is_some() {
 552            Some(&self.text)
 553        } else {
 554            None
 555        }
 556    }
 557
 558    /// Get the content mask for this element style, based on the given bounds.
 559    /// If the element does not hide its overflow, this will return `None`.
 560    pub fn overflow_mask(
 561        &self,
 562        bounds: Bounds<Pixels>,
 563        rem_size: Pixels,
 564    ) -> Option<ContentMask<Pixels>> {
 565        match self.overflow {
 566            Point {
 567                x: Overflow::Visible,
 568                y: Overflow::Visible,
 569            } => None,
 570            _ => {
 571                let mut min = bounds.origin;
 572                let mut max = bounds.bottom_right();
 573
 574                if self
 575                    .border_color
 576                    .is_some_and(|color| !color.is_transparent())
 577                {
 578                    min.x += self.border_widths.left.to_pixels(rem_size);
 579                    max.x -= self.border_widths.right.to_pixels(rem_size);
 580                    min.y += self.border_widths.top.to_pixels(rem_size);
 581                    max.y -= self.border_widths.bottom.to_pixels(rem_size);
 582                }
 583
 584                let bounds = match (
 585                    self.overflow.x == Overflow::Visible,
 586                    self.overflow.y == Overflow::Visible,
 587                ) {
 588                    // x and y both visible
 589                    (true, true) => return None,
 590                    // x visible, y hidden
 591                    (true, false) => Bounds::from_corners(
 592                        point(min.x, bounds.origin.y),
 593                        point(max.x, bounds.bottom_right().y),
 594                    ),
 595                    // x hidden, y visible
 596                    (false, true) => Bounds::from_corners(
 597                        point(bounds.origin.x, min.y),
 598                        point(bounds.bottom_right().x, max.y),
 599                    ),
 600                    // both hidden
 601                    (false, false) => Bounds::from_corners(min, max),
 602                };
 603
 604                Some(ContentMask { bounds })
 605            }
 606        }
 607    }
 608
 609    /// Paints the background of an element styled with this style.
 610    pub fn paint(
 611        &self,
 612        bounds: Bounds<Pixels>,
 613        window: &mut Window,
 614        cx: &mut App,
 615        continuation: impl FnOnce(&mut Window, &mut App),
 616    ) {
 617        #[cfg(debug_assertions)]
 618        if self.debug_below {
 619            cx.set_global(DebugBelow)
 620        }
 621
 622        #[cfg(debug_assertions)]
 623        if self.debug || cx.has_global::<DebugBelow>() {
 624            window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
 625        }
 626
 627        let rem_size = window.rem_size();
 628        let corner_radii = self
 629            .corner_radii
 630            .to_pixels(rem_size)
 631            .clamp_radii_for_quad_size(bounds.size);
 632
 633        window.paint_shadows(bounds, corner_radii, &self.box_shadow);
 634
 635        let background_color = self.background.as_ref().and_then(Fill::color);
 636        if background_color.is_some_and(|color| !color.is_transparent()) {
 637            let mut border_color = match background_color {
 638                Some(color) => match color.tag {
 639                    BackgroundTag::Solid => color.solid,
 640                    BackgroundTag::LinearGradient => color
 641                        .colors
 642                        .first()
 643                        .map(|stop| stop.color)
 644                        .unwrap_or_default(),
 645                    BackgroundTag::PatternSlash => color.solid,
 646                },
 647                None => Hsla::default(),
 648            };
 649            border_color.a = 0.;
 650            window.paint_quad(quad(
 651                bounds,
 652                corner_radii,
 653                background_color.unwrap_or_default(),
 654                Edges::default(),
 655                border_color,
 656                self.border_style,
 657            ));
 658        }
 659
 660        continuation(window, cx);
 661
 662        if self.is_border_visible() {
 663            let border_widths = self.border_widths.to_pixels(rem_size);
 664            let max_border_width = border_widths.max();
 665            let max_corner_radius = corner_radii.max();
 666
 667            let top_bounds = Bounds::from_corners(
 668                bounds.origin,
 669                bounds.top_right() + point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
 670            );
 671            let bottom_bounds = Bounds::from_corners(
 672                bounds.bottom_left() - point(Pixels::ZERO, max_border_width.max(max_corner_radius)),
 673                bounds.bottom_right(),
 674            );
 675            let left_bounds = Bounds::from_corners(
 676                top_bounds.bottom_left(),
 677                bottom_bounds.origin + point(max_border_width, Pixels::ZERO),
 678            );
 679            let right_bounds = Bounds::from_corners(
 680                top_bounds.bottom_right() - point(max_border_width, Pixels::ZERO),
 681                bottom_bounds.top_right(),
 682            );
 683
 684            let mut background = self.border_color.unwrap_or_default();
 685            background.a = 0.;
 686            let quad = quad(
 687                bounds,
 688                corner_radii,
 689                background,
 690                border_widths,
 691                self.border_color.unwrap_or_default(),
 692                self.border_style,
 693            );
 694
 695            window.with_content_mask(Some(ContentMask { bounds: top_bounds }), |window| {
 696                window.paint_quad(quad.clone());
 697            });
 698            window.with_content_mask(
 699                Some(ContentMask {
 700                    bounds: right_bounds,
 701                }),
 702                |window| {
 703                    window.paint_quad(quad.clone());
 704                },
 705            );
 706            window.with_content_mask(
 707                Some(ContentMask {
 708                    bounds: bottom_bounds,
 709                }),
 710                |window| {
 711                    window.paint_quad(quad.clone());
 712                },
 713            );
 714            window.with_content_mask(
 715                Some(ContentMask {
 716                    bounds: left_bounds,
 717                }),
 718                |window| {
 719                    window.paint_quad(quad);
 720                },
 721            );
 722        }
 723
 724        #[cfg(debug_assertions)]
 725        if self.debug_below {
 726            cx.remove_global::<DebugBelow>();
 727        }
 728    }
 729
 730    fn is_border_visible(&self) -> bool {
 731        self.border_color
 732            .is_some_and(|color| !color.is_transparent())
 733            && self.border_widths.any(|length| !length.is_zero())
 734    }
 735}
 736
 737impl Default for Style {
 738    fn default() -> Self {
 739        Style {
 740            display: Display::Block,
 741            visibility: Visibility::Visible,
 742            overflow: Point {
 743                x: Overflow::Visible,
 744                y: Overflow::Visible,
 745            },
 746            allow_concurrent_scroll: false,
 747            restrict_scroll_to_axis: false,
 748            scrollbar_width: AbsoluteLength::default(),
 749            position: Position::Relative,
 750            inset: Edges::auto(),
 751            margin: Edges::<Length>::zero(),
 752            padding: Edges::<DefiniteLength>::zero(),
 753            border_widths: Edges::<AbsoluteLength>::zero(),
 754            size: Size::auto(),
 755            min_size: Size::auto(),
 756            max_size: Size::auto(),
 757            aspect_ratio: None,
 758            gap: Size::default(),
 759            // Alignment
 760            align_items: None,
 761            align_self: None,
 762            align_content: None,
 763            justify_content: None,
 764            // Flexbox
 765            flex_direction: FlexDirection::Row,
 766            flex_wrap: FlexWrap::NoWrap,
 767            flex_grow: 0.0,
 768            flex_shrink: 1.0,
 769            flex_basis: Length::Auto,
 770            background: None,
 771            border_color: None,
 772            border_style: BorderStyle::default(),
 773            corner_radii: Corners::default(),
 774            box_shadow: Default::default(),
 775            text: TextStyleRefinement::default(),
 776            mouse_cursor: None,
 777            opacity: None,
 778            grid_rows: None,
 779            grid_cols: None,
 780            grid_location: None,
 781
 782            #[cfg(debug_assertions)]
 783            debug: false,
 784            #[cfg(debug_assertions)]
 785            debug_below: false,
 786        }
 787    }
 788}
 789
 790/// The properties that can be applied to an underline.
 791#[derive(
 792    Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
 793)]
 794pub struct UnderlineStyle {
 795    /// The thickness of the underline.
 796    pub thickness: Pixels,
 797
 798    /// The color of the underline.
 799    pub color: Option<Hsla>,
 800
 801    /// Whether the underline should be wavy, like in a spell checker.
 802    pub wavy: bool,
 803}
 804
 805/// The properties that can be applied to a strikethrough.
 806#[derive(
 807    Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema,
 808)]
 809pub struct StrikethroughStyle {
 810    /// The thickness of the strikethrough.
 811    pub thickness: Pixels,
 812
 813    /// The color of the strikethrough.
 814    pub color: Option<Hsla>,
 815}
 816
 817/// The kinds of fill that can be applied to a shape.
 818#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 819pub enum Fill {
 820    /// A solid color fill.
 821    Color(Background),
 822}
 823
 824impl Fill {
 825    /// Unwrap this fill into a solid color, if it is one.
 826    ///
 827    /// If the fill is not a solid color, this method returns `None`.
 828    pub fn color(&self) -> Option<Background> {
 829        match self {
 830            Fill::Color(color) => Some(*color),
 831        }
 832    }
 833}
 834
 835impl Default for Fill {
 836    fn default() -> Self {
 837        Self::Color(Background::default())
 838    }
 839}
 840
 841impl From<Hsla> for Fill {
 842    fn from(color: Hsla) -> Self {
 843        Self::Color(color.into())
 844    }
 845}
 846
 847impl From<Rgba> for Fill {
 848    fn from(color: Rgba) -> Self {
 849        Self::Color(color.into())
 850    }
 851}
 852
 853impl From<Background> for Fill {
 854    fn from(background: Background) -> Self {
 855        Self::Color(background)
 856    }
 857}
 858
 859impl From<TextStyle> for HighlightStyle {
 860    fn from(other: TextStyle) -> Self {
 861        Self::from(&other)
 862    }
 863}
 864
 865impl From<&TextStyle> for HighlightStyle {
 866    fn from(other: &TextStyle) -> Self {
 867        Self {
 868            color: Some(other.color),
 869            font_weight: Some(other.font_weight),
 870            font_style: Some(other.font_style),
 871            background_color: other.background_color,
 872            underline: other.underline,
 873            strikethrough: other.strikethrough,
 874            fade_out: None,
 875        }
 876    }
 877}
 878
 879impl HighlightStyle {
 880    /// Create a highlight style with just a color
 881    pub fn color(color: Hsla) -> Self {
 882        Self {
 883            color: Some(color),
 884            ..Default::default()
 885        }
 886    }
 887    /// Blend this highlight style with another.
 888    /// Non-continuous properties, like font_weight and font_style, are overwritten.
 889    #[must_use]
 890    pub fn highlight(self, other: HighlightStyle) -> Self {
 891        Self {
 892            color: other
 893                .color
 894                .map(|other_color| {
 895                    if let Some(color) = self.color {
 896                        color.blend(other_color)
 897                    } else {
 898                        other_color
 899                    }
 900                })
 901                .or(self.color),
 902            font_weight: other.font_weight.or(self.font_weight),
 903            font_style: other.font_style.or(self.font_style),
 904            background_color: other.background_color.or(self.background_color),
 905            underline: other.underline.or(self.underline),
 906            strikethrough: other.strikethrough.or(self.strikethrough),
 907            fade_out: other
 908                .fade_out
 909                .map(|source_fade| {
 910                    self.fade_out
 911                        .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
 912                        .unwrap_or(source_fade)
 913                })
 914                .or(self.fade_out),
 915        }
 916    }
 917}
 918
 919impl From<Hsla> for HighlightStyle {
 920    fn from(color: Hsla) -> Self {
 921        Self {
 922            color: Some(color),
 923            ..Default::default()
 924        }
 925    }
 926}
 927
 928impl From<FontWeight> for HighlightStyle {
 929    fn from(font_weight: FontWeight) -> Self {
 930        Self {
 931            font_weight: Some(font_weight),
 932            ..Default::default()
 933        }
 934    }
 935}
 936
 937impl From<FontStyle> for HighlightStyle {
 938    fn from(font_style: FontStyle) -> Self {
 939        Self {
 940            font_style: Some(font_style),
 941            ..Default::default()
 942        }
 943    }
 944}
 945
 946impl From<Rgba> for HighlightStyle {
 947    fn from(color: Rgba) -> Self {
 948        Self {
 949            color: Some(color.into()),
 950            ..Default::default()
 951        }
 952    }
 953}
 954
 955/// Combine and merge the highlights and ranges in the two iterators.
 956pub fn combine_highlights(
 957    a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
 958    b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
 959) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
 960    let mut endpoints = Vec::new();
 961    let mut highlights = Vec::new();
 962    for (range, highlight) in a.into_iter().chain(b) {
 963        if !range.is_empty() {
 964            let highlight_id = highlights.len();
 965            endpoints.push((range.start, highlight_id, true));
 966            endpoints.push((range.end, highlight_id, false));
 967            highlights.push(highlight);
 968        }
 969    }
 970    endpoints.sort_unstable_by_key(|(position, _, _)| *position);
 971    let mut endpoints = endpoints.into_iter().peekable();
 972
 973    let mut active_styles = HashSet::default();
 974    let mut ix = 0;
 975    iter::from_fn(move || {
 976        while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
 977            let prev_index = mem::replace(&mut ix, *endpoint_ix);
 978            if ix > prev_index && !active_styles.is_empty() {
 979                let current_style = active_styles
 980                    .iter()
 981                    .fold(HighlightStyle::default(), |acc, highlight_id| {
 982                        acc.highlight(highlights[*highlight_id])
 983                    });
 984                return Some((prev_index..ix, current_style));
 985            }
 986
 987            if *is_start {
 988                active_styles.insert(*highlight_id);
 989            } else {
 990                active_styles.remove(highlight_id);
 991            }
 992            endpoints.next();
 993        }
 994        None
 995    })
 996}
 997
 998/// Used to control how child nodes are aligned.
 999/// For Flexbox it controls alignment in the cross axis
1000/// For Grid it controls alignment in the block axis
1001///
1002/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items)
1003#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1004// Copy of taffy::style type of the same name, to derive JsonSchema.
1005pub enum AlignItems {
1006    /// Items are packed toward the start of the axis
1007    Start,
1008    /// Items are packed toward the end of the axis
1009    End,
1010    /// Items are packed towards the flex-relative start of the axis.
1011    ///
1012    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1013    /// to End. In all other cases it is equivalent to Start.
1014    FlexStart,
1015    /// Items are packed towards the flex-relative end of the axis.
1016    ///
1017    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1018    /// to Start. In all other cases it is equivalent to End.
1019    FlexEnd,
1020    /// Items are packed along the center of the cross axis
1021    Center,
1022    /// Items are aligned such as their baselines align
1023    Baseline,
1024    /// Stretch to fill the container
1025    Stretch,
1026}
1027/// Used to control how child nodes are aligned.
1028/// Does not apply to Flexbox, and will be ignored if specified on a flex container
1029/// For Grid it controls alignment in the inline axis
1030///
1031/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)
1032pub type JustifyItems = AlignItems;
1033/// Used to control how the specified nodes is aligned.
1034/// Overrides the parent Node's `AlignItems` property.
1035/// For Flexbox it controls alignment in the cross axis
1036/// For Grid it controls alignment in the block axis
1037///
1038/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self)
1039pub type AlignSelf = AlignItems;
1040/// Used to control how the specified nodes is aligned.
1041/// Overrides the parent Node's `JustifyItems` property.
1042/// Does not apply to Flexbox, and will be ignored if specified on a flex child
1043/// For Grid it controls alignment in the inline axis
1044///
1045/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self)
1046pub type JustifySelf = AlignItems;
1047
1048/// Sets the distribution of space between and around content items
1049/// For Flexbox it controls alignment in the cross axis
1050/// For Grid it controls alignment in the block axis
1051///
1052/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)
1053#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize, JsonSchema)]
1054// Copy of taffy::style type of the same name, to derive JsonSchema.
1055pub enum AlignContent {
1056    /// Items are packed toward the start of the axis
1057    Start,
1058    /// Items are packed toward the end of the axis
1059    End,
1060    /// Items are packed towards the flex-relative start of the axis.
1061    ///
1062    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1063    /// to End. In all other cases it is equivalent to Start.
1064    FlexStart,
1065    /// Items are packed towards the flex-relative end of the axis.
1066    ///
1067    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
1068    /// to Start. In all other cases it is equivalent to End.
1069    FlexEnd,
1070    /// Items are centered around the middle of the axis
1071    Center,
1072    /// Items are stretched to fill the container
1073    Stretch,
1074    /// The first and last items are aligned flush with the edges of the container (no gap)
1075    /// The gap between items is distributed evenly.
1076    SpaceBetween,
1077    /// The gap between the first and last items is exactly THE SAME as the gap between items.
1078    /// The gaps are distributed evenly
1079    SpaceEvenly,
1080    /// The gap between the first and last items is exactly HALF the gap between items.
1081    /// The gaps are distributed evenly in proportion to these ratios.
1082    SpaceAround,
1083}
1084
1085/// Sets the distribution of space between and around content items
1086/// For Flexbox it controls alignment in the main axis
1087/// For Grid it controls alignment in the inline axis
1088///
1089/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content)
1090pub type JustifyContent = AlignContent;
1091
1092/// Sets the layout used for the children of this node
1093///
1094/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Grid, Block, None.
1095#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1096// Copy of taffy::style type of the same name, to derive JsonSchema.
1097pub enum Display {
1098    /// The children will follow the block layout algorithm
1099    Block,
1100    /// The children will follow the flexbox layout algorithm
1101    #[default]
1102    Flex,
1103    /// The children will follow the CSS Grid layout algorithm
1104    Grid,
1105    /// The children will not be laid out, and will follow absolute positioning
1106    None,
1107}
1108
1109/// Controls whether flex items are forced onto one line or can wrap onto multiple lines.
1110///
1111/// Defaults to [`FlexWrap::NoWrap`]
1112///
1113/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-wrap-property)
1114#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1115// Copy of taffy::style type of the same name, to derive JsonSchema.
1116pub enum FlexWrap {
1117    /// Items will not wrap and stay on a single line
1118    #[default]
1119    NoWrap,
1120    /// Items will wrap according to this item's [`FlexDirection`]
1121    Wrap,
1122    /// Items will wrap in the opposite direction to this item's [`FlexDirection`]
1123    WrapReverse,
1124}
1125
1126/// The direction of the flexbox layout main axis.
1127///
1128/// There are always two perpendicular layout axes: main (or primary) and cross (or secondary).
1129/// Adding items will cause them to be positioned adjacent to each other along the main axis.
1130/// By varying this value throughout your tree, you can create complex axis-aligned layouts.
1131///
1132/// Items are always aligned relative to the cross axis, and justified relative to the main axis.
1133///
1134/// The default behavior is [`FlexDirection::Row`].
1135///
1136/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-direction-property)
1137#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1138// Copy of taffy::style type of the same name, to derive JsonSchema.
1139pub enum FlexDirection {
1140    /// Defines +x as the main axis
1141    ///
1142    /// Items will be added from left to right in a row.
1143    #[default]
1144    Row,
1145    /// Defines +y as the main axis
1146    ///
1147    /// Items will be added from top to bottom in a column.
1148    Column,
1149    /// Defines -x as the main axis
1150    ///
1151    /// Items will be added from right to left in a row.
1152    RowReverse,
1153    /// Defines -y as the main axis
1154    ///
1155    /// Items will be added from bottom to top in a column.
1156    ColumnReverse,
1157}
1158
1159/// How children overflowing their container should affect layout
1160///
1161/// In CSS the primary effect of this property is to control whether contents of a parent container that overflow that container should
1162/// be displayed anyway, be clipped, or trigger the container to become a scroll container. However it also has secondary effects on layout,
1163/// the main ones being:
1164///
1165///   - The automatic minimum size Flexbox/CSS Grid items with non-`Visible` overflow is `0` rather than being content based
1166///   - `Overflow::Scroll` nodes have space in the layout reserved for a scrollbar (width controlled by the `scrollbar_width` property)
1167///
1168/// In Taffy, we only implement the layout related secondary effects as we are not concerned with drawing/painting. The amount of space reserved for
1169/// a scrollbar is controlled by the `scrollbar_width` property. If this is `0` then `Scroll` behaves identically to `Hidden`.
1170///
1171/// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow>
1172#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1173// Copy of taffy::style type of the same name, to derive JsonSchema.
1174pub enum Overflow {
1175    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1176    /// Content that overflows this node *should* contribute to the scroll region of its parent.
1177    #[default]
1178    Visible,
1179    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
1180    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1181    Clip,
1182    /// The automatic minimum size of this node as a flexbox/grid item should be `0`.
1183    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1184    Hidden,
1185    /// The automatic minimum size of this node as a flexbox/grid item should be `0`. Additionally, space should be reserved
1186    /// for a scrollbar. The amount of space reserved is controlled by the `scrollbar_width` property.
1187    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
1188    Scroll,
1189}
1190
1191/// The positioning strategy for this item.
1192///
1193/// This controls both how the origin is determined for the [`Style::position`] field,
1194/// and whether or not the item will be controlled by flexbox's layout algorithm.
1195///
1196/// WARNING: this enum follows the behavior of [CSS's `position` property](https://developer.mozilla.org/en-US/docs/Web/CSS/position),
1197/// which can be unintuitive.
1198///
1199/// [`Position::Relative`] is the default value, in contrast to the default behavior in CSS.
1200#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize, JsonSchema)]
1201// Copy of taffy::style type of the same name, to derive JsonSchema.
1202pub enum Position {
1203    /// The offset is computed relative to the final position given by the layout algorithm.
1204    /// Offsets do not affect the position of any other items; they are effectively a correction factor applied at the end.
1205    #[default]
1206    Relative,
1207    /// The offset is computed relative to this item's closest positioned ancestor, if any.
1208    /// Otherwise, it is placed relative to the origin.
1209    /// No space is created for the item in the page layout, and its size will not be altered.
1210    ///
1211    /// WARNING: to opt-out of layouting entirely, you must use [`Display::None`] instead on your [`Style`] object.
1212    Absolute,
1213}
1214
1215impl From<AlignItems> for taffy::style::AlignItems {
1216    fn from(value: AlignItems) -> Self {
1217        match value {
1218            AlignItems::Start => Self::Start,
1219            AlignItems::End => Self::End,
1220            AlignItems::FlexStart => Self::FlexStart,
1221            AlignItems::FlexEnd => Self::FlexEnd,
1222            AlignItems::Center => Self::Center,
1223            AlignItems::Baseline => Self::Baseline,
1224            AlignItems::Stretch => Self::Stretch,
1225        }
1226    }
1227}
1228
1229impl From<AlignContent> for taffy::style::AlignContent {
1230    fn from(value: AlignContent) -> Self {
1231        match value {
1232            AlignContent::Start => Self::Start,
1233            AlignContent::End => Self::End,
1234            AlignContent::FlexStart => Self::FlexStart,
1235            AlignContent::FlexEnd => Self::FlexEnd,
1236            AlignContent::Center => Self::Center,
1237            AlignContent::Stretch => Self::Stretch,
1238            AlignContent::SpaceBetween => Self::SpaceBetween,
1239            AlignContent::SpaceEvenly => Self::SpaceEvenly,
1240            AlignContent::SpaceAround => Self::SpaceAround,
1241        }
1242    }
1243}
1244
1245impl From<Display> for taffy::style::Display {
1246    fn from(value: Display) -> Self {
1247        match value {
1248            Display::Block => Self::Block,
1249            Display::Flex => Self::Flex,
1250            Display::Grid => Self::Grid,
1251            Display::None => Self::None,
1252        }
1253    }
1254}
1255
1256impl From<FlexWrap> for taffy::style::FlexWrap {
1257    fn from(value: FlexWrap) -> Self {
1258        match value {
1259            FlexWrap::NoWrap => Self::NoWrap,
1260            FlexWrap::Wrap => Self::Wrap,
1261            FlexWrap::WrapReverse => Self::WrapReverse,
1262        }
1263    }
1264}
1265
1266impl From<FlexDirection> for taffy::style::FlexDirection {
1267    fn from(value: FlexDirection) -> Self {
1268        match value {
1269            FlexDirection::Row => Self::Row,
1270            FlexDirection::Column => Self::Column,
1271            FlexDirection::RowReverse => Self::RowReverse,
1272            FlexDirection::ColumnReverse => Self::ColumnReverse,
1273        }
1274    }
1275}
1276
1277impl From<Overflow> for taffy::style::Overflow {
1278    fn from(value: Overflow) -> Self {
1279        match value {
1280            Overflow::Visible => Self::Visible,
1281            Overflow::Clip => Self::Clip,
1282            Overflow::Hidden => Self::Hidden,
1283            Overflow::Scroll => Self::Scroll,
1284        }
1285    }
1286}
1287
1288impl From<Position> for taffy::style::Position {
1289    fn from(value: Position) -> Self {
1290        match value {
1291            Position::Relative => Self::Relative,
1292            Position::Absolute => Self::Absolute,
1293        }
1294    }
1295}
1296
1297#[cfg(test)]
1298mod tests {
1299    use crate::{blue, green, px, red, yellow};
1300
1301    use super::*;
1302
1303    #[test]
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    #[test]
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}