Skip to main content

gpui/
style.rs

1use std::{
2    hash::{Hash, Hasher},
3    iter, mem,
4    ops::Range,
5    sync::Arc,
6};
7
8use crate::{
9    AbsoluteLength, App, Background, BackgroundTag, BorderStyle, Bounds, ContentMask, Corners,
10    CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges, EdgesRefinement,
11    EffectCrossFade, EffectSpec, Font,
12    FontFallbacks, FontFeatures, FontStyle, FontWeight, GridLocation, Hsla, Length, Pixels, Point,
13    PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, Window, black, phi,
14    TransformSpec, TransformationMatrix, VnClipOutline, VnFillRule, VnPathVerb, point, px, quad,
15    rems, size,
16};
17use collections::HashSet;
18use refineable::Refineable;
19#[cfg(feature = "schemars")]
20use schemars::JsonSchema;
21use serde::{Deserialize, Serialize};
22
23/// Use this struct for interfacing with the 'debug_below' styling from your own elements.
24/// If a parent element has this style set on it, then this struct will be set as a global in
25/// GPUI.
26#[cfg(debug_assertions)]
27pub struct DebugBelow;
28
29#[cfg(debug_assertions)]
30impl crate::Global for DebugBelow {}
31
32/// How to fit the image into the bounds of the element.
33pub enum ObjectFit {
34    /// The image will be stretched to fill the bounds of the element.
35    Fill,
36    /// The image will be scaled to fit within the bounds of the element.
37    Contain,
38    /// The image will be scaled to cover the bounds of the element.
39    Cover,
40    /// The image will be scaled down to fit within the bounds of the element.
41    ScaleDown,
42    /// The image will maintain its original size.
43    None,
44}
45
46impl ObjectFit {
47    /// Get the bounds of the image within the given bounds.
48    pub fn get_bounds(
49        &self,
50        bounds: Bounds<Pixels>,
51        image_size: Size<DevicePixels>,
52    ) -> Bounds<Pixels> {
53        let fitted = self.get_bounds_at(bounds, image_size, ObjectPosition::default());
54        match self {
55            ObjectFit::None => Bounds {
56                origin: bounds.origin,
57                size: fitted.size,
58            },
59            _ => fitted,
60        }
61    }
62
63    /// The bounds of the image within `bounds`, placed in the free space by `position`
64    /// (CSS `object-fit` with `object-position`).
65    pub fn get_bounds_at(
66        &self,
67        bounds: Bounds<Pixels>,
68        image_size: Size<DevicePixels>,
69        position: ObjectPosition,
70    ) -> Bounds<Pixels> {
71        let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
72        let image_ratio = image_size.width / image_size.height;
73        let bounds_ratio = bounds.size.width / bounds.size.height;
74        let contain = || {
75            if bounds_ratio > image_ratio {
76                size(
77                    image_size.width * (bounds.size.height / image_size.height),
78                    bounds.size.height,
79                )
80            } else {
81                size(
82                    bounds.size.width,
83                    image_size.height * (bounds.size.width / image_size.width),
84                )
85            }
86        };
87
88        let new_size = match self {
89            ObjectFit::Fill => bounds.size,
90            ObjectFit::Contain => contain(),
91            ObjectFit::ScaleDown => {
92                if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
93                    contain()
94                } else {
95                    image_size
96                }
97            }
98            ObjectFit::Cover => {
99                if bounds_ratio > image_ratio {
100                    size(
101                        bounds.size.width,
102                        image_size.height * (bounds.size.width / image_size.width),
103                    )
104                } else {
105                    size(
106                        image_size.width * (bounds.size.height / image_size.height),
107                        bounds.size.height,
108                    )
109                }
110            }
111            ObjectFit::None => image_size,
112        };
113        Bounds {
114            origin: point(
115                bounds.origin.x
116                    + (bounds.size.width - new_size.width) * position.x_fraction
117                    + position.x_offset,
118                bounds.origin.y
119                    + (bounds.size.height - new_size.height) * position.y_fraction
120                    + position.y_offset,
121            ),
122            size: new_size,
123        }
124    }
125}
126
127/// CSS `object-position`: per axis, a fraction of the free space (box minus content, which may be
128/// negative) plus an offset. The default is centred.
129#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
130#[cfg_attr(feature = "schemars", derive(JsonSchema))]
131pub struct ObjectPosition {
132    /// Fraction of the horizontal free space.
133    pub x_fraction: f32,
134    /// Added to the horizontal placement.
135    pub x_offset: Pixels,
136    /// Fraction of the vertical free space.
137    pub y_fraction: f32,
138    /// Added to the vertical placement.
139    pub y_offset: Pixels,
140}
141
142impl Default for ObjectPosition {
143    fn default() -> Self {
144        Self {
145            x_fraction: 0.5,
146            x_offset: Pixels::ZERO,
147            y_fraction: 0.5,
148            y_offset: Pixels::ZERO,
149        }
150    }
151}
152
153/// The minimum size of a column or row in a grid layout
154#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)]
155#[cfg_attr(feature = "schemars", derive(JsonSchema))]
156pub enum GridTemplateMinSize {
157    /// The column or row size may be 0
158    #[default]
159    Zero,
160    /// The column or row size can be determined by the min content
161    MinContent,
162    /// The column or row size can be determined by the max content
163    MaxContent,
164}
165
166/// A simplified representation of the grid-template-* value
167#[derive(
168    Copy, Clone, Refineable, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize,
169)]
170#[cfg_attr(feature = "schemars", derive(JsonSchema))]
171pub struct GridTemplate {
172    /// How this template directive should be repeated
173    pub repeat: u16,
174    /// The minimum size in the repeat(<>, minmax(_, 1fr)) equation
175    pub min_size: GridTemplateMinSize,
176}
177
178/// One end of a CSS grid track's sizing function — the `a` or the `b` in
179/// `minmax(a, b)`.
180///
181/// This is the full set taffy can express for a *definite* track. `fit-content()`
182/// and `calc()` are absent: the first has no caller and the second is resolved
183/// before it reaches here.
184#[derive(Copy, Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
185#[cfg_attr(feature = "schemars", derive(JsonSchema))]
186pub enum GridTrackSize {
187    /// `auto`
188    #[default]
189    Auto,
190    /// `min-content`
191    MinContent,
192    /// `max-content`
193    MaxContent,
194    /// An absolute length, in logical pixels.
195    Px(f32),
196    /// A percentage of the container's track-axis size, as a FRACTION (`50%`
197    /// is `0.5`) — taffy's unit, not CSS's.
198    Percent(f32),
199    /// `<flex>` — `1fr` is `Fr(1.0)`. Only valid as the MAX of a track; a `fr`
200    /// minimum is invalid CSS and is normalised to `Auto` by the caller.
201    Fr(f32),
202}
203
204/// One track in a `grid-template-columns` / `grid-template-rows` list.
205///
206/// Always stored in its `minmax()` normal form, which is what CSS says every
207/// track sizing function means: a bare `1fr` is `minmax(auto, 1fr)`, a bare
208/// `200px` is `minmax(200px, 200px)`.
209#[derive(Copy, Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
210#[cfg_attr(feature = "schemars", derive(JsonSchema))]
211pub struct GridTrack {
212    /// The track's minimum size.
213    pub min: GridTrackSize,
214    /// The track's maximum size.
215    pub max: GridTrackSize,
216}
217
218impl GridTrack {
219    /// `minmax(size, size)` — the normal form of a bare, definite track.
220    pub fn fixed(size: GridTrackSize) -> Self {
221        Self {
222            min: size,
223            max: size,
224        }
225    }
226
227    /// `minmax(auto, <flex>)` — the normal form of a bare `<flex>` track.
228    pub fn fr(flex: f32) -> Self {
229        Self {
230            min: GridTrackSize::Auto,
231            max: GridTrackSize::Fr(flex),
232        }
233    }
234}
235
236/// vue-native fork: CSS `repeat(auto-fill | auto-fit, <tracks>)` inside a
237/// track list — as many repetitions as fit the container, which taffy counts
238/// at layout time. The repeated tracks are a run of the track list it belongs
239/// to ([`Style::vn_grid_cols`] / [`Style::vn_grid_rows`]); CSS allows one such
240/// repetition per list, and every other track in that list must then have a
241/// fixed size, which the caller checks.
242#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
243#[cfg_attr(feature = "schemars", derive(JsonSchema))]
244pub struct GridAutoRepeat {
245    /// `auto-fit` (the empty repetitions collapse) rather than `auto-fill`
246    /// (they keep their size).
247    pub fit: bool,
248    /// The index in the track list of the first repeated track.
249    pub start: u16,
250    /// How many tracks of the list one repetition holds.
251    pub len: u16,
252}
253
254/// CSS `grid-auto-flow`: which axis the auto-placement algorithm fills, and
255/// whether it backfills holes.
256#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
257#[cfg_attr(feature = "schemars", derive(JsonSchema))]
258pub enum GridAutoFlow {
259    /// Fill each row in turn, adding rows as needed.
260    #[default]
261    Row,
262    /// Fill each column in turn, adding columns as needed.
263    Column,
264    /// `row dense`
265    RowDense,
266    /// `column dense`
267    ColumnDense,
268}
269
270/// CSS `outline`: a ring painted just outside the border box, taking no layout
271/// space. See [`Style::vn_outline`].
272#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
273#[cfg_attr(feature = "schemars", derive(JsonSchema))]
274pub struct Outline {
275    /// `outline-width`. Zero paints nothing.
276    pub width: Pixels,
277    /// `outline-offset` — the gap between the border box and the ring's INNER
278    /// edge. May be negative, which pulls the ring inside the box.
279    pub offset: Pixels,
280    /// `outline-color`.
281    pub color: Hsla,
282    /// `outline-style`, reduced to what gpui's quad can draw.
283    pub style: BorderStyle,
284}
285
286/// vue-native fork: one CSS `border-*-radius` corner, as its two radii. Each
287/// is a length, a percentage of the box (`Fraction`), or a linear `calc()`
288/// with one. See [`Style::vn_corner_radii`].
289#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
290#[cfg_attr(feature = "schemars", derive(JsonSchema))]
291pub struct VnCornerRadius {
292    /// The horizontal radius; a percentage is of the box's width.
293    pub x: DefiniteLength,
294    /// The vertical radius; a percentage is of the box's height.
295    pub y: DefiniteLength,
296}
297
298static VN_ELLIPSE_DRAWN_AS_CIRCLE: std::sync::atomic::AtomicBool =
299    std::sync::atomic::AtomicBool::new(false);
300
301/// vue-native fork: whether a corner was painted with a circle in place of
302/// the ellipse CSS asks for, since the last call. vn-tree reads it to advise
303/// once.
304pub fn vn_take_ellipse_drawn_as_circle() -> bool {
305    VN_ELLIPSE_DRAWN_AS_CIRCLE.swap(false, std::sync::atomic::Ordering::Relaxed)
306}
307
308/// vue-native fork: a box's painted corner radii, as CSS resolves them.
309///
310/// - A corner with a `relative` radius resolves it against `size`: the
311///   horizontal radius against the width, the vertical against the height.
312///   Any other corner takes its `lengths` radius on both axes.
313/// - CSS's overlap rule (css-backgrounds-3 §5.5) applies: when the radii
314///   along a side sum past its length, every radius is scaled by the
315///   smallest such ratio. That is what makes Tailwind's `rounded-full`
316///   (9999px) a pill.
317/// - gpui's corners are circles, so a corner whose two radii still differ
318///   takes the smaller one. `50%` on a box that is not square comes out as a
319///   pill where a browser draws an ellipse, and
320///   [`vn_take_ellipse_drawn_as_circle`] reports it.
321/// - Each radius is finally clamped to half the shorter side, which the
322///   shaders need because they pick a corner by quadrant. CSS lets a lone
323///   large corner reach past the middle of the box.
324pub fn vn_resolve_corner_radii(
325    lengths: &Corners<AbsoluteLength>,
326    relative: &Corners<Option<VnCornerRadius>>,
327    size: Size<Pixels>,
328    rem_size: Pixels,
329) -> Corners<Pixels> {
330    let (width, height) = (f32::from(size.width).max(0.), f32::from(size.height).max(0.));
331    let pair = |length: &AbsoluteLength, relative: &Option<VnCornerRadius>| -> (f32, f32) {
332        match relative {
333            Some(radius) => (
334                f32::from(radius.x.to_pixels(px(width).into(), rem_size)).max(0.),
335                f32::from(radius.y.to_pixels(px(height).into(), rem_size)).max(0.),
336            ),
337            None => {
338                let radius = f32::from(length.to_pixels(rem_size)).max(0.);
339                (radius, radius)
340            }
341        }
342    };
343    let top_left = pair(&lengths.top_left, &relative.top_left);
344    let top_right = pair(&lengths.top_right, &relative.top_right);
345    let bottom_right = pair(&lengths.bottom_right, &relative.bottom_right);
346    let bottom_left = pair(&lengths.bottom_left, &relative.bottom_left);
347
348    let ratio = |side: f32, a: f32, b: f32| if a + b > side { side / (a + b) } else { 1. };
349    let factor = ratio(width, top_left.0, top_right.0)
350        .min(ratio(width, bottom_left.0, bottom_right.0))
351        .min(ratio(height, top_left.1, bottom_left.1))
352        .min(ratio(height, top_right.1, bottom_right.1));
353
354    let circle = |(x, y): (f32, f32)| {
355        let (x, y) = (x * factor, y * factor);
356        let radius = x.min(y);
357        if radius > 0. && (x - y).abs() > 0.5 {
358            VN_ELLIPSE_DRAWN_AS_CIRCLE.store(true, std::sync::atomic::Ordering::Relaxed);
359        }
360        px(radius)
361    };
362    Corners {
363        top_left: circle(top_left),
364        top_right: circle(top_right),
365        bottom_right: circle(bottom_right),
366        bottom_left: circle(bottom_left),
367    }
368    .clamp_radii_for_quad_size(size)
369}
370
371/// vue-native fork: the box a `clip-path` is laid against (CSS Masking 1
372/// §5.1, `<geometry-box>`). `fill-box` is the content box and `stroke-box` and
373/// `view-box` the border box, as for any element with a CSS box.
374#[derive(Copy, Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
375#[cfg_attr(feature = "schemars", derive(JsonSchema))]
376pub enum VnClipBox {
377    /// The margin box.
378    Margin,
379    /// The border box, the default.
380    #[default]
381    Border,
382    /// The padding box.
383    Padding,
384    /// The content box.
385    Content,
386}
387
388/// vue-native fork: a `<shape-radius>` of `circle()` or `ellipse()`.
389#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
390#[cfg_attr(feature = "schemars", derive(JsonSchema))]
391pub enum VnShapeRadius {
392    /// A length. A percentage is of the reference box's width for an
393    /// ellipse's horizontal radius, of its height for the vertical one, and
394    /// of `sqrt(width² + height²) / sqrt(2)` for a circle's.
395    Length(DefiniteLength),
396    /// The distance from the centre to the reference box's closest side
397    /// (in the radius's own axis, for an ellipse).
398    ClosestSide,
399    /// The distance to the farthest side.
400    FarthestSide,
401}
402
403/// vue-native fork: CSS `clip-path` (CSS Masking 1 §5). The shapes a rounded
404/// content mask can carry are one ([`Style::vn_clip_mask`]); `polygon()`,
405/// `path()` and an ellipse that is no circle are an isolated layer composited
406/// through the shape ([`Style::vn_clip_outline`], [`crate::VnClipGeometry`]).
407#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
408#[cfg_attr(feature = "schemars", derive(JsonSchema))]
409pub enum VnClipPath {
410    /// `none`: no clip.
411    #[default]
412    None,
413    /// A `<geometry-box>` alone: that box, rounded as `border-radius` rounds
414    /// it.
415    Box(VnClipBox),
416    /// `inset()`: the reference box less `insets`, with `radii` (`round`).
417    /// A percentage inset is of the box's width (left and right) or height
418    /// (top and bottom), and a percentage radius of the box's size, as
419    /// Chromium resolves them.
420    Inset {
421        /// The box the insets are taken from.
422        reference: VnClipBox,
423        /// The insets: top, right, bottom, left.
424        insets: [DefiniteLength; 4],
425        /// The `round` radii: top left, top right, bottom right, bottom
426        /// left. Zero for a square corner.
427        radii: [VnCornerRadius; 4],
428    },
429    /// `circle()`, or `ellipse()`: a centre in the reference box and two
430    /// radii. A circle is a rounded mask; an ellipse whose radii differ is
431    /// its outline, four cubics, in an isolated layer. Both are exact.
432    Ellipse {
433        /// The box the centre and the radii are resolved against.
434        reference: VnClipBox,
435        /// The centre, from the reference box's top left corner: x, y.
436        center: [DefiniteLength; 2],
437        /// The horizontal and vertical radii; the same for a circle.
438        radius: [VnShapeRadius; 2],
439        /// `circle()`: a percentage radius is of the box's diagonal over
440        /// `sqrt(2)`, and the closest or farthest side is of all four.
441        circle: bool,
442    },
443    /// `polygon()`: its vertices, x and y from the reference box's top left
444    /// corner, a percentage of its width and height.
445    Polygon {
446        /// The box the vertices are laid against.
447        reference: VnClipBox,
448        /// `nonzero` or `evenodd`.
449        fill_rule: VnFillRule,
450        /// The vertices, in order.
451        points: Arc<[[DefiniteLength; 2]]>,
452    },
453    /// `path()`: SVG path data, in pixels from the reference box's top left
454    /// corner (CSS Shapes 1 §3.1).
455    Path {
456        /// The box the path is laid against.
457        reference: VnClipBox,
458        /// `nonzero` or `evenodd`.
459        fill_rule: VnFillRule,
460        /// The path, absolute ([`VnPathVerb`]).
461        verbs: Arc<[VnPathVerb]>,
462    },
463}
464
465/// vue-native fork: a `circle()` or `ellipse()` resolved against its reference
466/// box `rect`: the centre and the two radii (CSS Shapes 1 §3.1).
467fn vn_clip_ellipse(
468    rect: Bounds<Pixels>,
469    center: &[DefiniteLength; 2],
470    radius: &[VnShapeRadius; 2],
471    circle: bool,
472    rem_size: Pixels,
473) -> (Point<Pixels>, Pixels, Pixels) {
474    let (w, h) = (rect.size.width, rect.size.height);
475    let resolve = |length: &DefiniteLength, base: Pixels| length.to_pixels(AbsoluteLength::Pixels(base), rem_size);
476    let cx = rect.left() + resolve(&center[0], w);
477    let cy = rect.top() + resolve(&center[1], h);
478    let (near_x, far_x) = ((cx - rect.left()).abs(), (rect.right() - cx).abs());
479    let (near_y, far_y) = ((cy - rect.top()).abs(), (rect.bottom() - cy).abs());
480    // A circle's sides are all four, and its percentage is of the box's
481    // diagonal over sqrt(2).
482    let diagonal = px((f32::from(w).powi(2) + f32::from(h).powi(2)).sqrt() / 2f32.sqrt());
483    let one = |r: &VnShapeRadius, horizontal: bool| -> Pixels {
484        let (a, b) = if circle {
485            (near_x.min(far_x).min(near_y.min(far_y)), near_x.max(far_x).max(near_y.max(far_y)))
486        } else if horizontal {
487            (near_x.min(far_x), near_x.max(far_x))
488        } else {
489            (near_y.min(far_y), near_y.max(far_y))
490        };
491        match r {
492            VnShapeRadius::ClosestSide => a,
493            VnShapeRadius::FarthestSide => b,
494            VnShapeRadius::Length(l) => resolve(l, if circle { diagonal } else if horizontal { w } else { h }).max(px(0.)),
495        }
496    };
497    (point(cx, cy), one(&radius[0], true), one(&radius[1], false))
498}
499
500/// The CSS styling that can be applied to an element via the `Styled` trait
501#[derive(Clone, Refineable, Debug)]
502#[refineable(Debug, PartialEq, Serialize, Deserialize)]
503#[cfg_attr(feature = "schemars", refineable(JsonSchema))]
504pub struct Style {
505    /// What layout strategy should be used?
506    pub display: Display,
507
508    /// Should the element be painted on screen?
509    pub visibility: Visibility,
510
511    // Overflow properties
512    /// How children overflowing their container should affect layout
513    #[refineable]
514    pub overflow: Point<Overflow>,
515    /// How much space (in points) should be reserved for the scrollbars of `Overflow::Scroll` and `Overflow::Auto` nodes.
516    pub scrollbar_width: AbsoluteLength,
517    /// Whether both x and y axis should be scrollable at the same time.
518    pub allow_concurrent_scroll: bool,
519    /// Whether scrolling should be restricted to the input gesture's axis.
520    ///
521    /// Pixel-based scroll gestures are locked to their initially dominant axis. The lock may be
522    /// released when the gesture changes direction strongly. Touch phases delimit gestures when
523    /// available, with a timeout fallback for platforms that only emit moved events.
524    ///
525    /// This also prevents input from being remapped to another axis. For example, horizontal input
526    /// will not scroll a container that only has vertical overflow enabled. Mouse wheel platforms
527    /// typically report ordinary wheel input on the Y axis and Shift-modified input on the X axis.
528    ///
529    /// ## Motivation
530    ///
531    /// On the web when scrolling with the mouse wheel, scrolling up and down will always scroll the Y axis, even when
532    /// the mouse is over a horizontally-scrollable element.
533    ///
534    /// The only way to scroll horizontally is to hold down `Shift` while scrolling, which then changes the scroll axis
535    /// to the X axis.
536    ///
537    /// Currently, GPUI operates differently from the web in that it will scroll an element in either the X or Y axis
538    /// when scrolling with just the mouse wheel. This causes problems when scrolling in a vertical list that contains
539    /// horizontally-scrollable elements, as when you get to the horizontally-scrollable elements the scroll will be
540    /// hijacked.
541    ///
542    /// Ideally we would match the web's behavior and not have a need for this, but right now we're adding this opt-in
543    /// style property to limit the potential blast radius.
544    pub restrict_scroll_to_axis: bool,
545
546    // Position properties
547    /// What should the `position` value of this struct use as a base offset?
548    pub position: Position,
549    /// How should the position of this element be tweaked relative to the layout defined?
550    #[refineable]
551    pub inset: Edges<Length>,
552
553    // Size properties
554    /// Sets the initial size of the item
555    #[refineable]
556    pub size: Size<Length>,
557    /// Controls the minimum size of the item
558    #[refineable]
559    pub min_size: Size<Length>,
560    /// Controls the maximum size of the item
561    #[refineable]
562    pub max_size: Size<Length>,
563    /// Sets the preferred aspect ratio for the item. The ratio is calculated as width divided by height.
564    pub aspect_ratio: Option<f32>,
565
566    // Spacing Properties
567    /// How large should the margin be on each side?
568    #[refineable]
569    pub margin: Edges<Length>,
570    /// How large should the padding be on each side?
571    #[refineable]
572    pub padding: Edges<DefiniteLength>,
573    /// How large should the border be on each side?
574    #[refineable]
575    pub border_widths: Edges<AbsoluteLength>,
576
577    // Alignment properties
578    /// How this node's children aligned in the cross/block axis?
579    pub align_items: Option<AlignItems>,
580    /// How this node should be aligned in the cross/block axis. Falls back to the parents [`AlignItems`] if not set
581    pub align_self: Option<AlignSelf>,
582    /// How should content contained within this item be aligned in the cross/block axis
583    pub align_content: Option<AlignContent>,
584    /// How should contained within this item be aligned in the main/inline axis
585    pub justify_content: Option<JustifyContent>,
586    /// How large should the gaps between items in a flex container be?
587    #[refineable]
588    pub gap: Size<DefiniteLength>,
589
590    // Flexbox properties
591    /// Which direction does the main axis flow in?
592    pub flex_direction: FlexDirection,
593    /// Should elements wrap, or stay in a single line?
594    pub flex_wrap: FlexWrap,
595    /// Sets the initial main axis size of the item
596    pub flex_basis: Length,
597    /// 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.
598    pub flex_grow: f32,
599    /// 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.
600    pub flex_shrink: f32,
601    /// CSS `order`: a flex or grid item is laid out in ascending order, ties in document order.
602    /// Painting, hit-testing and focus order keep document order.
603    pub vn_order: i32,
604    /// CSS `object-position` of an image painted in this box; `None` keeps
605    /// [`ObjectFit::get_bounds`]'s placement.
606    pub vn_object_position: Option<ObjectPosition>,
607
608    /// The fill color of this element
609    pub background: Option<Fill>,
610
611    /// Extra background layers painted OVER [`Style::background`], bottom layer
612    /// first — CSS's `background-image` stack, which sits above
613    /// `background-color`.
614    ///
615    /// One quad per layer rather than a layer array inside the quad: painter's
616    /// order already composites them in the right sequence, the scene's sort
617    /// and cull need no new concept, and nothing about the shader changes. The
618    /// cost is one extra primitive per layer, which is why a caller is expected
619    /// to keep the stack short.
620    ///
621    /// CSS lists layers top-first; this vector is bottom-first, so the mapper
622    /// reverses.
623    pub background_layers: Vec<Background>,
624
625    /// The border color of this element
626    pub border_color: Option<Hsla>,
627
628    /// CSS side colours override the shared colour independently.
629    #[refineable]
630    pub vn_border_colors: Edges<Option<Hsla>>,
631
632    /// The border style of this element
633    pub border_style: BorderStyle,
634
635    /// The radius of the corners of this element
636    #[refineable]
637    pub corner_radii: Corners<AbsoluteLength>,
638
639    /// vue-native fork: a CSS corner radius `corner_radii` cannot hold. That is a
640    /// percentage of the box, a `calc()` with one, or an elliptical `a / b`
641    /// corner. Where a corner has one, it replaces that corner's
642    /// `corner_radii`, and it resolves against the box at paint
643    /// ([`Style::corner_radii_for`]). vn-css writes both fields for every
644    /// corner it maps, so the later declaration wins whichever it used.
645    #[refineable]
646    pub vn_corner_radii: Corners<Option<VnCornerRadius>>,
647
648    /// Box shadow of the element
649    pub box_shadow: Vec<BoxShadow>,
650
651    /// vue-native fork: draw the outer shadows under the border box too.
652    ///
653    /// CSS clips an outer `box-shadow` to the outside of the border box (CSS
654    /// Backgrounds 3 §7.1): the shadow is cast as if the box were opaque, so
655    /// a translucent background shows what is behind the element, not the
656    /// shadow. [`Window::paint_drop_shadows`] does that by default. This
657    /// switch is for a shadow that stands in for the element's own painting:
658    /// vue-native draws `filter: blur()` on a solid box as the box's own
659    /// Gaussian shadow, whose middle must stay filled.
660    pub vn_shadow_under_box: bool,
661
662    /// CSS `backdrop-filter: blur(<length>)`: blur everything already painted
663    /// behind this element's border box, clipped to `corner_radii`.
664    ///
665    /// `None` (and a non-positive radius) means no backdrop filter. Only the
666    /// `blur()` filter function is modelled; the rest of the CSS filter
667    /// function list is not.
668    pub backdrop_blur: Option<Pixels>,
669
670    /// The `--shading: <effect>(<args>)` custom property: shade this element's
671    /// border box with one of the built-in effect pipelines.
672    ///
673    /// `None` means the property was never declared. `--shading: none` is
674    /// [`EffectSpec::NONE`] — a *value*, because a refinement cannot spell
675    /// "explicitly nothing" and that is what has to cancel an effect declared
676    /// by an earlier rule in the cascade. Same shape as `backdrop-filter: none`
677    /// mapping to a 0px radius.
678    ///
679    /// Deliberate divergence from CSS, documented for authors: a browser
680    /// *inherits* custom properties down the subtree. vue-native applies
681    /// `--shading` to the declaring element only — inheriting a GPU effect into
682    /// every descendant is never what an author means, and a browser ignores
683    /// the property entirely anyway, so nothing renders differently there.
684    pub vn_effect: Option<EffectSpec>,
685
686    /// A `--shading` transition between different effects: the outgoing one,
687    /// painted beneath `vn_effect` while they cross-fade.
688    pub vn_effect_fade: Option<EffectCrossFade>,
689
690    /// CSS `transform`: rotate, scale and translate this element's PAINTED
691    /// output — its background, borders, shadows, text and its whole subtree —
692    /// about its own centre, changing no layout at all.
693    ///
694    /// `None` means the property was never declared; [`TransformSpec::IDENTITY`]
695    /// is `transform: none`, a *value*, because a refinement cannot spell
696    /// "explicitly nothing" and that is what has to cancel a transform declared
697    /// by an earlier rule in the cascade. Same shape as `vn_effect` above, and
698    /// as `backdrop-filter: none` mapping to a 0px radius.
699    ///
700    /// Layout is untouched on purpose, and that is the browser's rule rather
701    /// than a shortcut: a transformed element still occupies exactly the box it
702    /// laid out in, its siblings do not move, and its scroll container does not
703    /// grow. It also means `translate()` here is NOT interchangeable with a
704    /// margin offset — which is the divergence this field exists to retire.
705    ///
706    /// Hit-testing follows the picture: a hitbox records the matrix in force
707    /// when it was inserted and the pointer is mapped back through the inverse,
708    /// so a rotated button is clickable where it is *drawn*.
709    pub vn_transform: Option<TransformSpec>,
710
711    /// The text style of this element
712    #[refineable]
713    pub text: TextStyleRefinement,
714
715    /// The mouse cursor style shown when the mouse pointer is over an element.
716    pub mouse_cursor: Option<CursorStyle>,
717
718    /// The opacity of this element
719    pub opacity: Option<f32>,
720
721    /// The grid columns of this element
722    /// Roughly equivalent to the Tailwind `grid-cols-<number>`
723    pub grid_cols: Option<GridTemplate>,
724
725    /// The row span of this element
726    /// Equivalent to the Tailwind `grid-rows-<number>`
727    pub grid_rows: Option<GridTemplate>,
728
729    /// The grid location of this element
730    pub grid_location: Option<GridLocation>,
731
732    /// CSS `grid-template-columns` as an ARBITRARY track list — `1fr auto`,
733    /// `minmax(0, 1fr) 200px`, `repeat(3, 1fr)` (expanded by the caller).
734    ///
735    /// Takes precedence over [`Style::grid_cols`], which stays as the cheap
736    /// `repeat(N, …)` shorthand the `Styled` helpers write. `None` means "this
737    /// element declared no track list", not "no columns".
738    pub vn_grid_cols: Option<Vec<GridTrack>>,
739
740    /// CSS `grid-template-rows` as an arbitrary track list. See
741    /// [`Style::vn_grid_cols`].
742    pub vn_grid_rows: Option<Vec<GridTrack>>,
743
744    /// The `repeat(auto-fill | auto-fit, …)` run of [`Style::vn_grid_cols`],
745    /// if it has one. Meaningless without that list.
746    pub vn_grid_cols_auto: Option<GridAutoRepeat>,
747
748    /// The `repeat(auto-fill | auto-fit, …)` run of [`Style::vn_grid_rows`].
749    pub vn_grid_rows_auto: Option<GridAutoRepeat>,
750
751    /// CSS `grid-auto-columns`: a repeating pattern for implicit column tracks.
752    pub vn_grid_auto_cols: Option<Vec<GridTrack>>,
753
754    /// CSS `grid-auto-rows`: a repeating pattern for implicit row tracks.
755    pub vn_grid_auto_rows: Option<Vec<GridTrack>>,
756
757    /// CSS `grid-auto-flow` — the direction the auto-placement algorithm fills,
758    /// and whether it packs densely.
759    pub vn_grid_auto_flow: Option<GridAutoFlow>,
760
761    /// CSS `justify-items` — the inline-axis alignment this container gives its
762    /// children. (`align_items` is the block axis; taffy honours both, gpui only
763    /// ever exposed the second.)
764    pub vn_justify_items: Option<AlignItems>,
765
766    /// CSS `justify-self` — this item's own inline-axis alignment, overriding
767    /// its container's `justify-items`.
768    pub vn_justify_self: Option<AlignSelf>,
769
770    /// CSS `outline` — a ring painted OUTSIDE the border box that takes no
771    /// layout space at all, which is what makes it (and not a border) the right
772    /// primitive for a focus indicator.
773    ///
774    /// gpui has no outline in its scene; this is painted as one extra
775    /// border-only quad at dilated bounds, after the element's own border, so it
776    /// lands on top of the element and outside it. `None` = never declared.
777    pub vn_outline: Option<Outline>,
778
779    /// vue-native fork: CSS `mask` in the one shape the paint path can cut,
780    /// the gradient-border idiom. That is two opaque layers, the top one
781    /// clipped to the content box, composited with `exclude`:
782    /// `mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
783    /// mask-composite: exclude`. What is left visible is the ring of padding
784    /// and border around the content box.
785    ///
786    /// When set, the background and its layers paint only in that ring, as one
787    /// quad each whose border widths are the border plus the padding
788    /// (`color::BG_RING`). The border lies inside the ring and paints as
789    /// usual. Not painted at all: the outer shadows and the outline, which lie
790    /// outside the border box and which the mask cuts entirely, and the inset
791    /// shadows, backdrop blur and effect quads, which the ring would show only
792    /// a strip of. The children are NOT masked. vn-tree says so when there
793    /// are any. A
794    /// percentage padding resolves against the element's own width here,
795    /// not its containing block's.
796    pub vn_mask_ring: bool,
797
798    /// vue-native fork: CSS `clip-path`, in the shapes a rounded content
799    /// mask carries ([`VnClipPath`]). It clips the element's whole painting,
800    /// its shadows, background, border, outline and subtree, and its hit
801    /// test, inside its `transform`.
802    pub vn_clip_path: VnClipPath,
803
804    /// SVG color filtering of the whole painted subtree.
805    pub vn_color_matrix: Option<crate::VnColorMatrix>,
806
807    /// vue-native fork: paint this element into the snapshot of this id
808    /// instead of the page ([`Window::vn_with_capture`]).
809    pub vn_capture: Option<u64>,
810
811    /// vue-native fork: paint the subtree into an isolated group, so a
812    /// `plus-lighter` composite inside blends with the group only.
813    pub vn_isolate: bool,
814
815    /// CSS backgrounds painted through the descendant glyph alpha, not the box.
816    pub vn_text_fill: Option<VnTextFill>,
817
818    /// CSS `mask` over the element's whole painting, inside its `clip-path`.
819    pub vn_mask: Option<VnMask>,
820
821    /// Whether to draw a red debugging outline around this element
822    #[cfg(debug_assertions)]
823    pub debug: bool,
824
825    /// Whether to draw a red debugging outline around this element and all of its conforming children
826    #[cfg(debug_assertions)]
827    pub debug_below: bool,
828}
829
830impl Styled for StyleRefinement {
831    fn style(&mut self) -> &mut StyleRefinement {
832        self
833    }
834}
835
836impl StyleRefinement {
837    /// The grid location of this element
838    pub fn grid_location_mut(&mut self) -> &mut GridLocation {
839        self.grid_location.get_or_insert_default()
840    }
841}
842
843/// The value of the visibility property, similar to the CSS property `visibility`
844#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
845#[cfg_attr(feature = "schemars", derive(JsonSchema))]
846pub enum Visibility {
847    /// The element should be drawn as normal.
848    #[default]
849    Visible,
850    /// The element should not be drawn, but should still take up space in the layout.
851    Hidden,
852}
853
854/// The possible values of the box-shadow property
855#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
856#[cfg_attr(feature = "schemars", derive(JsonSchema))]
857pub struct BoxShadow {
858    /// What color should the shadow have?
859    pub color: Hsla,
860    /// How should it be offset from its element?
861    pub offset: Point<Pixels>,
862    /// How much should the shadow be blurred?
863    pub blur_radius: Pixels,
864    /// How much should the shadow spread?
865    pub spread_radius: Pixels,
866    /// Whether this is an inset shadow (drawn inside the element's bounds).
867    pub inset: bool,
868}
869
870/// One CSS `text-shadow`, painted beneath the glyphs it is attached to.
871#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
872#[cfg_attr(feature = "schemars", derive(JsonSchema))]
873pub struct TextShadow {
874    /// `None` is CSS `currentColor`: the color of the text it shadows.
875    pub color: Option<Hsla>,
876    /// The offset from the glyphs.
877    pub offset: Point<Pixels>,
878    /// The CSS blur radius: a Gaussian blur with a standard deviation of half of it.
879    pub blur_radius: Pixels,
880}
881
882impl BoxShadow {
883    /// Creates a new [`BoxShadow`] with the given offset and color, matching the order
884    /// of the CSS `box-shadow` property. Use the builder methods to set blur radius,
885    /// spread radius, and inset.
886    pub fn new(offset_x: Pixels, offset_y: Pixels, color: Hsla) -> Self {
887        Self {
888            color,
889            offset: point(offset_x, offset_y),
890            blur_radius: px(0.),
891            spread_radius: px(0.),
892            inset: false,
893        }
894    }
895
896    /// Sets the shadow blur radius.
897    pub fn blur_radius(mut self, blur_radius: Pixels) -> Self {
898        self.blur_radius = blur_radius;
899        self
900    }
901
902    /// Sets the shadow spread radius.
903    pub fn spread_radius(mut self, spread_radius: Pixels) -> Self {
904        self.spread_radius = spread_radius;
905        self
906    }
907
908    /// Marks the shadow as inset (drawn inside the element's bounds).
909    pub fn inset(mut self) -> Self {
910        self.inset = true;
911        self
912    }
913}
914
915/// How to handle whitespace in text
916#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
917#[cfg_attr(feature = "schemars", derive(JsonSchema))]
918pub enum WhiteSpace {
919    /// Normal line wrapping when text overflows the width of the element
920    #[default]
921    Normal,
922    /// No line wrapping, text will overflow the width of the element
923    Nowrap,
924}
925
926/// vue-native fork: CSS `overflow-wrap` (CSS Text 3 §5.5). May a line break
927/// inside a word that does not fit on a line of its own?
928#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
929#[cfg_attr(feature = "schemars", derive(JsonSchema))]
930pub enum OverflowWrap {
931    /// Lines break only at soft wrap opportunities. A word wider than the
932    /// line overflows it.
933    #[default]
934    Normal,
935    /// A word that does not fit on a line of its own is broken where it
936    /// overflows. The min-content size still counts the word whole.
937    BreakWord,
938    /// As `BreakWord`, and the min-content size counts those breaks too, so a
939    /// flex item or a `min-content` box can be as narrow as one character.
940    Anywhere,
941}
942
943/// vue-native fork: CSS `word-break` (CSS Text 3 §5.2).
944#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
945#[cfg_attr(feature = "schemars", derive(JsonSchema))]
946pub enum WordBreak {
947    /// The usual soft wrap opportunities.
948    #[default]
949    Normal,
950    /// A line may break between any two letters, and the min-content size
951    /// counts those breaks.
952    BreakAll,
953    /// CJK letters are kept together like the letters of any other word: no
954    /// break between two of them.
955    KeepAll,
956    /// The legacy keyword: `normal` with `overflow-wrap: anywhere`, whatever
957    /// `overflow-wrap` says.
958    BreakWord,
959}
960
961/// vue-native fork: CSS `hyphens` (CSS Text 3 §6.1). There is no hyphenation
962/// dictionary, so `auto` is the caller's to map to `Manual`.
963#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
964#[cfg_attr(feature = "schemars", derive(JsonSchema))]
965pub enum Hyphens {
966    /// A soft hyphen (U+00AD) is no break opportunity.
967    None,
968    /// A line may break after a soft hyphen, and shows a hyphen there.
969    #[default]
970    Manual,
971}
972
973/// vue-native fork: the rules a text breaks its lines under, from its style
974/// ([`TextStyle::wrap`]). Part of the line layout cache's key.
975#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
976pub struct TextWrap {
977    /// CSS `overflow-wrap`.
978    pub overflow_wrap: OverflowWrap,
979    /// CSS `word-break`.
980    pub word_break: WordBreak,
981    /// CSS `hyphens`.
982    pub hyphens: Hyphens,
983}
984
985impl TextWrap {
986    /// gpui's rules before the fork took CSS's: a word that does not fit on
987    /// a line is broken where it overflows. What [`crate::WindowTextSystem::shape_text`]
988    /// keeps for its callers, a text field among them (a `<textarea>` is
989    /// `overflow-wrap: break-word` in every browser's UA sheet).
990    pub const BREAK_WORD: Self = Self {
991        overflow_wrap: OverflowWrap::BreakWord,
992        word_break: WordBreak::Normal,
993        hyphens: Hyphens::Manual,
994    };
995
996    /// May a word that does not fit be broken where it overflows?
997    pub(crate) fn breaks_words(&self) -> bool {
998        self.overflow_wrap != OverflowWrap::Normal || self.word_break == WordBreak::BreakWord
999    }
1000
1001    /// Do those breaks count for the min-content size?
1002    pub(crate) fn min_content_breaks_words(&self) -> bool {
1003        self.overflow_wrap == OverflowWrap::Anywhere || self.word_break == WordBreak::BreakWord
1004    }
1005}
1006
1007/// How to truncate text that overflows the width of the element
1008#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1009#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1010pub enum TextOverflow {
1011    /// Truncate the text at the end when it doesn't fit, and represent this truncation by
1012    /// displaying the provided string (e.g., "very long te…").
1013    Truncate(SharedString),
1014    /// Truncate the text at the start when it doesn't fit, and represent this truncation by
1015    /// displaying the provided string at the beginning (e.g., "…ong text here").
1016    /// Typically more adequate for file paths where the end is more important than the beginning.
1017    TruncateStart(SharedString),
1018    /// Truncate the text in the middle when it doesn't fit, preserving both the start and end
1019    /// of the string (e.g., "long fi…name.rs"). Useful for filenames where both the prefix
1020    /// and the extension are important context.
1021    TruncateMiddle(SharedString),
1022}
1023
1024/// How to align text within the element
1025#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1026#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1027pub enum TextAlign {
1028    /// Align the text to the left of the element
1029    #[default]
1030    Left,
1031
1032    /// Center the text within the element
1033    Center,
1034
1035    /// Align the text to the right of the element
1036    Right,
1037}
1038
1039/// Paints a mask's layers into the border box it is given. With a tint (always
1040/// opaque), the layers paint in that colour as the element's whole picture
1041/// ([`VnMask::tint_leaf`]).
1042pub type VnMaskPainter = std::rc::Rc<dyn Fn(Bounds<Pixels>, Option<Hsla>, &mut Window, &mut App)>;
1043
1044/// CSS `mask`: the element's painting, subtree included, is multiplied by the
1045/// alpha (or luminance) of what `paint` draws over its border box.
1046#[derive(Clone, Default, Serialize, Deserialize)]
1047#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1048pub struct VnMask {
1049    /// `mask-mode: luminance`; alpha otherwise.
1050    pub luminance: bool,
1051    /// The element paints nothing but its background, and every layer can be
1052    /// drawn tinted: a solid background then paints as the mask in its colour,
1053    /// without an isolated layer.
1054    pub tint_leaf: bool,
1055    /// Identifies what `paint` draws, for comparing styles.
1056    pub key: u64,
1057    /// Draws the layers; no painter, no mask.
1058    #[serde(skip)]
1059    #[cfg_attr(feature = "schemars", schemars(skip))]
1060    pub paint: Option<VnMaskPainter>,
1061}
1062
1063impl std::fmt::Debug for VnMask {
1064    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1065        f.debug_struct("VnMask")
1066            .field("luminance", &self.luminance)
1067            .field("tint_leaf", &self.tint_leaf)
1068            .field("key", &self.key)
1069            .finish_non_exhaustive()
1070    }
1071}
1072
1073impl PartialEq for VnMask {
1074    fn eq(&self, other: &Self) -> bool {
1075        (self.luminance, self.tint_leaf, self.key) == (other.luminance, other.tint_leaf, other.key)
1076    }
1077}
1078
1079/// A CSS background stack clipped to the element's descendant text.
1080#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1081#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1082pub struct VnTextFill {
1083    /// Stable element identity; reopened/deferred text shares one alpha mask.
1084    pub group_id: u64,
1085    /// Backgrounds, bottom first, retaining their gradient and tile parameters.
1086    pub backgrounds: Vec<Background>,
1087}
1088
1089/// A text background resolved against its element, in logical CSS pixels.
1090/// Carried in TextStyle so deferred drawing and paint-cache keys retain it.
1091#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1092#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1093pub struct VnTextPaint {
1094    /// The authored stack.
1095    pub fill: VnTextFill,
1096    /// The background positioning box.
1097    pub bounds: [f32; 4],
1098    /// Inverse device-space element transform, row major followed by translation.
1099    pub inverse: [f32; 6],
1100    /// Device pixels per logical CSS pixel.
1101    pub scale_factor: f32,
1102    /// The owner scope's geometry, shared by every descendant glyph.
1103    #[serde(skip)]
1104    #[cfg_attr(feature = "schemars", schemars(skip))]
1105    pub geometry: Arc<crate::VnClipGeometry>,
1106    /// The owner scope's outer mask. Glyphs retain their local child masks.
1107    #[serde(skip)]
1108    #[cfg_attr(feature = "schemars", schemars(skip))]
1109    pub content_mask: ContentMask<crate::ScaledPixels>,
1110}
1111
1112/// The properties that can be used to style text in GPUI
1113#[derive(Refineable, Clone, Debug, PartialEq)]
1114#[refineable(Debug, PartialEq, Serialize, Deserialize)]
1115#[cfg_attr(feature = "schemars", refineable(JsonSchema))]
1116pub struct TextStyle {
1117    /// The color of the text
1118    pub color: Hsla,
1119
1120    /// Background clipped to transparent glyphs in this text scope.
1121    pub vn_text_paint: Option<Arc<VnTextPaint>>,
1122
1123    /// The font family to use
1124    pub font_family: SharedString,
1125
1126    /// The font features to use
1127    pub font_features: FontFeatures,
1128
1129    /// The fallback fonts to use
1130    pub font_fallbacks: Option<FontFallbacks>,
1131
1132    /// The font size to use, in pixels or rems.
1133    pub font_size: AbsoluteLength,
1134
1135    /// The line height to use, in pixels or fractions
1136    pub line_height: DefiniteLength,
1137
1138    /// The font weight, e.g. bold
1139    pub font_weight: FontWeight,
1140
1141    /// The font style, e.g. italic
1142    pub font_style: FontStyle,
1143
1144    /// The background color of the text
1145    pub background_color: Option<Hsla>,
1146
1147    /// The underline style of the text
1148    pub underline: Option<UnderlineStyle>,
1149
1150    /// The strikethrough style of the text
1151    pub strikethrough: Option<StrikethroughStyle>,
1152
1153    /// How to handle whitespace in the text
1154    pub white_space: WhiteSpace,
1155
1156    /// The text should be truncated if it overflows the width of the element
1157    pub text_overflow: Option<TextOverflow>,
1158
1159    /// How the text should be aligned within the element
1160    pub text_align: TextAlign,
1161
1162    /// The number of lines to display before truncating the text
1163    pub line_clamp: Option<usize>,
1164
1165    /// Extra space after each typographic character unit — CSS
1166    /// `letter-spacing`. Already resolved to pixels: `em`-relative tracking is
1167    /// a function of the font size, which the caller has and this does not.
1168    pub letter_spacing: Pixels,
1169
1170    /// Extra space after each word separator — CSS `word-spacing`.
1171    pub word_spacing: Pixels,
1172
1173    /// vue-native fork: CSS `overflow-wrap`. Initial `normal`, as in CSS.
1174    pub overflow_wrap: OverflowWrap,
1175
1176    /// vue-native fork: CSS `word-break`.
1177    pub word_break: WordBreak,
1178
1179    /// vue-native fork: CSS `hyphens`.
1180    pub hyphens: Hyphens,
1181
1182    /// vue-native fork: CSS `text-shadow`, first on top.
1183    pub text_shadow: Vec<TextShadow>,
1184}
1185
1186impl Default for TextStyle {
1187    fn default() -> Self {
1188        TextStyle {
1189            color: black(),
1190            vn_text_paint: None,
1191            // todo(linux) make this configurable or choose better default
1192            font_family: ".SystemUIFont".into(),
1193            font_features: FontFeatures::default(),
1194            font_fallbacks: None,
1195            font_size: rems(1.).into(),
1196            line_height: phi(),
1197            font_weight: FontWeight::default(),
1198            font_style: FontStyle::default(),
1199            background_color: None,
1200            underline: None,
1201            strikethrough: None,
1202            white_space: WhiteSpace::Normal,
1203            text_overflow: None,
1204            text_align: TextAlign::default(),
1205            line_clamp: None,
1206            letter_spacing: px(0.),
1207            word_spacing: px(0.),
1208            overflow_wrap: OverflowWrap::default(),
1209            word_break: WordBreak::default(),
1210            hyphens: Hyphens::default(),
1211            text_shadow: Vec::new(),
1212        }
1213    }
1214}
1215
1216impl TextStyle {
1217    /// vue-native fork: the line-breaking rules of this style.
1218    pub fn wrap(&self) -> TextWrap {
1219        TextWrap {
1220            overflow_wrap: self.overflow_wrap,
1221            word_break: self.word_break,
1222            hyphens: self.hyphens,
1223        }
1224    }
1225
1226    /// Create a new text style with the given highlighting applied.
1227    pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
1228        let style = style.into();
1229        if let Some(weight) = style.font_weight {
1230            self.font_weight = weight;
1231        }
1232        if let Some(style) = style.font_style {
1233            self.font_style = style;
1234        }
1235
1236        if let Some(color) = style.color {
1237            self.color = self.color.blend(color);
1238        }
1239
1240        if let Some(factor) = style.fade_out {
1241            self.color.fade_out(factor);
1242        }
1243
1244        if let Some(background_color) = style.background_color {
1245            self.background_color = Some(background_color);
1246        }
1247
1248        if let Some(underline) = style.underline {
1249            self.underline = Some(underline);
1250        }
1251
1252        if let Some(strikethrough) = style.strikethrough {
1253            self.strikethrough = Some(strikethrough);
1254        }
1255
1256        self
1257    }
1258
1259    /// Get the font configured for this text style.
1260    pub fn font(&self) -> Font {
1261        Font {
1262            family: self.font_family.clone(),
1263            features: self.font_features.clone(),
1264            fallbacks: self.font_fallbacks.clone(),
1265            weight: self.font_weight,
1266            style: self.font_style,
1267        }
1268    }
1269
1270    /// Returns the rounded line height in pixels.
1271    pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
1272        self.line_height.to_pixels(self.font_size, rem_size).round()
1273    }
1274
1275    /// Convert this text style into a [`TextRun`], for the given length of the text.
1276    pub fn to_run(&self, len: usize) -> TextRun {
1277        TextRun {
1278            len,
1279            font: Font {
1280                family: self.font_family.clone(),
1281                features: self.font_features.clone(),
1282                fallbacks: self.font_fallbacks.clone(),
1283                weight: self.font_weight,
1284                style: self.font_style,
1285            },
1286            color: self.color,
1287            background_color: self.background_color,
1288            underline: self.underline,
1289            strikethrough: self.strikethrough,
1290            tracking: self.letter_spacing,
1291            word_spacing: self.word_spacing,
1292            text_shadow: self.text_shadow.clone(),
1293        }
1294    }
1295}
1296
1297/// A highlight style to apply, similar to a `TextStyle` except
1298/// for a single font, uniformly sized and spaced text.
1299#[derive(Copy, Clone, Debug, Default, PartialEq)]
1300pub struct HighlightStyle {
1301    /// The color of the text
1302    pub color: Option<Hsla>,
1303
1304    /// The font weight, e.g. bold
1305    pub font_weight: Option<FontWeight>,
1306
1307    /// The font style, e.g. italic
1308    pub font_style: Option<FontStyle>,
1309
1310    /// The background color of the text
1311    pub background_color: Option<Hsla>,
1312
1313    /// The underline style of the text
1314    pub underline: Option<UnderlineStyle>,
1315
1316    /// The underline style of the text
1317    pub strikethrough: Option<StrikethroughStyle>,
1318
1319    /// Similar to the CSS `opacity` property, this will cause the text to be less vibrant.
1320    pub fade_out: Option<f32>,
1321}
1322
1323impl Eq for HighlightStyle {}
1324
1325impl Hash for HighlightStyle {
1326    fn hash<H: Hasher>(&self, state: &mut H) {
1327        self.color.hash(state);
1328        self.font_weight.hash(state);
1329        self.font_style.hash(state);
1330        self.background_color.hash(state);
1331        self.underline.hash(state);
1332        self.strikethrough.hash(state);
1333        state.write_u32(u32::from_be_bytes(
1334            self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
1335        ));
1336    }
1337}
1338
1339/// The one colour that best stands in for a background — the fill itself when
1340/// it is solid, and a gradient's first live stop otherwise. Used for the
1341/// transparent border that keeps a fill's antialiased corner from seaming.
1342fn representative_color(background: &Background) -> Hsla {
1343    match background.tag {
1344        BackgroundTag::Solid | BackgroundTag::PatternSlash | BackgroundTag::Checkerboard => {
1345            background.solid
1346        }
1347        BackgroundTag::LinearGradient
1348        | BackgroundTag::RadialGradient
1349        | BackgroundTag::ConicGradient => background
1350            .live_stops()
1351            .first()
1352            .map(|stop| stop.color)
1353            .unwrap_or_default(),
1354    }
1355}
1356
1357impl Style {
1358    /// Returns true if the style is visible and the background is opaque.
1359    pub fn has_opaque_background(&self) -> bool {
1360        self.background
1361            .as_ref()
1362            .is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
1363    }
1364
1365    /// Get the text style in this element style.
1366    pub fn text_style(&self) -> Option<&TextStyleRefinement> {
1367        if self.text.is_some() {
1368            Some(&self.text)
1369        } else {
1370            None
1371        }
1372    }
1373
1374    /// Text refinements with the background positioning box resolved for paint.
1375    /// Layout uses `text_style` because this scope must not change glyph shaping.
1376    pub fn text_style_for_bounds(&self, bounds: Bounds<Pixels>, window: &Window) -> Option<TextStyleRefinement> {
1377        let mut text = self.text.clone();
1378        if let Some(fill) = &self.vn_text_fill {
1379            text.vn_text_paint = Some(window.vn_text_paint(fill.clone(), bounds));
1380        }
1381        text.is_some().then_some(text)
1382    }
1383
1384    /// vue-native fork: the corner radii this style paints on a box of `size`,
1385    /// percentages, the overlap rule and all. See [`vn_resolve_corner_radii`].
1386    pub fn corner_radii_for(&self, size: Size<Pixels>, rem_size: Pixels) -> Corners<Pixels> {
1387        vn_resolve_corner_radii(&self.corner_radii, &self.vn_corner_radii, size, rem_size)
1388    }
1389
1390    /// Get the content mask for this element style, based on the given bounds.
1391    /// If the element does not hide its overflow, this will return `None`.
1392    pub fn overflow_mask(
1393        &self,
1394        bounds: Bounds<Pixels>,
1395        rem_size: Pixels,
1396    ) -> Option<ContentMask<Pixels>> {
1397        match self.overflow {
1398            Point {
1399                x: Overflow::Visible,
1400                y: Overflow::Visible,
1401            } => None,
1402            _ => {
1403                let mut min = bounds.origin;
1404                let mut max = bounds.bottom_right();
1405                let border_box = bounds;
1406
1407                // vue-native fork: side by side, since each side can have its
1408                // own colour (`vn_border_colors`). Only the shared colour was
1409                // asked, so a box whose borders were all coloured per side
1410                // clipped to its border box and its content painted over them.
1411                let painted = self
1412                    .vn_resolved_border_colors()
1413                    .map(|color| !color.is_transparent());
1414                if painted.left {
1415                    min.x += self.border_widths.left.to_pixels(rem_size);
1416                }
1417                if painted.right {
1418                    max.x -= self.border_widths.right.to_pixels(rem_size);
1419                }
1420                if painted.top {
1421                    min.y += self.border_widths.top.to_pixels(rem_size);
1422                }
1423                if painted.bottom {
1424                    max.y -= self.border_widths.bottom.to_pixels(rem_size);
1425                }
1426
1427                let bounds = match (
1428                    self.overflow.x == Overflow::Visible,
1429                    self.overflow.y == Overflow::Visible,
1430                ) {
1431                    // x and y both visible
1432                    (true, true) => return None,
1433                    // x visible, y hidden
1434                    (true, false) => Bounds::from_corners(
1435                        point(min.x, bounds.origin.y),
1436                        point(max.x, bounds.bottom_right().y),
1437                    ),
1438                    // x hidden, y visible
1439                    (false, true) => Bounds::from_corners(
1440                        point(bounds.origin.x, min.y),
1441                        point(bounds.bottom_right().x, max.y),
1442                    ),
1443                    // both hidden
1444                    (false, false) => Bounds::from_corners(min, max),
1445                };
1446
1447                // vue-native fork: CSS clips overflow to the padding box's
1448                // ROUNDED shape, whose radii are the border radii less the
1449                // border widths. Each corner takes the larger of its two
1450                // borders off, a circle inside the elliptical corner CSS draws
1451                // for unequal ones. The insets are read off the mask's own
1452                // bounds, so a border the mask does not inset (a transparent
1453                // one, above) takes nothing off.
1454                let insets = Edges {
1455                    top: bounds.top() - border_box.top(),
1456                    right: border_box.right() - bounds.right(),
1457                    bottom: border_box.bottom() - bounds.bottom(),
1458                    left: bounds.left() - border_box.left(),
1459                };
1460                let outer = self.corner_radii_for(border_box.size, rem_size);
1461                let inner = |radius: Pixels, a: Pixels, b: Pixels| (radius - a.max(b)).max(px(0.));
1462                let corner_radii = Corners {
1463                    top_left: inner(outer.top_left, insets.top, insets.left),
1464                    top_right: inner(outer.top_right, insets.top, insets.right),
1465                    bottom_right: inner(outer.bottom_right, insets.bottom, insets.right),
1466                    bottom_left: inner(outer.bottom_left, insets.bottom, insets.left),
1467                }
1468                .clamp_radii_for_quad_size(bounds.size);
1469
1470                Some(ContentMask {
1471                    bounds,
1472                    corner_radii,
1473                })
1474            }
1475        }
1476    }
1477
1478    /// vue-native fork: the mask `clip-path` cuts this element's painting and
1479    /// hit test to ([`Style::vn_clip_path`]), for the border box `bounds`, in
1480    /// the element's own frame. `None` without a clip.
1481    ///
1482    /// A shape that is no rounded rectangle ([`Style::vn_clip_outline`])
1483    /// gives the rectangle around its outline here, which culls and cuts the
1484    /// isolated layer the outline is then composited through.
1485    pub fn vn_clip_mask(&self, bounds: Bounds<Pixels>, rem_size: Pixels) -> Option<ContentMask<Pixels>> {
1486        let clip = &self.vn_clip_path;
1487        let reference = match clip {
1488            VnClipPath::None => return None,
1489            VnClipPath::Polygon { .. } | VnClipPath::Path { .. } => {
1490                let outline = self.vn_clip_outline(bounds, rem_size)?;
1491                let rect = outline.control_bounds().unwrap_or(Bounds { origin: bounds.origin, size: Size::default() });
1492                return Some(ContentMask::rect(rect));
1493            }
1494            VnClipPath::Box(reference)
1495            | VnClipPath::Inset { reference, .. }
1496            | VnClipPath::Ellipse { reference, .. } => *reference,
1497        };
1498        let (rect, rounded) = self.vn_clip_box(reference, bounds, rem_size);
1499        let (w, h) = (rect.size.width, rect.size.height);
1500        let resolve = |length: &DefiniteLength, base: Pixels| length.to_pixels(AbsoluteLength::Pixels(base), rem_size);
1501        Some(match clip {
1502            VnClipPath::None | VnClipPath::Polygon { .. } | VnClipPath::Path { .. } => return None,
1503            VnClipPath::Box(_) => ContentMask { bounds: rect, corner_radii: rounded },
1504            VnClipPath::Inset { insets, radii, .. } => {
1505                // Chromium's `BasicShapeInset::GetPath`: the insets come off
1506                // the reference box, an empty side stays empty, and the radii
1507                // resolve against the reference box and are then scaled down
1508                // to fit the inset rectangle (css-backgrounds-3 §5.5).
1509                let [top, right, bottom, left] = insets;
1510                let (top, right) = (resolve(top, h), resolve(right, w));
1511                let (bottom, left) = (resolve(bottom, h), resolve(left, w));
1512                let shape = Bounds {
1513                    origin: point(rect.left() + left, rect.top() + top),
1514                    size: size((w - left - right).max(px(0.)), (h - top - bottom).max(px(0.))),
1515                };
1516                let pairs = radii.map(|r| {
1517                    let x = f32::from(resolve(&r.x, w)).max(0.);
1518                    let y = f32::from(resolve(&r.y, h)).max(0.);
1519                    (x, y)
1520                });
1521                let [tl, tr, br, bl] = pairs;
1522                let (sw, sh) = (f32::from(shape.size.width), f32::from(shape.size.height));
1523                let ratio = |side: f32, a: f32, b: f32| if a + b > side { side / (a + b) } else { 1. };
1524                let factor = ratio(sw, tl.0, tr.0)
1525                    .min(ratio(sw, bl.0, br.0))
1526                    .min(ratio(sh, tl.1, bl.1))
1527                    .min(ratio(sh, tr.1, br.1));
1528                let circle = |(x, y): (f32, f32)| px(x.min(y) * factor);
1529                let corner_radii = Corners {
1530                    top_left: circle(tl),
1531                    top_right: circle(tr),
1532                    bottom_right: circle(br),
1533                    bottom_left: circle(bl),
1534                }
1535                .clamp_radii_for_quad_size(shape.size);
1536                ContentMask { bounds: shape, corner_radii }
1537            }
1538            VnClipPath::Ellipse { center, radius, circle, .. } => {
1539                let (c, rx, ry) = vn_clip_ellipse(rect, center, radius, *circle, rem_size);
1540                let shape = Bounds { origin: point(c.x - rx, c.y - ry), size: size(rx * 2., ry * 2.) };
1541                // A circle is the rounded mask; an ellipse is its box here,
1542                // and its outline in an isolated layer.
1543                let corner_radii = if rx == ry { Corners::all(rx) } else { Corners::default() };
1544                ContentMask { bounds: shape, corner_radii }
1545            }
1546        })
1547    }
1548
1549    /// vue-native fork: the outline of a `clip-path` that is no rounded
1550    /// rectangle (`polygon()`, `path()`, an ellipse whose radii differ), laid
1551    /// against its reference box for the border box `bounds`, in the
1552    /// element's own frame. `None` for no clip and for a shape
1553    /// [`Style::vn_clip_mask`] carries alone. The element paints into an
1554    /// isolated layer composited through it ([`Window::vn_with_clip_shape`]).
1555    pub fn vn_clip_outline(&self, bounds: Bounds<Pixels>, rem_size: Pixels) -> Option<VnClipOutline> {
1556        let resolve = |length: &DefiniteLength, base: Pixels| {
1557            f32::from(length.to_pixels(AbsoluteLength::Pixels(base), rem_size))
1558        };
1559        match &self.vn_clip_path {
1560            VnClipPath::Polygon { reference, fill_rule, points } => {
1561                let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
1562                let (x0, y0) = (f32::from(rect.left()), f32::from(rect.top()));
1563                let (w, h) = (rect.size.width, rect.size.height);
1564                let mut verbs = Vec::with_capacity(points.len() + 1);
1565                for (i, [x, y]) in points.iter().enumerate() {
1566                    let p = [x0 + resolve(x, w), y0 + resolve(y, h)];
1567                    verbs.push(if i == 0 { VnPathVerb::MoveTo(p) } else { VnPathVerb::LineTo(p) });
1568                }
1569                if !verbs.is_empty() {
1570                    verbs.push(VnPathVerb::Close);
1571                }
1572                Some(VnClipOutline { fill_rule: *fill_rule, verbs })
1573            }
1574            VnClipPath::Path { reference, fill_rule, verbs } => {
1575                let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
1576                let (x0, y0) = (f32::from(rect.left()), f32::from(rect.top()));
1577                let at = |p: [f32; 2]| [p[0] + x0, p[1] + y0];
1578                let verbs = verbs
1579                    .iter()
1580                    .map(|v| match *v {
1581                        VnPathVerb::MoveTo(p) => VnPathVerb::MoveTo(at(p)),
1582                        VnPathVerb::LineTo(p) => VnPathVerb::LineTo(at(p)),
1583                        VnPathVerb::QuadTo(c, p) => VnPathVerb::QuadTo(at(c), at(p)),
1584                        VnPathVerb::CubicTo(c1, c2, p) => VnPathVerb::CubicTo(at(c1), at(c2), at(p)),
1585                        VnPathVerb::Close => VnPathVerb::Close,
1586                    })
1587                    .collect();
1588                Some(VnClipOutline { fill_rule: *fill_rule, verbs })
1589            }
1590            VnClipPath::Ellipse { reference, center, radius, circle } => {
1591                let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
1592                let (c, rx, ry) = vn_clip_ellipse(rect, center, radius, *circle, rem_size);
1593                if rx == ry {
1594                    return None;
1595                }
1596                // Four cubics, one per quadrant, k = 4/3 (sqrt(2) - 1).
1597                let (cx, cy, rx, ry) = (f32::from(c.x), f32::from(c.y), f32::from(rx), f32::from(ry));
1598                let (kx, ky) = (0.552_284_8 * rx, 0.552_284_8 * ry);
1599                use VnPathVerb::*;
1600                Some(VnClipOutline {
1601                    fill_rule: VnFillRule::NonZero,
1602                    verbs: vec![
1603                        MoveTo([cx + rx, cy]),
1604                        CubicTo([cx + rx, cy + ky], [cx + kx, cy + ry], [cx, cy + ry]),
1605                        CubicTo([cx - kx, cy + ry], [cx - rx, cy + ky], [cx - rx, cy]),
1606                        CubicTo([cx - rx, cy - ky], [cx - kx, cy - ry], [cx, cy - ry]),
1607                        CubicTo([cx + kx, cy - ry], [cx + rx, cy - ky], [cx + rx, cy]),
1608                        Close,
1609                    ],
1610                })
1611            }
1612            VnClipPath::None | VnClipPath::Box(_) | VnClipPath::Inset { .. } => None,
1613        }
1614    }
1615
1616    /// vue-native fork: a `clip-path` reference box and its rounded corners,
1617    /// for the border box `bounds`. Inside the border box a corner loses the
1618    /// larger of its two insets, as `overflow_mask` rounds the padding box;
1619    /// the margin box's grows by the larger margin, where it is rounded at
1620    /// all. A percentage padding or margin resolves against the element's own
1621    /// width, not its containing block's.
1622    fn vn_clip_box(&self, reference: VnClipBox, bounds: Bounds<Pixels>, rem_size: Pixels) -> (Bounds<Pixels>, Corners<Pixels>) {
1623        let outer = self.corner_radii_for(bounds.size, rem_size);
1624        let width = AbsoluteLength::Pixels(bounds.size.width);
1625        let edges = match reference {
1626            VnClipBox::Border => return (bounds, outer),
1627            VnClipBox::Margin => {
1628                let margin = |l: &Length| match l {
1629                    Length::Definite(l) => -l.to_pixels(width, rem_size),
1630                    Length::Auto => px(0.),
1631                };
1632                Edges {
1633                    top: margin(&self.margin.top),
1634                    right: margin(&self.margin.right),
1635                    bottom: margin(&self.margin.bottom),
1636                    left: margin(&self.margin.left),
1637                }
1638            }
1639            VnClipBox::Padding | VnClipBox::Content => {
1640                let border = self.border_widths.to_pixels(rem_size);
1641                if reference == VnClipBox::Padding {
1642                    border
1643                } else {
1644                    let padding = self.padding.to_pixels(size(width, width), rem_size);
1645                    Edges {
1646                        top: border.top + padding.top,
1647                        right: border.right + padding.right,
1648                        bottom: border.bottom + padding.bottom,
1649                        left: border.left + padding.left,
1650                    }
1651                }
1652            }
1653        };
1654        let rect = Bounds::from_corners(
1655            point(bounds.left() + edges.left, bounds.top() + edges.top),
1656            point(
1657                (bounds.right() - edges.right).max(bounds.left() + edges.left),
1658                (bounds.bottom() - edges.bottom).max(bounds.top() + edges.top),
1659            ),
1660        );
1661        // A negative inset is an outset (the margin box).
1662        let corner = |radius: Pixels, a: Pixels, b: Pixels| {
1663            if a < px(0.) || b < px(0.) {
1664                if radius > px(0.) { radius - a.min(b) } else { px(0.) }
1665            } else {
1666                (radius - a.max(b)).max(px(0.))
1667            }
1668        };
1669        let corner_radii = Corners {
1670            top_left: corner(outer.top_left, edges.top, edges.left),
1671            top_right: corner(outer.top_right, edges.top, edges.right),
1672            bottom_right: corner(outer.bottom_right, edges.bottom, edges.right),
1673            bottom_left: corner(outer.bottom_left, edges.bottom, edges.left),
1674        }
1675        .clamp_radii_for_quad_size(rect.size);
1676        (rect, corner_radii)
1677    }
1678
1679    /// The device-space matrix this style's CSS `transform` produces for an
1680    /// element laid out at `bounds`, or the identity when there is none.
1681    ///
1682    /// Shared by paint (which pushes it onto the primitives) and prepaint
1683    /// (which records it on the hitbox), so the picture and the hit test can
1684    /// never disagree about where the element is.
1685    pub fn transform_matrix(&self, bounds: Bounds<Pixels>, scale_factor: f32) -> TransformationMatrix
1686    {
1687        self.vn_transform
1688            .filter(|t| !t.is_identity())
1689            .map(|t| t.to_matrix(bounds, scale_factor))
1690            .unwrap_or_else(TransformationMatrix::unit)
1691    }
1692
1693    /// Paints the background of an element styled with this style.
1694    pub fn paint(
1695        &self,
1696        bounds: Bounds<Pixels>,
1697        window: &mut Window,
1698        cx: &mut App,
1699        continuation: impl FnOnce(&mut Window, &mut App),
1700    ) {
1701        // CSS `transform` applies to this element's whole painted output AND
1702        // to its subtree, so it is pushed around everything below — including
1703        // `continuation`, which is where the children paint. Layout has already
1704        // happened at this point and is deliberately not consulted again: a
1705        // transform never moves a box, only its picture.
1706        //
1707        // vue-native fork: `clip-path` cuts everything below too, in the
1708        // element's transformed frame (`Style::vn_clip_mask`).
1709        //
1710        // A shape that is no rounded rectangle paints into an isolated layer
1711        // composited through it (`Window::vn_with_clip_shape`), inside its
1712        // box's mask.
1713        // A captured element paints untransformed; its transform travels with
1714        // the capture (`Window::vn_with_capture`).
1715        let transformation = if self.vn_capture.is_some() {
1716            TransformationMatrix::unit()
1717        } else {
1718            self.transform_matrix(bounds, window.scale_factor())
1719        };
1720        let clip = self.vn_clip_mask(bounds, window.rem_size());
1721        let outline = self.vn_clip_outline(bounds, window.rem_size());
1722        let element = window.vn_take_effect_element();
1723        let paint = |window: &mut Window| {
1724            window.with_content_mask(clip, |window| {
1725                window.vn_with_clip_shape(outline.as_ref(), |window| {
1726                    if let Some(tint) = self.vn_mask_tint()
1727                        && let Some(paint) = self.vn_mask.as_ref().and_then(|mask| mask.paint.clone())
1728                    {
1729                        if !tint.is_transparent() {
1730                            window.with_element_opacity(Some(tint.a), |window| {
1731                                paint(bounds, Some(Hsla { a: 1., ..tint }), window, cx)
1732                            });
1733                        }
1734                        return continuation(window, cx);
1735                    }
1736                    window.vn_with_mask(self.vn_mask.as_ref(), bounds, cx, |window, cx| {
1737                        window.vn_with_color_matrix(self.vn_color_matrix, |window| {
1738                            window.vn_with_isolation(self.vn_isolate, |window| {
1739                                self.paint_shaded(bounds, element, window, cx, continuation)
1740                            })
1741                        })
1742                    })
1743                })
1744            })
1745        };
1746        if !transformation.is_unit() {
1747            return window.with_element_transform(transformation, paint);
1748        }
1749        paint(window)
1750    }
1751
1752    /// The colour a [`VnMask::tint_leaf`] mask paints in, when nothing but a
1753    /// solid background shows under it.
1754    fn vn_mask_tint(&self) -> Option<Hsla> {
1755        let mask = self.vn_mask.as_ref()?;
1756        if !mask.tint_leaf
1757            || mask.luminance
1758            || self.vn_color_matrix.is_some()
1759            || !self.background_layers.is_empty()
1760            || !self.box_shadow.is_empty()
1761            || self.is_border_visible()
1762            || self.backdrop_blur.is_some_and(|radius| radius > px(0.))
1763            || self.vn_effect.is_some()
1764            || self.vn_effect_fade.is_some()
1765            || self.vn_mask_ring
1766            || self.vn_outline.is_some_and(|o| o.width > px(0.) && !o.color.is_transparent())
1767        {
1768            return None;
1769        }
1770        match self.background.as_ref().and_then(Fill::color) {
1771            None => Some(Hsla::transparent_black()),
1772            Some(background) => background.as_solid(),
1773        }
1774    }
1775
1776    /// The `--shading` effects this style paints, the outgoing one of a
1777    /// cross-fade first, each with its share of the element's opacity.
1778    fn vn_effects(&self, cx: &App) -> [Option<(EffectSpec, f32)>; 2] {
1779        // An effect whose output moves with `time` (an animated grain) keeps
1780        // asking for the next frame. That is decorative motion, so it honours
1781        // `App::reduce_motion` here — clearing the flag stops the repaint
1782        // request, which freezes the effect on its current frame rather than
1783        // removing it. Same behaviour vn-css's animator gives transitions.
1784        let reduce_motion = cx.reduce_motion();
1785        let layer = |mut spec: EffectSpec, weight: f32| {
1786            (spec.is_some() && !self.vn_mask_ring && weight > 0.).then(|| {
1787                spec.animated &= !reduce_motion;
1788                if reduce_motion {
1789                    spec.clock_mask = 0;
1790                }
1791                (spec, weight)
1792            })
1793        };
1794        let progress = self
1795            .vn_effect_fade
1796            .map_or(1., |fade| fade.progress.clamp(0., 1.));
1797        [
1798            self.vn_effect_fade
1799                .and_then(|fade| layer(fade.from, 1. - progress)),
1800            self.vn_effect.and_then(|spec| layer(spec, progress)),
1801        ]
1802    }
1803
1804    /// An effect that reads the element's content (`[SkContent]`) takes
1805    /// everything the element paints, its subtree included, into a group it
1806    /// composites in its place; the element's own backdrop filter and
1807    /// backdrop effects read the page, so they paint before it.
1808    fn paint_shaded(
1809        &self,
1810        bounds: Bounds<Pixels>,
1811        element: u64,
1812        window: &mut Window,
1813        cx: &mut App,
1814        continuation: impl FnOnce(&mut Window, &mut App),
1815    ) {
1816        let effects = self.vn_effects(cx);
1817        let content = effects
1818            .iter()
1819            .flatten()
1820            .any(|(spec, _)| spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT != 0);
1821        if !content {
1822            return self.paint_untransformed(
1823                bounds,
1824                window,
1825                cx,
1826                continuation,
1827                &effects,
1828                element,
1829                false,
1830            );
1831        }
1832        let corner_radii = self.corner_radii_for(bounds.size, window.rem_size());
1833        self.paint_backdrop(bounds, corner_radii, window, cx, &effects, element);
1834        let shaded: Vec<_> = effects
1835            .iter()
1836            .flatten()
1837            .map(|(spec, weight)| {
1838                let textures = crate::resolve_effect_textures(spec, window, cx);
1839                (*spec, *weight, textures)
1840            })
1841            .collect();
1842        window.vn_with_effect_content(bounds, corner_radii, &shaded, element, cx, |window, cx| {
1843            self.paint_untransformed(bounds, window, cx, continuation, &effects, element, true)
1844        })
1845    }
1846
1847    /// Whether an effect of this style reads the element's content, whose
1848    /// deferred descendants then paint into it ([`Window::vn_with_defer_scope`]).
1849    pub fn vn_reads_content(&self) -> bool {
1850        [self.vn_effect, self.vn_effect_fade.map(|fade| fade.from)]
1851            .into_iter()
1852            .flatten()
1853            .any(|spec| spec.is_some() && spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT != 0)
1854    }
1855
1856    /// CSS paints the filtered backdrop underneath the element's own
1857    /// background, so the blur goes in between the drop shadows and the
1858    /// background quad. The tint stays transparent — `background-color` is
1859    /// the quad below.
1860    ///
1861    /// A BACKDROP effect (`frost`) replaces the pixels behind the element and
1862    /// so paints exactly where `backdrop-filter` does. It also *has* to: it
1863    /// draws with blending disabled and owns every pixel of its quad, so
1864    /// painting it later would erase the background quad.
1865    fn paint_backdrop(
1866        &self,
1867        bounds: Bounds<Pixels>,
1868        corner_radii: Corners<Pixels>,
1869        window: &mut Window,
1870        cx: &mut App,
1871        effects: &[Option<(EffectSpec, f32)>; 2],
1872        element: u64,
1873    ) {
1874        if let Some(radius) = self.backdrop_blur
1875            && radius > crate::px(0.)
1876            && !self.vn_mask_ring
1877        {
1878            window.paint_backdrop_blur_rect(
1879                bounds,
1880                corner_radii,
1881                crate::BackdropBlurEffect::new(radius),
1882            );
1883        }
1884        Self::paint_effects(bounds, corner_radii, window, cx, effects, element, true);
1885    }
1886
1887    /// The effects of one kind that do not read the element's content: the
1888    /// backdrop ones, or the source-over ones (`noise`, `glow`), which paint
1889    /// over the background but under the content — the only slot where film
1890    /// grain is visible on an opaque panel and where a glow's inner rim
1891    /// survives.
1892    fn paint_effects(
1893        bounds: Bounds<Pixels>,
1894        corner_radii: Corners<Pixels>,
1895        window: &mut Window,
1896        cx: &mut App,
1897        effects: &[Option<(EffectSpec, f32)>; 2],
1898        element: u64,
1899        backdrop: bool,
1900    ) {
1901        for (spec, weight) in effects.iter().flatten() {
1902            if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0
1903                && (spec.flags & crate::EFFECT_FLAG_NEEDS_BACKDROP != 0) == backdrop
1904            {
1905                window.with_element_opacity((*weight < 1.).then_some(*weight), |window| {
1906                    window.vn_paint_textured_effect(bounds, corner_radii, *spec, element, cx)
1907                });
1908            }
1909        }
1910    }
1911
1912    #[allow(clippy::too_many_arguments)]
1913    fn paint_untransformed(
1914        &self,
1915        bounds: Bounds<Pixels>,
1916        window: &mut Window,
1917        cx: &mut App,
1918        continuation: impl FnOnce(&mut Window, &mut App),
1919        effects: &[Option<(EffectSpec, f32)>; 2],
1920        element: u64,
1921        in_content: bool,
1922    ) {
1923        #[cfg(debug_assertions)]
1924        if self.debug_below {
1925            cx.set_global(DebugBelow)
1926        }
1927
1928        #[cfg(debug_assertions)]
1929        if self.debug || cx.has_global::<DebugBelow>() {
1930            window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
1931        }
1932
1933        let rem_size = window.rem_size();
1934        let corner_radii = self.corner_radii_for(bounds.size, rem_size);
1935
1936        // vue-native fork: `vn_mask_ring` paints the background only in the
1937        // padding and border area. These are the border widths of the quads
1938        // that do it: the border plus the padding. A percentage padding
1939        // resolves against this box's width (see the field's doc).
1940        let ring_widths = self.vn_mask_ring.then(|| {
1941            let border = self.border_widths.to_pixels(rem_size);
1942            let width = AbsoluteLength::Pixels(bounds.size.width);
1943            let padding = self.padding.to_pixels(size(width, width), rem_size);
1944            Edges {
1945                top: border.top + padding.top,
1946                right: border.right + padding.right,
1947                bottom: border.bottom + padding.bottom,
1948                left: border.left + padding.left,
1949            }
1950        });
1951        let ring = ring_widths.is_some();
1952
1953        if !ring {
1954            if self.vn_shadow_under_box {
1955                window.paint_drop_shadows_under_box(bounds, corner_radii, &self.box_shadow);
1956            } else {
1957                window.paint_drop_shadows(bounds, corner_radii, &self.box_shadow);
1958            }
1959        }
1960
1961        if !in_content {
1962            self.paint_backdrop(bounds, corner_radii, window, cx, effects, element);
1963        }
1964        // The background quads: the whole box, or only the ring.
1965        let fill = |background: Background| match ring_widths {
1966            Some(widths) => (background.ring(), widths),
1967            None => (background, Edges::default()),
1968        };
1969
1970        let background_color = self.background.as_ref().and_then(Fill::color);
1971        if background_color.is_some_and(|color| !color.is_transparent()) {
1972            let color = background_color.unwrap_or_default();
1973            let mut border_color = representative_color(&color);
1974            border_color.a = 0.;
1975            let (color, widths) = fill(color);
1976            window.paint_quad(quad(
1977                bounds,
1978                corner_radii,
1979                color,
1980                widths,
1981                border_color,
1982                self.border_style,
1983            ));
1984        }
1985
1986        // The `background-image` stack, bottom layer first, each one its own
1987        // quad over the colour below it. The AA-matching transparent border
1988        // trick above is deliberately NOT repeated per layer: it exists to stop
1989        // the bottom fill's antialiased corner showing a seam against the
1990        // border, and a second quad carrying it would double-blend that seam.
1991        for layer in &self.background_layers {
1992            if layer.is_transparent() {
1993                continue;
1994            }
1995            let mut border_color = representative_color(layer);
1996            border_color.a = 0.;
1997            let (layer, widths) = fill(*layer);
1998            window.paint_quad(quad(
1999                bounds,
2000                corner_radii,
2001                layer,
2002                widths,
2003                border_color,
2004                self.border_style,
2005            ));
2006        }
2007
2008        if !ring {
2009            window.paint_inset_shadows(bounds, corner_radii, &self.box_shadow);
2010        }
2011
2012        Self::paint_effects(bounds, corner_radii, window, cx, effects, element, false);
2013
2014        continuation(window, cx);
2015
2016        if self.is_border_visible() {
2017            let border_widths = self.border_widths.to_pixels(rem_size);
2018            let colors = self.vn_resolved_border_colors();
2019            if colors.top == colors.right && colors.top == colors.bottom && colors.top == colors.left {
2020                window.paint_quad(quad(
2021                    bounds, corner_radii, Hsla::transparent_black(), border_widths,
2022                    colors.top, self.border_style,
2023                ));
2024            } else {
2025                // Reuse the rounded/dashed border shader, partitioned along
2026                // the joins between outer and inner corners. Rectangular
2027                // strips would give rounded corners the wrong side colour.
2028                let clips = Self::vn_border_side_clips(bounds, border_widths);
2029                for (points, (color, width)) in clips.into_iter().zip([
2030                    (colors.top, border_widths.top), (colors.right, border_widths.right),
2031                    (colors.bottom, border_widths.bottom), (colors.left, border_widths.left),
2032                ]) {
2033                    if width <= px(0.) || color.is_transparent() || points.len() < 3 { continue; }
2034                    let mut verbs: Vec<_> = points.into_iter().enumerate().map(|(index, point)| {
2035                        if index == 0 { VnPathVerb::MoveTo(point) } else { VnPathVerb::LineTo(point) }
2036                    }).collect();
2037                    verbs.push(VnPathVerb::Close);
2038                    let outline = VnClipOutline { fill_rule: VnFillRule::NonZero, verbs };
2039                    window.vn_with_clip_shape(Some(&outline), |window| {
2040                        window.paint_quad(quad(bounds, corner_radii, Hsla::transparent_black(),
2041                            border_widths, color, self.border_style));
2042                    });
2043                }
2044            }
2045        }
2046
2047        // `outline` LAST, and at dilated bounds: CSS paints it outside the
2048        // border box, over everything, and it takes no layout space — so it is
2049        // one extra border-only quad rather than anything the box itself knows
2050        // about. `dilate` by (offset + width) puts the ring's INNER edge at
2051        // `offset` from the border box and its outer edge `width` beyond that,
2052        // which is what `outline-offset` means.
2053        //
2054        // The corner radius grows with the dilation, so the ring stays
2055        // concentric with a rounded box — the same rule Chromium applies.
2056        if let Some(outline) = self
2057            .vn_outline
2058            .filter(|o| o.width > px(0.) && !o.color.is_transparent() && !ring)
2059        {
2060            let grow = outline.offset + outline.width;
2061            let ring = bounds.dilate(grow);
2062            // Per corner: a square corner stays square (CSS does not round an
2063            // outline the box did not round), a rounded one grows with the ring.
2064            let radii = corner_radii.map(|r| {
2065                if r.0 <= 0.0 {
2066                    px(0.)
2067                } else {
2068                    px((r.0 + grow.0).max(0.0))
2069                }
2070            });
2071            window.paint_quad(quad(
2072                ring,
2073                radii,
2074                Hsla::transparent_black(),
2075                Edges::all(outline.width),
2076                outline.color,
2077                outline.style,
2078            ));
2079        }
2080
2081        #[cfg(debug_assertions)]
2082        if self.debug_below {
2083            cx.remove_global::<DebugBelow>();
2084        }
2085    }
2086
2087    fn vn_resolved_border_colors(&self) -> Edges<Hsla> {
2088        let shared = self.border_color.unwrap_or_default();
2089        self.vn_border_colors.map(|color| color.unwrap_or(shared))
2090    }
2091
2092    fn vn_border_side_clips(bounds: Bounds<Pixels>, widths: Edges<Pixels>) -> [Vec<[f32; 2]>; 4] {
2093        let (left, top, right, bottom) = (f32::from(bounds.left()), f32::from(bounds.top()),
2094            f32::from(bounds.right()), f32::from(bounds.bottom()));
2095        let widths = [widths.top, widths.right, widths.bottom, widths.left].map(|width| f32::from(width).max(0.));
2096        let distances = [[0., 1., -top], [-1., 0., right], [0., -1., bottom], [1., 0., -left]];
2097        std::array::from_fn(|side| {
2098            if widths[side] <= 0. { return Vec::new(); }
2099            let mut polygon = vec![[left, top], [right, top], [right, bottom], [left, bottom]];
2100            // Partition the FULL quad by distance / border width. Stopping
2101            // at inner rectangular corners cuts holes out of rounded arcs.
2102            // These bisectors keep the CSS joins through the inner corners
2103            // while extending far enough to cover circles and large radii.
2104            for other in 0..4 {
2105                if other == side || widths[other] <= 0. { continue; }
2106                let plane: [f32; 3] = std::array::from_fn(|index|
2107                    distances[side][index] * widths[other] - distances[other][index] * widths[side]);
2108                let distance = |point: [f32; 2]| plane[0] * point[0] + plane[1] * point[1] + plane[2];
2109                let Some(mut previous) = polygon.last().copied() else { break };
2110                let mut previous_distance = distance(previous);
2111                let mut clipped = Vec::with_capacity(polygon.len() + 1);
2112                for current in polygon {
2113                    let current_distance = distance(current);
2114                    if (previous_distance <= 0.) != (current_distance <= 0.) {
2115                        let fraction = previous_distance / (previous_distance - current_distance);
2116                        clipped.push([previous[0] + fraction * (current[0] - previous[0]),
2117                            previous[1] + fraction * (current[1] - previous[1])]);
2118                    }
2119                    if current_distance <= 0. { clipped.push(current); }
2120                    previous = current;
2121                    previous_distance = current_distance;
2122                }
2123                polygon = clipped;
2124            }
2125            polygon
2126        })
2127    }
2128
2129    fn is_border_visible(&self) -> bool {
2130        self.vn_resolved_border_colors().any(|color| !color.is_transparent())
2131            && self.border_widths.any(|length| !length.is_zero())
2132    }
2133}
2134
2135impl Default for Style {
2136    fn default() -> Self {
2137        Style {
2138            display: Display::Block,
2139            visibility: Visibility::Visible,
2140            overflow: Point {
2141                x: Overflow::Visible,
2142                y: Overflow::Visible,
2143            },
2144            allow_concurrent_scroll: false,
2145            restrict_scroll_to_axis: false,
2146            scrollbar_width: AbsoluteLength::default(),
2147            position: Position::Relative,
2148            inset: Edges::auto(),
2149            margin: Edges::<Length>::zero(),
2150            padding: Edges::<DefiniteLength>::zero(),
2151            border_widths: Edges::<AbsoluteLength>::zero(),
2152            size: Size::auto(),
2153            min_size: Size::auto(),
2154            max_size: Size::auto(),
2155            aspect_ratio: None,
2156            gap: Size::default(),
2157            // Alignment
2158            align_items: None,
2159            align_self: None,
2160            align_content: None,
2161            justify_content: None,
2162            // Flexbox
2163            flex_direction: FlexDirection::Row,
2164            flex_wrap: FlexWrap::NoWrap,
2165            flex_grow: 0.0,
2166            flex_shrink: 1.0,
2167            vn_order: 0,
2168            vn_object_position: None,
2169            flex_basis: Length::Auto,
2170            background: None,
2171            background_layers: Vec::new(),
2172            border_color: None,
2173            vn_border_colors: Edges::default(),
2174            border_style: BorderStyle::default(),
2175            corner_radii: Corners::default(),
2176            box_shadow: Default::default(),
2177            vn_shadow_under_box: false,
2178            backdrop_blur: None,
2179            vn_effect: None,
2180            vn_effect_fade: None,
2181            vn_transform: None,
2182            text: TextStyleRefinement::default(),
2183            mouse_cursor: None,
2184            opacity: None,
2185            grid_rows: None,
2186            grid_cols: None,
2187            grid_location: None,
2188            vn_grid_cols: None,
2189            vn_grid_rows: None,
2190            vn_grid_cols_auto: None,
2191            vn_grid_rows_auto: None,
2192            vn_grid_auto_cols: None,
2193            vn_grid_auto_rows: None,
2194            vn_grid_auto_flow: None,
2195            vn_justify_items: None,
2196            vn_justify_self: None,
2197            vn_outline: None,
2198            vn_mask_ring: false,
2199            vn_clip_path: VnClipPath::None,
2200            vn_color_matrix: None,
2201            vn_capture: None,
2202            vn_isolate: false,
2203            vn_text_fill: None,
2204            vn_mask: None,
2205            vn_corner_radii: Corners::default(),
2206
2207            #[cfg(debug_assertions)]
2208            debug: false,
2209            #[cfg(debug_assertions)]
2210            debug_below: false,
2211        }
2212    }
2213}
2214
2215/// The properties that can be applied to an underline.
2216#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
2217#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2218pub struct UnderlineStyle {
2219    /// The thickness of the underline.
2220    pub thickness: Pixels,
2221
2222    /// The color of the underline.
2223    pub color: Option<Hsla>,
2224
2225    /// Whether the underline should be wavy, like in a spell checker.
2226    pub wavy: bool,
2227
2228    /// How far BELOW its default position the line sits — CSS
2229    /// `text-underline-offset`. Zero keeps the position the font's own metrics
2230    /// put it at, which is what every existing caller gets.
2231    pub offset: Pixels,
2232}
2233
2234/// The properties that can be applied to a strikethrough.
2235#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
2236#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2237pub struct StrikethroughStyle {
2238    /// The thickness of the strikethrough.
2239    pub thickness: Pixels,
2240
2241    /// The color of the strikethrough.
2242    pub color: Option<Hsla>,
2243}
2244
2245/// The kinds of fill that can be applied to a shape.
2246#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
2247#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2248pub enum Fill {
2249    /// A solid color fill.
2250    Color(Background),
2251}
2252
2253impl Fill {
2254    /// Unwrap this fill into a solid color, if it is one.
2255    ///
2256    /// If the fill is not a solid color, this method returns `None`.
2257    pub fn color(&self) -> Option<Background> {
2258        match self {
2259            Fill::Color(color) => Some(*color),
2260        }
2261    }
2262}
2263
2264impl Default for Fill {
2265    fn default() -> Self {
2266        Self::Color(Background::default())
2267    }
2268}
2269
2270impl From<Hsla> for Fill {
2271    fn from(color: Hsla) -> Self {
2272        Self::Color(color.into())
2273    }
2274}
2275
2276impl From<Rgba> for Fill {
2277    fn from(color: Rgba) -> Self {
2278        Self::Color(color.into())
2279    }
2280}
2281
2282impl From<Background> for Fill {
2283    fn from(background: Background) -> Self {
2284        Self::Color(background)
2285    }
2286}
2287
2288impl From<TextStyle> for HighlightStyle {
2289    fn from(other: TextStyle) -> Self {
2290        Self::from(&other)
2291    }
2292}
2293
2294impl From<&TextStyle> for HighlightStyle {
2295    fn from(other: &TextStyle) -> Self {
2296        Self {
2297            color: Some(other.color),
2298            font_weight: Some(other.font_weight),
2299            font_style: Some(other.font_style),
2300            background_color: other.background_color,
2301            underline: other.underline,
2302            strikethrough: other.strikethrough,
2303            fade_out: None,
2304        }
2305    }
2306}
2307
2308impl HighlightStyle {
2309    /// Create a highlight style with just a color
2310    pub fn color(color: Hsla) -> Self {
2311        Self {
2312            color: Some(color),
2313            ..Default::default()
2314        }
2315    }
2316    /// Blend this highlight style with another.
2317    /// Non-continuous properties, like font_weight and font_style, are overwritten.
2318    #[must_use]
2319    pub fn highlight(self, other: HighlightStyle) -> Self {
2320        Self {
2321            color: other
2322                .color
2323                .map(|other_color| {
2324                    if let Some(color) = self.color {
2325                        color.blend(other_color)
2326                    } else {
2327                        other_color
2328                    }
2329                })
2330                .or(self.color),
2331            font_weight: other.font_weight.or(self.font_weight),
2332            font_style: other.font_style.or(self.font_style),
2333            background_color: other.background_color.or(self.background_color),
2334            underline: other.underline.or(self.underline),
2335            strikethrough: other.strikethrough.or(self.strikethrough),
2336            fade_out: other
2337                .fade_out
2338                .map(|source_fade| {
2339                    self.fade_out
2340                        .map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
2341                        .unwrap_or(source_fade)
2342                })
2343                .or(self.fade_out),
2344        }
2345    }
2346}
2347
2348impl From<Hsla> for HighlightStyle {
2349    fn from(color: Hsla) -> Self {
2350        Self {
2351            color: Some(color),
2352            ..Default::default()
2353        }
2354    }
2355}
2356
2357impl From<FontWeight> for HighlightStyle {
2358    fn from(font_weight: FontWeight) -> Self {
2359        Self {
2360            font_weight: Some(font_weight),
2361            ..Default::default()
2362        }
2363    }
2364}
2365
2366impl From<FontStyle> for HighlightStyle {
2367    fn from(font_style: FontStyle) -> Self {
2368        Self {
2369            font_style: Some(font_style),
2370            ..Default::default()
2371        }
2372    }
2373}
2374
2375impl From<Rgba> for HighlightStyle {
2376    fn from(color: Rgba) -> Self {
2377        Self {
2378            color: Some(color.into()),
2379            ..Default::default()
2380        }
2381    }
2382}
2383
2384/// Combine and merge the highlights and ranges in the two iterators.
2385pub fn combine_highlights(
2386    a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
2387    b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
2388) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
2389    let mut endpoints = Vec::new();
2390    let mut highlights = Vec::new();
2391    for (range, highlight) in a.into_iter().chain(b) {
2392        if !range.is_empty() {
2393            let highlight_id = highlights.len();
2394            endpoints.push((range.start, highlight_id, true));
2395            endpoints.push((range.end, highlight_id, false));
2396            highlights.push(highlight);
2397        }
2398    }
2399    endpoints.sort_unstable_by_key(|(position, _, _)| *position);
2400    let mut endpoints = endpoints.into_iter().peekable();
2401
2402    let mut active_styles = HashSet::default();
2403    let mut ix = 0;
2404    iter::from_fn(move || {
2405        while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
2406            let prev_index = mem::replace(&mut ix, *endpoint_ix);
2407            if ix > prev_index && !active_styles.is_empty() {
2408                let current_style = active_styles
2409                    .iter()
2410                    .fold(HighlightStyle::default(), |acc, highlight_id| {
2411                        acc.highlight(highlights[*highlight_id])
2412                    });
2413                return Some((prev_index..ix, current_style));
2414            }
2415
2416            if *is_start {
2417                active_styles.insert(*highlight_id);
2418            } else {
2419                active_styles.remove(highlight_id);
2420            }
2421            endpoints.next();
2422        }
2423        None
2424    })
2425}
2426
2427/// Used to control how child nodes are aligned.
2428/// For Flexbox it controls alignment in the cross axis
2429/// For Grid it controls alignment in the block axis
2430///
2431/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items)
2432#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
2433#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2434// Copy of taffy::style type of the same name, to derive JsonSchema.
2435pub enum AlignItems {
2436    /// Items are packed toward the start of the axis
2437    Start,
2438    /// Items are packed toward the end of the axis
2439    End,
2440    /// Items are packed towards the flex-relative start of the axis.
2441    ///
2442    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
2443    /// to End. In all other cases it is equivalent to Start.
2444    FlexStart,
2445    /// Items are packed towards the flex-relative end of the axis.
2446    ///
2447    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
2448    /// to Start. In all other cases it is equivalent to End.
2449    FlexEnd,
2450    /// Items are packed along the center of the cross axis
2451    Center,
2452    /// Items are aligned such as their baselines align
2453    Baseline,
2454    /// Stretch to fill the container
2455    Stretch,
2456}
2457/// Used to control how child nodes are aligned.
2458/// Does not apply to Flexbox, and will be ignored if specified on a flex container
2459/// For Grid it controls alignment in the inline axis
2460///
2461/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-items)
2462pub type JustifyItems = AlignItems;
2463/// Used to control how the specified nodes is aligned.
2464/// Overrides the parent Node's `AlignItems` property.
2465/// For Flexbox it controls alignment in the cross axis
2466/// For Grid it controls alignment in the block axis
2467///
2468/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self)
2469pub type AlignSelf = AlignItems;
2470/// Used to control how the specified nodes is aligned.
2471/// Overrides the parent Node's `JustifyItems` property.
2472/// Does not apply to Flexbox, and will be ignored if specified on a flex child
2473/// For Grid it controls alignment in the inline axis
2474///
2475/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self)
2476pub type JustifySelf = AlignItems;
2477
2478/// Sets the distribution of space between and around content items
2479/// For Flexbox it controls alignment in the cross axis
2480/// For Grid it controls alignment in the block axis
2481///
2482/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content)
2483#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
2484#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2485// Copy of taffy::style type of the same name, to derive JsonSchema.
2486pub enum AlignContent {
2487    /// Items are packed toward the start of the axis
2488    Start,
2489    /// Items are packed toward the end of the axis
2490    End,
2491    /// Items are packed towards the flex-relative start of the axis.
2492    ///
2493    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
2494    /// to End. In all other cases it is equivalent to Start.
2495    FlexStart,
2496    /// Items are packed towards the flex-relative end of the axis.
2497    ///
2498    /// For flex containers with flex_direction RowReverse or ColumnReverse this is equivalent
2499    /// to Start. In all other cases it is equivalent to End.
2500    FlexEnd,
2501    /// Items are centered around the middle of the axis
2502    Center,
2503    /// Items are stretched to fill the container
2504    Stretch,
2505    /// The first and last items are aligned flush with the edges of the container (no gap)
2506    /// The gap between items is distributed evenly.
2507    SpaceBetween,
2508    /// The gap between the first and last items is exactly THE SAME as the gap between items.
2509    /// The gaps are distributed evenly
2510    SpaceEvenly,
2511    /// The gap between the first and last items is exactly HALF the gap between items.
2512    /// The gaps are distributed evenly in proportion to these ratios.
2513    SpaceAround,
2514    /// vue-native fork: CSS `safe center`. Centred while the content fits, and
2515    /// packed toward the start when it would overflow. HTML lays a `<button>`'s
2516    /// content out this way.
2517    SafeCenter,
2518}
2519
2520/// Sets the distribution of space between and around content items
2521/// For Flexbox it controls alignment in the main axis
2522/// For Grid it controls alignment in the inline axis
2523///
2524/// [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content)
2525pub type JustifyContent = AlignContent;
2526
2527/// Sets the layout used for the children of this node
2528///
2529/// The default values depends on on which feature flags are enabled. The order of precedence is: Flex, Grid, Block, None.
2530#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2531#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2532// Copy of taffy::style type of the same name, to derive JsonSchema.
2533pub enum Display {
2534    /// The children will follow the block layout algorithm
2535    Block,
2536    /// The children will follow the flexbox layout algorithm
2537    #[default]
2538    Flex,
2539    /// The children will follow the CSS Grid layout algorithm
2540    Grid,
2541    /// The children will not be laid out, and will follow absolute positioning
2542    None,
2543}
2544
2545/// Controls whether flex items are forced onto one line or can wrap onto multiple lines.
2546///
2547/// Defaults to [`FlexWrap::NoWrap`]
2548///
2549/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-wrap-property)
2550#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2551#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2552// Copy of taffy::style type of the same name, to derive JsonSchema.
2553pub enum FlexWrap {
2554    /// Items will not wrap and stay on a single line
2555    #[default]
2556    NoWrap,
2557    /// Items will wrap according to this item's [`FlexDirection`]
2558    Wrap,
2559    /// Items will wrap in the opposite direction to this item's [`FlexDirection`]
2560    WrapReverse,
2561}
2562
2563/// The direction of the flexbox layout main axis.
2564///
2565/// There are always two perpendicular layout axes: main (or primary) and cross (or secondary).
2566/// Adding items will cause them to be positioned adjacent to each other along the main axis.
2567/// By varying this value throughout your tree, you can create complex axis-aligned layouts.
2568///
2569/// Items are always aligned relative to the cross axis, and justified relative to the main axis.
2570///
2571/// The default behavior is [`FlexDirection::Row`].
2572///
2573/// [Specification](https://www.w3.org/TR/css-flexbox-1/#flex-direction-property)
2574#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2575#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2576// Copy of taffy::style type of the same name, to derive JsonSchema.
2577pub enum FlexDirection {
2578    /// Defines +x as the main axis
2579    ///
2580    /// Items will be added from left to right in a row.
2581    #[default]
2582    Row,
2583    /// Defines +y as the main axis
2584    ///
2585    /// Items will be added from top to bottom in a column.
2586    Column,
2587    /// Defines -x as the main axis
2588    ///
2589    /// Items will be added from right to left in a row.
2590    RowReverse,
2591    /// Defines -y as the main axis
2592    ///
2593    /// Items will be added from bottom to top in a column.
2594    ColumnReverse,
2595}
2596
2597/// How children overflowing their container should affect layout
2598///
2599/// In CSS the primary effect of this property is to control whether contents of a parent container that overflow that container should
2600/// be displayed anyway, be clipped, or trigger the container to become a scroll container. However it also has secondary effects on layout,
2601/// the main ones being:
2602///
2603///   - The automatic minimum size Flexbox/CSS Grid items with non-`Visible` overflow is `0` rather than being content based
2604///   - `Overflow::Scroll` nodes have space in the layout reserved for a scrollbar (width controlled by the `scrollbar_width` property)
2605///
2606/// In Taffy, we only implement the layout related secondary effects as we are not concerned with drawing/painting. The amount of space reserved for
2607/// a scrollbar is controlled by the `scrollbar_width` property. If this is `0` then `Scroll` behaves identically to `Hidden`.
2608///
2609/// <https://developer.mozilla.org/en-US/docs/Web/CSS/overflow>
2610#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2611#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2612// Copy of taffy::style type of the same name, to derive JsonSchema.
2613pub enum Overflow {
2614    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
2615    /// Content that overflows this node *should* contribute to the scroll region of its parent.
2616    #[default]
2617    Visible,
2618    /// The automatic minimum size of this node as a flexbox/grid item should be based on the size of its content.
2619    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
2620    Clip,
2621    /// The automatic minimum size of this node as a flexbox/grid item should be `0`.
2622    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
2623    Hidden,
2624    /// The automatic minimum size of this node as a flexbox/grid item should be `0`. Additionally, space should be reserved
2625    /// for a scrollbar. The amount of space reserved is controlled by the `scrollbar_width` property.
2626    /// Content that overflows this node should *not* contribute to the scroll region of its parent.
2627    Scroll,
2628}
2629
2630/// The positioning strategy for this item.
2631///
2632/// This controls both how the origin is determined for the [`Style::position`] field,
2633/// and whether or not the item will be controlled by flexbox's layout algorithm.
2634///
2635/// WARNING: this enum follows the behavior of [CSS's `position` property](https://developer.mozilla.org/en-US/docs/Web/CSS/position),
2636/// which can be unintuitive.
2637///
2638/// [`Position::Relative`] is the default value, in contrast to the default behavior in CSS.
2639#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
2640#[cfg_attr(feature = "schemars", derive(JsonSchema))]
2641// Copy of taffy::style type of the same name, to derive JsonSchema.
2642pub enum Position {
2643    /// The offset is computed relative to the final position given by the layout algorithm.
2644    /// Offsets do not affect the position of any other items; they are effectively a correction factor applied at the end.
2645    #[default]
2646    Relative,
2647    /// The offset is computed relative to this item's closest positioned ancestor, if any.
2648    /// Otherwise, it is placed relative to the origin.
2649    /// No space is created for the item in the page layout, and its size will not be altered.
2650    ///
2651    /// WARNING: to opt-out of layouting entirely, you must use [`Display::None`] instead on your [`Style`] object.
2652    Absolute,
2653}
2654
2655impl From<AlignItems> for taffy::style::AlignItems {
2656    fn from(value: AlignItems) -> Self {
2657        match value {
2658            AlignItems::Start => Self::START,
2659            AlignItems::End => Self::END,
2660            AlignItems::FlexStart => Self::FLEX_START,
2661            AlignItems::FlexEnd => Self::FLEX_END,
2662            AlignItems::Center => Self::CENTER,
2663            AlignItems::Baseline => Self::BASELINE,
2664            AlignItems::Stretch => Self::STRETCH,
2665        }
2666    }
2667}
2668
2669impl From<AlignContent> for taffy::style::AlignContent {
2670    fn from(value: AlignContent) -> Self {
2671        match value {
2672            AlignContent::Start => Self::START,
2673            AlignContent::End => Self::END,
2674            AlignContent::FlexStart => Self::FLEX_START,
2675            AlignContent::FlexEnd => Self::FLEX_END,
2676            AlignContent::Center => Self::CENTER,
2677            AlignContent::Stretch => Self::STRETCH,
2678            AlignContent::SpaceBetween => Self::SPACE_BETWEEN,
2679            AlignContent::SpaceEvenly => Self::SPACE_EVENLY,
2680            AlignContent::SpaceAround => Self::SPACE_AROUND,
2681            AlignContent::SafeCenter => Self::SAFE_CENTER,
2682        }
2683    }
2684}
2685
2686impl From<Display> for taffy::style::Display {
2687    fn from(value: Display) -> Self {
2688        match value {
2689            Display::Block => Self::Block,
2690            Display::Flex => Self::Flex,
2691            Display::Grid => Self::Grid,
2692            Display::None => Self::None,
2693        }
2694    }
2695}
2696
2697impl From<FlexWrap> for taffy::style::FlexWrap {
2698    fn from(value: FlexWrap) -> Self {
2699        match value {
2700            FlexWrap::NoWrap => Self::NoWrap,
2701            FlexWrap::Wrap => Self::Wrap,
2702            FlexWrap::WrapReverse => Self::WrapReverse,
2703        }
2704    }
2705}
2706
2707impl From<FlexDirection> for taffy::style::FlexDirection {
2708    fn from(value: FlexDirection) -> Self {
2709        match value {
2710            FlexDirection::Row => Self::Row,
2711            FlexDirection::Column => Self::Column,
2712            FlexDirection::RowReverse => Self::RowReverse,
2713            FlexDirection::ColumnReverse => Self::ColumnReverse,
2714        }
2715    }
2716}
2717
2718impl From<Overflow> for taffy::style::Overflow {
2719    fn from(value: Overflow) -> Self {
2720        match value {
2721            Overflow::Visible => Self::Visible,
2722            Overflow::Clip => Self::Clip,
2723            Overflow::Hidden => Self::Hidden,
2724            Overflow::Scroll => Self::Scroll,
2725        }
2726    }
2727}
2728
2729impl From<Position> for taffy::style::Position {
2730    fn from(value: Position) -> Self {
2731        match value {
2732            Position::Relative => Self::Relative,
2733            Position::Absolute => Self::Absolute,
2734        }
2735    }
2736}
2737
2738#[cfg(test)]
2739mod tests {
2740    use crate::{blue, green, px, red, yellow};
2741
2742    use super::*;
2743
2744    use util_macros::perf;
2745
2746    #[perf]
2747    fn test_basic_highlight_style_combination() {
2748        let style_a = HighlightStyle::default();
2749        let style_b = HighlightStyle::default();
2750        let style_a = style_a.highlight(style_b);
2751        assert_eq!(
2752            style_a,
2753            HighlightStyle::default(),
2754            "Combining empty styles should not produce a non-empty style."
2755        );
2756
2757        let style_b = HighlightStyle {
2758            color: Some(red()),
2759            strikethrough: Some(StrikethroughStyle {
2760                thickness: px(2.),
2761                color: Some(blue()),
2762            }),
2763            fade_out: Some(0.),
2764            font_style: Some(FontStyle::Italic),
2765            font_weight: Some(FontWeight(300.)),
2766            background_color: Some(yellow()),
2767            underline: Some(UnderlineStyle {
2768                thickness: px(2.),
2769                color: Some(red()),
2770                wavy: true,
2771                offset: px(0.),
2772            }),
2773        };
2774        let expected_style = style_b;
2775
2776        let style_a = style_a.highlight(style_b);
2777        assert_eq!(
2778            style_a, expected_style,
2779            "Blending an empty style with another style should return the other style"
2780        );
2781
2782        let style_b = style_b.highlight(Default::default());
2783        assert_eq!(
2784            style_b, expected_style,
2785            "Blending a style with an empty style should not change the style."
2786        );
2787
2788        let style_c = expected_style;
2789
2790        let style_d = HighlightStyle {
2791            color: Some(blue().alpha(0.7)),
2792            strikethrough: Some(StrikethroughStyle {
2793                thickness: px(4.),
2794                color: Some(crate::red()),
2795            }),
2796            fade_out: Some(0.),
2797            font_style: Some(FontStyle::Oblique),
2798            font_weight: Some(FontWeight(800.)),
2799            background_color: Some(green()),
2800            underline: Some(UnderlineStyle {
2801                thickness: px(4.),
2802                color: None,
2803                wavy: false,
2804                offset: px(0.),
2805            }),
2806        };
2807
2808        let expected_style = HighlightStyle {
2809            color: Some(red().blend(blue().alpha(0.7))),
2810            strikethrough: Some(StrikethroughStyle {
2811                thickness: px(4.),
2812                color: Some(red()),
2813            }),
2814            // TODO this does not seem right
2815            fade_out: Some(0.),
2816            font_style: Some(FontStyle::Oblique),
2817            font_weight: Some(FontWeight(800.)),
2818            background_color: Some(green()),
2819            underline: Some(UnderlineStyle {
2820                thickness: px(4.),
2821                color: None,
2822                wavy: false,
2823                offset: px(0.),
2824            }),
2825        };
2826
2827        let style_c = style_c.highlight(style_d);
2828        assert_eq!(
2829            style_c, expected_style,
2830            "Blending styles should blend properties where possible and override all others"
2831        );
2832    }
2833
2834    #[perf]
2835    fn test_combine_highlights() {
2836        assert_eq!(
2837            combine_highlights(
2838                [
2839                    (0..5, green().into()),
2840                    (4..10, FontWeight::BOLD.into()),
2841                    (15..20, yellow().into()),
2842                ],
2843                [
2844                    (2..6, FontStyle::Italic.into()),
2845                    (1..3, blue().into()),
2846                    (21..23, red().into()),
2847                ]
2848            )
2849            .collect::<Vec<_>>(),
2850            [
2851                (
2852                    0..1,
2853                    HighlightStyle {
2854                        color: Some(green()),
2855                        ..Default::default()
2856                    }
2857                ),
2858                (
2859                    1..2,
2860                    HighlightStyle {
2861                        color: Some(blue()),
2862                        ..Default::default()
2863                    }
2864                ),
2865                (
2866                    2..3,
2867                    HighlightStyle {
2868                        color: Some(blue()),
2869                        font_style: Some(FontStyle::Italic),
2870                        ..Default::default()
2871                    }
2872                ),
2873                (
2874                    3..4,
2875                    HighlightStyle {
2876                        color: Some(green()),
2877                        font_style: Some(FontStyle::Italic),
2878                        ..Default::default()
2879                    }
2880                ),
2881                (
2882                    4..5,
2883                    HighlightStyle {
2884                        color: Some(green()),
2885                        font_weight: Some(FontWeight::BOLD),
2886                        font_style: Some(FontStyle::Italic),
2887                        ..Default::default()
2888                    }
2889                ),
2890                (
2891                    5..6,
2892                    HighlightStyle {
2893                        font_weight: Some(FontWeight::BOLD),
2894                        font_style: Some(FontStyle::Italic),
2895                        ..Default::default()
2896                    }
2897                ),
2898                (
2899                    6..10,
2900                    HighlightStyle {
2901                        font_weight: Some(FontWeight::BOLD),
2902                        ..Default::default()
2903                    }
2904                ),
2905                (
2906                    15..20,
2907                    HighlightStyle {
2908                        color: Some(yellow()),
2909                        ..Default::default()
2910                    }
2911                ),
2912                (
2913                    21..23,
2914                    HighlightStyle {
2915                        color: Some(red()),
2916                        ..Default::default()
2917                    }
2918                )
2919            ]
2920        );
2921    }
2922
2923    #[perf]
2924    fn test_text_style_refinement() {
2925        let mut style = Style::default();
2926        style.refine(&StyleRefinement::default().text_size(px(20.0)));
2927        style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
2928
2929        assert_eq!(
2930            Some(AbsoluteLength::from(px(20.0))),
2931            style.text_style().unwrap().font_size
2932        );
2933
2934        assert_eq!(
2935            Some(FontWeight::SEMIBOLD),
2936            style.text_style().unwrap().font_weight
2937        );
2938    }
2939}
2940
2941/// vue-native fork: `AlignContent::SafeCenter` reaches taffy as `safe center`.
2942/// A block container centres content that fits and starts content that
2943/// overflows.
2944#[cfg(test)]
2945mod vn_object_position_tests {
2946    use super::*;
2947    use crate::{px, size};
2948
2949    #[test]
2950    fn the_position_places_the_fitted_image_in_the_free_space() {
2951        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(50.)));
2952        let square = size(DevicePixels(40), DevicePixels(40));
2953        let at = |fit: ObjectFit, x: (f32, f32), y: (f32, f32)| {
2954            let position = ObjectPosition {
2955                x_fraction: x.0,
2956                x_offset: px(x.1),
2957                y_fraction: y.0,
2958                y_offset: px(y.1),
2959            };
2960            let b = fit.get_bounds_at(bounds, square, position);
2961            (f32::from(b.origin.x), f32::from(b.origin.y), f32::from(b.size.width), f32::from(b.size.height))
2962        };
2963        assert_eq!(at(ObjectFit::Contain, (0., 0.), (0., 0.)), (10., 20., 50., 50.));
2964        assert_eq!(at(ObjectFit::Contain, (1., -5.), (0.5, 0.)), (55., 20., 50., 50.));
2965        assert_eq!(at(ObjectFit::Cover, (0., 0.), (1., 0.)), (10., -30., 100., 100.));
2966        assert_eq!(at(ObjectFit::None, (0.25, 0.), (0., 3.)), (25., 23., 40., 40.));
2967        assert_eq!(at(ObjectFit::Fill, (0.5, 7.), (0.5, 0.)), (17., 20., 100., 50.));
2968        let legacy = ObjectFit::None.get_bounds(bounds, square);
2969        assert_eq!(legacy.origin, bounds.origin);
2970    }
2971}
2972
2973#[cfg(test)]
2974mod vn_safe_center_tests {
2975    use crate::{AlignContent, Context, TestAppContext, Window, div, prelude::*, px, size};
2976
2977    struct Boxes;
2978
2979    impl Render for Boxes {
2980        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
2981            let block = |name: &'static str, child_h: f32| {
2982                let mut d = div().w(px(100.)).h(px(100.));
2983                d.style().align_content = Some(AlignContent::SafeCenter);
2984                d.child(div().debug_selector(move || name.into()).w(px(10.)).h(px(child_h)))
2985            };
2986            div().child(block("FITS", 20.)).child(block("OVERFLOWS", 200.))
2987        }
2988    }
2989
2990    #[gpui::test]
2991    fn safe_center_centres_what_fits_and_starts_what_overflows(cx: &mut TestAppContext) {
2992        let window = cx.open_window(size(px(400.), px(600.)), |_, _| Boxes);
2993        cx.run_until_parked();
2994        window
2995            .update(cx, |_, window, _| {
2996                let at = |name: &str| window.rendered_frame.debug_bounds.get(name).copied().unwrap();
2997                assert_eq!(at("FITS").origin.y, px(40.), "(100 - 20) / 2");
2998                assert_eq!(at("OVERFLOWS").origin.y, px(100.), "at the start of the second box");
2999            })
3000            .unwrap();
3001    }
3002}
3003
3004/// vue-native fork: `Style::vn_mask_ring`.
3005#[cfg(test)]
3006mod vn_mask_ring_tests {
3007    use crate::{
3008        BoxShadow, Context, Hsla, TestAppContext, Window, color::BG_RING, div, point,
3009        prelude::*, px, size,
3010    };
3011
3012    struct Card {
3013        ring: bool,
3014    }
3015
3016    impl Render for Card {
3017        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3018            let mut d = div()
3019                .w(px(100.))
3020                .h(px(60.))
3021                .p(px(2.))
3022                .border_1()
3023                .border_color(Hsla::white())
3024                .bg(Hsla::red())
3025                .shadow(vec![BoxShadow {
3026                    color: Hsla::black(),
3027                    offset: point(px(0.), px(4.)),
3028                    blur_radius: px(8.),
3029                    spread_radius: px(0.),
3030                    inset: false,
3031                }]);
3032            d.style().vn_mask_ring = Some(self.ring);
3033            d
3034        }
3035    }
3036
3037    /// The painted quads, and the frame's shadow count.
3038    fn paint(ring: bool, cx: &mut TestAppContext) -> (Vec<crate::Quad>, usize, f32) {
3039        let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Card { ring });
3040        cx.run_until_parked();
3041        window
3042            .update(cx, |_, window, _| {
3043                let shadows = window.rendered_frame.scene.shadows.len();
3044                (window.painted_quads(), shadows, window.scale_factor())
3045            })
3046            .unwrap()
3047    }
3048
3049    #[gpui::test]
3050    fn a_ring_mask_paints_the_background_in_the_padding_and_border_only(
3051        cx: &mut TestAppContext,
3052    ) {
3053        let (quads, shadows, scale) = paint(false, cx);
3054        let background = quads.iter().find(|q| q.background.as_solid() == Some(Hsla::red()));
3055        let background = background.expect("the background quad");
3056        assert_eq!(background.background.flags & BG_RING, 0);
3057        assert_eq!(background.border_widths.top.0, 0.0, "a plain background fills the box");
3058        assert_eq!(shadows, 1);
3059
3060        let (quads, shadows, _) = paint(true, cx);
3061        let background = quads
3062            .iter()
3063            .find(|q| q.background.flags & BG_RING != 0)
3064            .expect("the background quad, flagged");
3065        assert_eq!(background.background.as_solid(), Some(Hsla::red()));
3066        for width in [
3067            background.border_widths.top,
3068            background.border_widths.right,
3069            background.border_widths.bottom,
3070            background.border_widths.left,
3071        ] {
3072            assert_eq!(width.0, 3.0 * scale, "1px border + 2px padding");
3073        }
3074        let border = quads
3075            .iter()
3076            .find(|q| q.border_color == Hsla::white())
3077            .expect("the border still paints");
3078        assert_eq!(border.border_widths.top.0, 1.0 * scale);
3079        assert_eq!(shadows, 0, "the mask cuts the outer shadow");
3080    }
3081}
3082
3083/// vue-native fork: `overflow` under a `border-radius` clips to the rounded
3084/// padding box, and what is painted inside carries that mask.
3085#[cfg(test)]
3086mod vn_rounded_clip_tests {
3087    use crate::{
3088        Bounds, Context, Corners, DefiniteLength, Edges, Hsla, Overflow, Style, TestAppContext,
3089        VnCornerRadius, Window, div, point, prelude::*, px, size, vn_resolve_corner_radii,
3090        vn_take_ellipse_drawn_as_circle,
3091    };
3092
3093    fn clipping(radius: f32, border: f32, border_color: Option<Hsla>) -> Style {
3094        Style {
3095            overflow: point(Overflow::Hidden, Overflow::Hidden),
3096            corner_radii: Corners::all(px(radius)).map(|radius| (*radius).into()),
3097            border_widths: Edges::all(px(border).into()),
3098            border_color,
3099            ..Style::default()
3100        }
3101    }
3102
3103    #[test]
3104    fn an_overflow_clip_takes_the_padding_box_curve() {
3105        let rem = px(16.);
3106        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(200.), px(160.)));
3107
3108        let mask = clipping(24., 4., Some(Hsla::black())).overflow_mask(bounds, rem).unwrap();
3109        assert_eq!(mask.bounds, Bounds::new(point(px(14.), px(24.)), size(px(192.), px(152.))));
3110        assert_eq!(mask.corner_radii, Corners::all(px(20.)), "the radius less the border");
3111
3112        let mask = clipping(24., 4., None).overflow_mask(bounds, rem).unwrap();
3113        assert_eq!(mask.bounds, bounds, "a transparent border is not inset");
3114        assert_eq!(mask.corner_radii, Corners::all(px(24.)), "so it takes nothing off");
3115
3116        let mask = clipping(3., 4., Some(Hsla::black())).overflow_mask(bounds, rem).unwrap();
3117        assert_eq!(mask.corner_radii, Corners::all(px(0.)), "a border wider than the radius");
3118
3119        let avatar = Bounds::new(point(px(0.), px(0.)), size(px(64.), px(64.)));
3120        let mask = clipping(9999., 0., None).overflow_mask(avatar, rem).unwrap();
3121        assert_eq!(mask.corner_radii, Corners::all(px(32.)), "a pill is a circle");
3122
3123        let mask = clipping(0., 0., None).overflow_mask(bounds, rem).unwrap();
3124        assert!(!mask.is_rounded(), "no radius, the plain rect");
3125    }
3126
3127    fn resolve(lengths: [f32; 4], relative: [Option<(DefiniteLength, DefiniteLength)>; 4], w: f32, h: f32) -> [f32; 4] {
3128        let corner = |r: Option<(DefiniteLength, DefiniteLength)>| r.map(|(x, y)| VnCornerRadius { x, y });
3129        let radii = vn_resolve_corner_radii(
3130            &Corners {
3131                top_left: px(lengths[0]).into(),
3132                top_right: px(lengths[1]).into(),
3133                bottom_right: px(lengths[2]).into(),
3134                bottom_left: px(lengths[3]).into(),
3135            },
3136            &Corners {
3137                top_left: corner(relative[0]),
3138                top_right: corner(relative[1]),
3139                bottom_right: corner(relative[2]),
3140                bottom_left: corner(relative[3]),
3141            },
3142            size(px(w), px(h)),
3143            px(16.),
3144        );
3145        [radii.top_left, radii.top_right, radii.bottom_right, radii.bottom_left].map(f32::from)
3146    }
3147
3148    #[test]
3149    fn percentages_resolve_against_the_box_and_overlaps_scale() {
3150        let half = Some((DefiniteLength::Fraction(0.5), DefiniteLength::Fraction(0.5)));
3151        let _ = vn_take_ellipse_drawn_as_circle();
3152
3153        assert_eq!(resolve([0.; 4], [half; 4], 64., 64.), [32.; 4], "50% of a square: a circle");
3154        assert!(!vn_take_ellipse_drawn_as_circle());
3155
3156        // 50% of 120x48 is a 60x24 ellipse at each corner; gpui draws the
3157        // 24px circle, a pill, and says so.
3158        assert_eq!(resolve([0.; 4], [half; 4], 120., 48.), [24.; 4]);
3159        assert!(vn_take_ellipse_drawn_as_circle());
3160
3161        // `rounded-full`: 9999px on every corner of 100x40 scales by 40/19998.
3162        assert_eq!(resolve([9999.; 4], [None; 4], 100., 40.), [20.; 4]);
3163        // `rounded-l-full`: only the left side overruns; both its corners
3164        // scale, and the right stays square.
3165        assert_eq!(resolve([9999., 0., 0., 9999.], [None; 4], 100., 40.), [20., 0., 0., 20.]);
3166        // Radii that fit stay as written.
3167        assert_eq!(resolve([8., 4., 0., 12.], [None; 4], 100., 40.), [8., 4., 0., 12.]);
3168        // 40 + 40 across a 60px top: both scale by 60/80, to 30.
3169        assert_eq!(resolve([40., 40., 0., 0.], [None; 4], 60., 200.), [30., 30., 0., 0.]);
3170
3171        // `calc(50% - 4px)` and an elliptical `10px / 20px`.
3172        let calc = DefiniteLength::Calc { fraction: 0.5, pixels: px(-4.) };
3173        assert_eq!(resolve([0.; 4], [Some((calc, calc)); 4], 64., 64.), [28.; 4]);
3174        let ellipse = Some((DefiniteLength::Absolute(px(10.).into()), DefiniteLength::Absolute(px(20.).into())));
3175        assert_eq!(resolve([0.; 4], [ellipse; 4], 100., 100.), [10.; 4]);
3176        assert!(vn_take_ellipse_drawn_as_circle());
3177    }
3178
3179    #[test]
3180    fn a_percentage_radius_clips_overflow_too() {
3181        let mut avatar = clipping(0., 0., None);
3182        let half = Some(VnCornerRadius {
3183            x: DefiniteLength::Fraction(0.5),
3184            y: DefiniteLength::Fraction(0.5),
3185        });
3186        avatar.vn_corner_radii = Corners {
3187            top_left: half,
3188            top_right: half,
3189            bottom_right: half,
3190            bottom_left: half,
3191        };
3192        let bounds = Bounds::new(point(px(0.), px(0.)), size(px(40.), px(40.)));
3193        let mask = avatar.overflow_mask(bounds, px(16.)).unwrap();
3194        assert_eq!(mask.corner_radii, Corners::all(px(20.)));
3195    }
3196
3197    /// reka's AvatarRoot around its image, and a rounded card around a list
3198    /// that scrolls.
3199    struct Clips;
3200
3201    impl Render for Clips {
3202        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3203            div()
3204                .child(
3205                    div()
3206                        .size(px(64.))
3207                        .rounded_full()
3208                        .overflow_hidden()
3209                        .child(div().size_full().bg(Hsla::red())),
3210                )
3211                .child(
3212                    div()
3213                        .w(px(200.))
3214                        .h(px(160.))
3215                        .rounded(px(24.))
3216                        .overflow_hidden()
3217                        .child(
3218                            div()
3219                                .id("list")
3220                                .size_full()
3221                                .overflow_y_scroll()
3222                                .child(div().w_full().h(px(400.)).bg(Hsla::green())),
3223                        ),
3224                )
3225        }
3226    }
3227
3228    #[gpui::test]
3229    fn what_paints_inside_carries_the_rounded_mask(cx: &mut TestAppContext) {
3230        let window = cx.open_window(size(px(400.), px(400.)), |_, _| Clips);
3231        cx.run_until_parked();
3232        let (quads, scale) = window
3233            .update(cx, |_, window, _| (window.painted_quads(), window.scale_factor()))
3234            .unwrap();
3235        let quad = |color: Hsla| {
3236            quads
3237                .iter()
3238                .find(|q| q.background.as_solid() == Some(color))
3239                .copied()
3240                .expect("the quad")
3241        };
3242
3243        let avatar = quad(Hsla::red());
3244        assert_eq!(avatar.content_mask.corner_radii, Corners::all(px(32.)).scale(scale));
3245        assert_eq!(avatar.corner_radii, Corners::default(), "the image itself is square");
3246
3247        // The scroller's own mask is square and fills the card, so its
3248        // corners are the card's: the rows clip at the card's curve.
3249        let rows = quad(Hsla::green());
3250        assert_eq!(rows.content_mask.corner_radii, Corners::all(px(24.)).scale(scale));
3251        assert_eq!(rows.content_mask.bounds.size, size(px(200.), px(160.)).scale(scale));
3252    }
3253}
3254
3255/// vue-native fork: `clip-path` is a rounded mask around the element's whole
3256/// painting (`Style::vn_clip_path`, `Style::vn_clip_mask`).
3257#[cfg(test)]
3258mod vn_clip_path_tests {
3259    use crate::{
3260        Bounds, BoxShadow, Context, Corners, DefiniteLength, Edges, Hsla, Length, Pixels, Style,
3261        TestAppContext, VnClipBox, VnClipPath, VnCornerRadius, VnShapeRadius, Window, div, point,
3262        prelude::*, px, relative, size,
3263    };
3264
3265    const BOX: VnClipBox = VnClipBox::Border;
3266
3267    fn len(v: f32) -> DefiniteLength {
3268        px(v).into()
3269    }
3270
3271    fn round(x: DefiniteLength, y: DefiniteLength) -> [VnCornerRadius; 4] {
3272        [VnCornerRadius { x, y }; 4]
3273    }
3274
3275    /// The mask's bounds, as `[x, y, w, h]`, and its four radii, to 0.01px.
3276    fn mask(clip: VnClipPath, style: Style, bounds: [f32; 4]) -> ([f32; 4], [f32; 4]) {
3277        let bounds = Bounds::new(point(px(bounds[0]), px(bounds[1])), size(px(bounds[2]), px(bounds[3])));
3278        let m = Style { vn_clip_path: clip, ..style }.vn_clip_mask(bounds, px(16.)).expect("a mask");
3279        let (b, r) = (m.bounds, m.corner_radii);
3280        let at = |v: Pixels| (f32::from(v) * 100.).round() / 100.;
3281        (
3282            [b.origin.x, b.origin.y, b.size.width, b.size.height].map(at),
3283            [r.top_left, r.top_right, r.bottom_right, r.bottom_left].map(at),
3284        )
3285    }
3286
3287    fn inset(insets: [DefiniteLength; 4], radii: [VnCornerRadius; 4]) -> VnClipPath {
3288        VnClipPath::Inset { reference: BOX, insets, radii }
3289    }
3290
3291    fn ellipse(center: [DefiniteLength; 2], radius: [VnShapeRadius; 2], circle: bool) -> VnClipPath {
3292        VnClipPath::Ellipse { reference: BOX, center, radius, circle }
3293    }
3294
3295    #[test]
3296    fn inset_takes_its_insets_off_the_box_and_fits_its_radii() {
3297        let none = Style::default;
3298        let square = round(len(0.), len(0.));
3299        assert_eq!(Style::default().vn_clip_mask(Bounds::default(), px(16.)), None, "none is no mask");
3300        // `inset(10px 20% round 8px)` on a 200x100 box at (10, 20).
3301        let insets = [len(10.), relative(0.2), len(10.), relative(0.2)];
3302        assert_eq!(
3303            mask(inset(insets, round(len(8.), len(8.))), none(), [10., 20., 200., 100.]),
3304            ([50., 30., 120., 80.], [8.; 4])
3305        );
3306        // The screen-reader-only `inset(50%)` encloses nothing.
3307        let half = relative(0.5);
3308        assert_eq!(mask(inset([half; 4], square), none(), [0., 0., 30., 10.]).0, [15., 5., 0., 0.]);
3309        // Insets past the box leave it empty, not inside out.
3310        assert_eq!(mask(inset([len(80.); 4], square), none(), [0., 0., 100., 100.]).0, [80., 80., 0., 0.]);
3311        // `round 30px` on a 200x20 strip scales by 20 / (30 + 30). A
3312        // percentage radius is of the REFERENCE box: 10% of 200x100 is 20 by
3313        // 10, drawn as the 10px circle.
3314        let strip = [len(40.), len(0.), len(40.), len(0.)];
3315        assert_eq!(mask(inset(strip, round(len(30.), len(30.))), none(), [0., 0., 200., 100.]).1, [10.; 4]);
3316        let ten = relative(0.1);
3317        assert_eq!(mask(inset([len(0.); 4], round(ten, ten)), none(), [0., 0., 200., 100.]).1, [10.; 4]);
3318    }
3319
3320    #[test]
3321    fn circle_and_ellipse_resolve_against_the_box() {
3322        let none = Style::default;
3323        let mid = [relative(0.5), relative(0.5)];
3324        // `circle(50%)` on a square is its disc.
3325        let circle = ellipse(mid, [VnShapeRadius::Length(relative(0.5)); 2], true);
3326        assert_eq!(mask(circle.clone(), none(), [0., 0., 60., 60.]), ([0., 0., 60., 60.], [30.; 4]));
3327        // On 200x100 the percentage is of sqrt(200^2 + 100^2) / sqrt(2), 158.11.
3328        assert_eq!(mask(circle, none(), [0., 0., 200., 100.]).1, [79.06; 4]);
3329        // `circle(closest-side at 25% 50%)`: 50 to the left, top and bottom.
3330        let at = [relative(0.25), relative(0.5)];
3331        assert_eq!(
3332            mask(ellipse(at, [VnShapeRadius::ClosestSide; 2], true), none(), [0., 0., 200., 100.]),
3333            ([0., 0., 100., 100.], [50.; 4])
3334        );
3335        let far = ellipse(at, [VnShapeRadius::FarthestSide; 2], true);
3336        assert_eq!(mask(far, none(), [0., 0., 200., 100.]).1, [150.; 4]);
3337        // `ellipse(closest-side farthest-side)`: each radius in its own axis.
3338        // The mask is its box; the ellipse is the outline (an isolated
3339        // layer), so it is exact.
3340        let e = ellipse(mid, [VnShapeRadius::ClosestSide, VnShapeRadius::FarthestSide], false);
3341        assert_eq!(mask(e.clone(), none(), [0., 0., 200., 100.]), ([0., 0., 200., 100.], [0.; 4]));
3342        let bounds = Bounds::new(point(px(0.), px(0.)), size(px(200.), px(100.)));
3343        let outline = Style { vn_clip_path: e, ..none() }.vn_clip_outline(bounds, px(16.)).expect("an outline");
3344        let g = crate::VnClipGeometry::new(&outline, 1., crate::TransformationMatrix::unit());
3345        assert!(g.contains([100., 50.]) && g.contains([2., 50.]) && g.contains([100., 2.]));
3346        assert!(!g.contains([20., 10.]), "the corner a capsule would keep");
3347        // `ellipse(10px 20% at right 10px center)`: `right 10px` is 100% - 10px.
3348        let right = [DefiniteLength::Calc { fraction: 1., pixels: px(-10.) }, relative(0.5)];
3349        let e = ellipse(right, [VnShapeRadius::Length(len(10.)), VnShapeRadius::Length(relative(0.2))], false);
3350        assert_eq!(mask(e, none(), [0., 0., 200., 100.]), ([180., 30., 20., 40.], [0.; 4]));
3351        // A circle has no outline: the rounded mask is all of it.
3352        let c = Style { vn_clip_path: ellipse(mid, [VnShapeRadius::ClosestSide; 2], true), ..none() };
3353        assert_eq!(c.vn_clip_outline(bounds, px(16.)), None);
3354    }
3355
3356    #[test]
3357    fn a_box_alone_is_rounded_as_the_border_radius_rounds_it() {
3358        let style = || Style {
3359            corner_radii: Corners::all(px(24.)).map(|r| (*r).into()),
3360            border_widths: Edges::all(px(4.).into()),
3361            padding: Edges::all(px(6.).into()),
3362            margin: Edges { top: Length::Auto, ..Edges::all(len(8.).into()) },
3363            ..Style::default()
3364        };
3365        let at = [0., 0., 100., 80.];
3366        assert_eq!(mask(VnClipPath::Box(VnClipBox::Border), style(), at), ([0., 0., 100., 80.], [24.; 4]));
3367        assert_eq!(mask(VnClipPath::Box(VnClipBox::Padding), style(), at), ([4., 4., 92., 72.], [20.; 4]));
3368        assert_eq!(mask(VnClipPath::Box(VnClipBox::Content), style(), at), ([10., 10., 80., 60.], [14.; 4]));
3369        // An `auto` margin is none; a rounded corner grows by the margin.
3370        assert_eq!(mask(VnClipPath::Box(VnClipBox::Margin), style(), at), ([-8., 0., 116., 88.], [32.; 4]));
3371        // An inset's reference box: the content box less 5px.
3372        let clip = VnClipPath::Inset { reference: VnClipBox::Content, insets: [len(5.); 4], radii: round(len(0.), len(0.)) };
3373        assert_eq!(mask(clip, style(), at), ([15., 15., 70., 50.], [0.; 4]));
3374    }
3375
3376    /// A clipped box with a border and a shadow, and a child that overflows
3377    /// it.
3378    struct Clipped;
3379
3380    impl Render for Clipped {
3381        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3382            let mut d = div()
3383                .size(px(60.))
3384                .bg(Hsla::red())
3385                .border_2()
3386                .border_color(Hsla::white())
3387                .shadow(vec![BoxShadow {
3388                    color: Hsla::black(),
3389                    offset: point(px(0.), px(4.)),
3390                    blur_radius: px(8.),
3391                    spread_radius: px(0.),
3392                    inset: false,
3393                }])
3394                .child(div().size(px(100.)).bg(Hsla::green()));
3395            d.style().vn_clip_path = Some(VnClipPath::Ellipse {
3396                reference: VnClipBox::Border,
3397                center: [relative(0.5), relative(0.5)],
3398                radius: [VnShapeRadius::Length(relative(0.5)); 2],
3399                circle: true,
3400            });
3401            div().child(d)
3402        }
3403    }
3404
3405    #[gpui::test]
3406    fn everything_the_element_paints_carries_the_mask(cx: &mut TestAppContext) {
3407        let window = cx.open_window(size(px(200.), px(200.)), |_, _| Clipped);
3408        cx.run_until_parked();
3409        let (quads, shadows, scale) = window
3410            .update(cx, |_, window, _| {
3411                (window.painted_quads(), window.rendered_frame.scene.shadows.clone(), window.scale_factor())
3412            })
3413            .unwrap();
3414        let disc = Bounds::new(point(px(0.), px(0.)), size(px(60.), px(60.))).scale(scale);
3415        let radius = Corners::all(px(30.)).scale(scale);
3416        for color in [Hsla::red(), Hsla::green()] {
3417            let q = quads.iter().find(|q| q.background.as_solid() == Some(color)).expect("the quad");
3418            assert_eq!((q.content_mask.bounds, q.content_mask.corner_radii), (disc, radius), "{color:?}");
3419        }
3420        let border = quads.iter().find(|q| q.border_color == Hsla::white()).expect("the border");
3421        assert_eq!(border.content_mask.bounds, disc);
3422        assert_eq!(shadows.len(), 1);
3423        assert_eq!((shadows[0].content_mask.bounds, shadows[0].content_mask.corner_radii), (disc, radius));
3424    }
3425
3426    fn polygon(reference: VnClipBox, fill_rule: crate::VnFillRule, points: &[[DefiniteLength; 2]]) -> VnClipPath {
3427        VnClipPath::Polygon { reference, fill_rule, points: points.to_vec().into() }
3428    }
3429
3430    fn outline(clip: VnClipPath, style: Style, at: [f32; 4]) -> crate::VnClipOutline {
3431        let bounds = Bounds::new(point(px(at[0]), px(at[1])), size(px(at[2]), px(at[3])));
3432        Style { vn_clip_path: clip, ..style }.vn_clip_outline(bounds, px(16.)).expect("an outline")
3433    }
3434
3435    #[test]
3436    fn a_polygon_resolves_its_percentages_against_the_reference_box() {
3437        use crate::{VnFillRule, VnPathVerb::*};
3438        // `polygon(50% 0, 100% 100%, 0 100%)` on a 200x100 box at (10, 20).
3439        let triangle = [[relative(0.5), len(0.)], [relative(1.), relative(1.)], [len(0.), relative(1.)]];
3440        let o = outline(polygon(BOX, VnFillRule::NonZero, &triangle), Style::default(), [10., 20., 200., 100.]);
3441        assert_eq!(o.verbs, vec![MoveTo([110., 20.]), LineTo([210., 120.]), LineTo([10., 120.]), Close]);
3442        // The mask is the box around it, which culls.
3443        assert_eq!(
3444            mask(polygon(BOX, VnFillRule::NonZero, &triangle), Style::default(), [10., 20., 200., 100.]),
3445            ([10., 20., 200., 100.], [0.; 4])
3446        );
3447        // Against the content box: 4px border and 6px padding in.
3448        let style = || Style {
3449            border_widths: Edges::all(px(4.).into()),
3450            padding: Edges::all(px(6.).into()),
3451            ..Style::default()
3452        };
3453        let o = outline(polygon(VnClipBox::Content, VnFillRule::EvenOdd, &triangle), style(), [0., 0., 100., 100.]);
3454        assert_eq!(o.fill_rule, VnFillRule::EvenOdd);
3455        assert_eq!(o.verbs[0], MoveTo([50., 10.]));
3456        assert_eq!(o.verbs[1], LineTo([90., 90.]));
3457        // `calc()` and a value past the box.
3458        let past = [[DefiniteLength::Calc { fraction: 1., pixels: px(-10.) }, relative(1.5)]];
3459        assert_eq!(
3460            outline(polygon(BOX, VnFillRule::NonZero, &past), Style::default(), [0., 0., 100., 40.]).verbs[0],
3461            MoveTo([90., 60.])
3462        );
3463    }
3464
3465    #[test]
3466    fn a_path_is_laid_from_the_reference_box_corner() {
3467        use crate::{VnFillRule, VnPathVerb::*};
3468        let verbs = vec![MoveTo([0., 0.]), QuadTo([10., 20.], [20., 0.]), Close];
3469        let path = |reference| VnClipPath::Path { reference, fill_rule: VnFillRule::NonZero, verbs: verbs.clone().into() };
3470        let o = outline(path(BOX), Style::default(), [5., 7., 50., 50.]);
3471        assert_eq!(o.verbs, vec![MoveTo([5., 7.]), QuadTo([15., 27.], [25., 7.]), Close]);
3472        let style = Style { padding: Edges::all(px(3.).into()), ..Style::default() };
3473        let o = outline(path(VnClipBox::Content), style, [0., 0., 50., 50.]);
3474        assert_eq!(o.verbs[0], MoveTo([3., 3.]));
3475        // The mask is the control points' box, the curve inside it.
3476        assert_eq!(mask(path(BOX), Style::default(), [5., 7., 50., 50.]).0, [5., 7., 20., 20.]);
3477    }
3478
3479    /// A box clipped to a triangle, with a child in flow and a deferred one.
3480    struct Triangle;
3481
3482    impl Render for Triangle {
3483        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3484            let mut d = div()
3485                .size(px(100.))
3486                .bg(Hsla::red())
3487                .cursor_pointer()
3488                .child(div().size(px(100.)).bg(Hsla::green()))
3489                .child(crate::deferred(div().absolute().top_0().left_0().size(px(50.)).bg(Hsla::blue())).clip_to_ancestors(true));
3490            d.style().vn_clip_path = Some(polygon(
3491                BOX,
3492                crate::VnFillRule::NonZero,
3493                &[[len(0.), len(0.)], [len(100.), len(0.)], [len(0.), len(100.)]],
3494            ));
3495            div().child(d)
3496        }
3497    }
3498
3499    #[gpui::test]
3500    fn a_polygon_paints_into_an_isolated_layer_and_cuts_the_hit_test(cx: &mut TestAppContext) {
3501        let window = cx.open_window(size(px(200.), px(200.)), |_, _| Triangle);
3502        cx.run_until_parked();
3503        window
3504            .update(cx, |_, window, _| {
3505                let scale = window.scale_factor();
3506                let scene = &window.rendered_frame.scene;
3507                // One layer for the box and its child in flow, one re-opened
3508                // for the deferred child; each composites one group.
3509                assert_eq!(scene.vn_layers.len(), 2, "{:?}", scene.vn_layers);
3510                assert_eq!(scene.vn_group_count(), 3);
3511                let root: Vec<_> = scene.vn_batches(0).collect();
3512                assert!(root.iter().all(|b| matches!(b, crate::VnBatch::Layers(_))), "{root:?}");
3513                let colors = |group: usize| -> Vec<Hsla> {
3514                    scene
3515                        .vn_batches(group)
3516                        .filter_map(|b| match b {
3517                            crate::VnBatch::Primitives(crate::PrimitiveBatch::Quads(r)) => Some(r),
3518                            _ => None,
3519                        })
3520                        .flat_map(|r| scene.quads[r].iter().filter_map(|q| q.background.as_solid()).collect::<Vec<_>>())
3521                        .collect()
3522                };
3523                let mut groups: Vec<Vec<Hsla>> = scene.vn_layers.iter().map(|l| colors(l.group as usize)).collect();
3524                groups.sort_by_key(|g| g.len());
3525                assert_eq!(groups, vec![vec![Hsla::blue()], vec![Hsla::red(), Hsla::green()]]);
3526                // Each composite is the triangle's box out to whole pixels
3527                // and a pixel more for the edge, with the triangle's edges.
3528                for layer in &scene.vn_layers {
3529                    assert_eq!(layer.segment_count, 3);
3530                    assert_eq!(layer.fill_rule, 0);
3531                    assert!(layer.bounds.size.width.0 >= 100. * scale);
3532                }
3533                assert_eq!(scene.vn_clip_segments.len(), 6);
3534                // A renderer without layers still gets every primitive.
3535                let flat = scene.batches().count();
3536                assert!(flat >= 2, "{flat}");
3537
3538                // The hitbox: in the triangle, and not past its hypotenuse.
3539                let frame = &window.rendered_frame;
3540                let clipped: Vec<_> = frame.hitboxes.iter().filter(|h| h.vn_clip.is_some()).collect();
3541                assert_eq!(clipped.len(), 1);
3542                let id = clipped[0].id;
3543                let hits = |x: f32, y: f32| frame.hit_test(point(px(x), px(y)), scale).ids.contains(&id);
3544                assert!(hits(10., 10.));
3545                assert!(hits(40., 40.));
3546                assert!(!hits(60., 60.), "inside the box, outside the triangle");
3547                assert!(!hits(150., 10.));
3548            })
3549            .unwrap();
3550    }
3551
3552    fn quad_mask(tint_leaf: bool) -> crate::VnMask {
3553        crate::VnMask {
3554            luminance: false,
3555            tint_leaf,
3556            key: 1,
3557            paint: Some(std::rc::Rc::new(|bounds, tint, window: &mut Window, _: &mut crate::App| {
3558                let half = Bounds::new(bounds.origin, size(bounds.size.width / 2., bounds.size.height));
3559                window.paint_quad(crate::fill(half, tint.unwrap_or_else(Hsla::white)));
3560            })),
3561        }
3562    }
3563
3564    /// A translucent box with a child and a deferred child under a mask, and an icon-like leaf.
3565    struct Masked;
3566
3567    impl Render for Masked {
3568        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
3569            let deferred = crate::deferred(div().absolute().top_0().left_0().size(px(20.)).bg(Hsla::black()));
3570            let mut boxed = div()
3571                .size(px(40.))
3572                .bg(Hsla::red())
3573                .opacity(0.5)
3574                .child(div().size(px(10.)).bg(Hsla::green()))
3575                .child(deferred.clip_to_ancestors(true));
3576            boxed.style().vn_mask = Some(quad_mask(false));
3577            let mut icon = div().size(px(20.)).bg(Hsla::blue());
3578            icon.style().vn_mask = Some(quad_mask(true));
3579            div().child(boxed).child(icon)
3580        }
3581    }
3582
3583    #[gpui::test]
3584    fn a_mask_composites_its_group_through_the_mask_group_and_a_leaf_is_tinted(cx: &mut TestAppContext) {
3585        let window = cx.open_window(size(px(200.), px(200.)), |_, _| Masked);
3586        cx.run_until_parked();
3587        window
3588            .update(cx, |_, window, _| {
3589                let scene = &window.rendered_frame.scene;
3590                assert_eq!(scene.vn_layers.len(), 2, "the box, the deferred child, and no layer for the leaf");
3591                let colors = |group: usize| -> Vec<Hsla> {
3592                    scene
3593                        .vn_batches(group)
3594                        .filter_map(|b| match b {
3595                            crate::VnBatch::Primitives(crate::PrimitiveBatch::Quads(r)) => Some(r),
3596                            _ => None,
3597                        })
3598                        .flat_map(|r| scene.quads[r].iter().filter_map(|q| q.background.as_solid()).collect::<Vec<_>>())
3599                        .collect()
3600                };
3601                let mut groups = Vec::new();
3602                for layer in &scene.vn_layers {
3603                    assert_eq!(layer.fill_rule, 1 << 1, "an alpha mask over a nonzero box");
3604                    let content = colors(layer.group as usize);
3605                    assert!(content.iter().all(|c| (c.a - 0.5).abs() < 1e-3), "{content:?}");
3606                    assert_eq!(colors(layer.group as usize + 1), vec![Hsla::white()], "the mask is not faded");
3607                    groups.push(content.len());
3608                }
3609                groups.sort();
3610                assert_eq!(groups, vec![1, 2], "the deferred child paints through the mask again");
3611                let root = colors(0);
3612                assert_eq!(root, vec![Hsla::blue()], "the leaf paints the mask in its colour");
3613                let leaf = scene.quads.iter().find(|q| q.background.as_solid() == Some(Hsla::blue())).unwrap();
3614                assert_eq!(leaf.bounds.size.width.0, 10. * window.scale_factor());
3615            })
3616            .unwrap();
3617    }
3618}
3619
3620#[cfg(test)]
3621mod vn_border_color_tests {
3622    use super::*;
3623
3624    #[test]
3625    fn independent_border_colors_keep_shared_fallback_and_transparent_sides() {
3626        let mut style = Style { border_color: Some(Hsla::red()), ..Default::default() };
3627        style.vn_border_colors.left = Some(Hsla::transparent_black());
3628        style.vn_border_colors.top = Some(Hsla::blue());
3629        let colors = style.vn_resolved_border_colors();
3630        assert_eq!(colors.top, Hsla::blue());
3631        assert_eq!(colors.right, Hsla::red());
3632        assert!(colors.left.is_transparent());
3633    }
3634
3635    /// A border coloured side by side, with no shared colour, still takes its
3636    /// width off the box its overflow is clipped to.
3637    #[test]
3638    fn overflow_is_clipped_inside_borders_coloured_per_side() {
3639        let mut style = Style::default();
3640        style.overflow = Point { x: Overflow::Hidden, y: Overflow::Hidden };
3641        style.border_widths = Edges::all(px(4.).into());
3642        style.vn_border_colors.top = Some(Hsla::blue());
3643        style.vn_border_colors.left = Some(Hsla::red());
3644        let bounds = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(100.)));
3645        let mask = style.overflow_mask(bounds, px(16.)).unwrap();
3646        assert_eq!(mask.bounds, Bounds::from_corners(point(px(4.), px(4.)), point(px(100.), px(100.))));
3647    }
3648
3649    #[test]
3650    fn colored_border_partitions_cover_rounded_arcs_with_width_weighted_joins() {
3651        let clips = Style::vn_border_side_clips(
3652            Bounds::new(point(px(0.), px(0.)), size(px(80.), px(80.))), Edges::all(px(8.)),
3653        );
3654        let contains = |polygon: &Vec<[f32; 2]>, point: [f32; 2]| {
3655            let mut sign = 0.;
3656            for (a, b) in polygon.iter().zip(polygon.iter().cycle().skip(1)) {
3657                let cross = (b[0] - a[0]) * (point[1] - a[1]) - (b[1] - a[1]) * (point[0] - a[0]);
3658                if cross.abs() < 0.0001 { continue; }
3659                if sign != 0. && cross.signum() != sign { return false; }
3660                sign = cross.signum();
3661            }
3662            polygon.len() >= 3
3663        };
3664        assert!(contains(&clips[0], [15., 13.]), "top rounded arc extends below the rectangular inner top");
3665        assert!(contains(&clips[3], [13., 15.]), "left rounded arc extends beyond the rectangular inner left");
3666        for y in 0..80 {
3667            for x in 0..80 {
3668                assert!(clips.iter().any(|polygon| contains(polygon, [x as f32 + 0.25, y as f32 + 0.25])),
3669                    "coloured side clips must cover the entire quad, including rounded corners");
3670            }
3671        }
3672        let clips = Style::vn_border_side_clips(
3673            Bounds::new(point(px(0.), px(0.)), size(px(100.), px(60.))),
3674            Edges { top: px(4.), right: px(8.), bottom: px(6.), left: px(2.) },
3675        );
3676        assert!(contains(&clips[0], [2., 3.]));
3677        assert!(contains(&clips[3], [2., 5.]), "top/left join uses their2:4width ratio");
3678    }
3679}