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