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