Skip to main content

sk_css/
mapper.rs

1//! `lightningcss::Property` -> `gpui::StyleRefinement`: this file decides what CSS renders. An
2//! unsupported declaration produces a diagnostic, never silence.
3
4use std::rc::Rc;
5
6use gpui::{
7    px, relative, AbsoluteLength, DefiniteLength, Hsla, Length, Overflow, StyleRefinement,
8    TransformLength, TransformSpec,
9};
10use lightningcss::declaration::DeclarationBlock;
11use lightningcss::properties::align::{ContentPosition, SelfPosition};
12use lightningcss::properties::border::LineStyle;
13use lightningcss::properties::display::{DisplayInside, DisplayKeyword};
14use lightningcss::properties::flex::FlexDirection as CssFlexDirection;
15use lightningcss::properties::font::{
16    AbsoluteFontWeight, FontFamily as CssFontFamily, FontWeight as CssFontWeight,
17    LineHeight as CssLineHeight,
18};
19use lightningcss::properties::masking::ClipPath as CssClipPath;
20use lightningcss::properties::overflow::OverflowKeyword;
21use lightningcss::properties::size::Size as CssSize;
22use lightningcss::properties::text::TextAlign as CssTextAlign;
23use lightningcss::properties::{Property, PropertyId};
24use lightningcss::stylesheet::{ParserOptions, PrinterOptions};
25use lightningcss::values::color::CssColor;
26use lightningcss::values::length::{
27    Length as CssLength, LengthPercentage, LengthPercentageOrAuto, LengthValue,
28};
29use lightningcss::values::percentage::DimensionPercentage;
30
31use crate::keyframes::{AnimationCollector, AnimationPatch, AnimationSpec};
32use crate::rgb_space::RgbSpace;
33use crate::transition::{Collector, TransitionSpec};
34use crate::vars::{self, Vars};
35
36/// `(name, raw value text)` pairs for what cannot be mapped at sheet-compile time: `--x`
37/// declarations and known properties whose value used `var()`, both resolved per element.
38pub type Decls = Vec<(String, String)>;
39
40/// CSS `object-fit`. A local mirror of `gpui::ObjectFit` (which derives neither `Clone` nor
41/// `PartialEq`); the initial value is `fill` while gpui's image default is `Contain`, so the
42/// renderer must state `Fill` explicitly.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum ObjectFit {
45    Fill,
46    Contain,
47    Cover,
48    ScaleDown,
49    None,
50}
51
52/// The CSSWG resolved on 2026-01-21 to standardise Electron's `-webkit-app-region` as `window-drag:
53/// none | move`, and separately that the property is INHERITED.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum WindowDrag {
56    Move,
57    None,
58}
59
60/// CSS `--window-control`: tells Windows 11 which element is the maximize button (snap layouts). A
61/// custom property because a browser ignores those, while an unknown value of a known property
62/// would drop and fall back to the inherited `move`.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub enum WindowControl {
65    Minimize,
66    Maximize,
67    Close,
68    None,
69}
70
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum UserSelect {
73    /// Declared `auto`: kept apart from "not declared" so that it can override an earlier rule's
74    /// `none` in the cascade.
75    Auto,
76    None,
77    Text,
78    All,
79}
80
81#[derive(Clone, Copy, Debug, PartialEq)]
82pub struct DropShadow {
83    pub dx: f32,
84    pub dy: f32,
85    /// The Gaussian's **sigma**, px. CSS's third length and gpui's `blur_radius` are both sigmas,
86    /// so it transfers 1:1.
87    pub blur: f32,
88    pub color: Option<gpui::Hsla>,
89}
90
91/// Which corners' `border-*-radius` is `inherit`, in cascade order. `border-radius` does not
92/// inherit, so `inherit` asks for the PARENT's computed radius, which the mapper cannot know.
93/// The high four bits are the corners' `corner-*-shape`.
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
95pub struct RadiusInherit {
96    pub declared: u8,
97    pub inherit: u8,
98}
99
100impl RadiusInherit {
101    pub const TOP_LEFT: u8 = 1;
102    pub const TOP_RIGHT: u8 = 2;
103    pub const BOTTOM_RIGHT: u8 = 4;
104    pub const BOTTOM_LEFT: u8 = 8;
105    pub const ALL: u8 = 15;
106
107    pub(crate) fn write(&mut self, corners: u8, inherit: bool) {
108        self.declared |= corners;
109        if inherit {
110            self.inherit |= corners;
111        } else {
112            self.inherit &= !corners;
113        }
114    }
115
116    pub(crate) fn refine(&mut self, later: &RadiusInherit) {
117        self.inherit = (self.inherit & !later.declared) | (later.inherit & later.declared);
118        self.declared |= later.declared;
119    }
120}
121
122#[derive(Clone, Debug, Default, PartialEq)]
123pub struct Extras {
124    pub object_fit: Option<ObjectFit>,
125    /// `None` means undeclared, which lets the renderer inherit the parent's value; `Some(None)` is
126    /// an explicit opt-out.
127    pub window_drag: Option<WindowDrag>,
128    pub window_control: Option<WindowControl>,
129    pub fixed: Option<bool>,
130    pub drop_shadow: Option<DropShadow>,
131    /// Whether `sticky` diverges depends on whether an ancestor scrolls, which only the renderer
132    /// knows (`advise_out_of_flow`).
133    pub sticky: Option<bool>,
134    pub z_index: Option<Option<i32>>,
135    pub isolate: Option<bool>,
136    /// The element declared a `position` other than `static`. gpui cannot say this: `static` and
137    /// `relative` both map onto its default `Relative`.
138    pub positioned: Option<bool>,
139    /// The cascade folds only the element's own declaration; `restyle_with` rewrites it to the
140    /// effective (inherited) value before the states are stored.
141    pub pointer_events_none: Option<bool>,
142    /// The declared `visibility`. gpui's own switch also goes off for the screen-reader-only `clip:
143    /// rect(0 0 0 0)`, while CSS `visibility` stays `visible` (read by `el.focus()`).
144    pub visibility_hidden: Option<bool>,
145    /// `user-select` as declared; `auto` defers to the parent when a selection asks
146    /// (`sk_tree::selection`), so it is not folded down.
147    pub user_select: Option<UserSelect>,
148    /// The `display` had an inline outer type. taffy lays the box out block-level, which ignores
149    /// the parent's `text-align`; the renderer advises (`advise_inline_level`).
150    pub inline_level: Option<bool>,
151    pub appearance_none: Option<bool>,
152    pub accent_color: Option<Option<Hsla>>,
153    pub fill: Option<SvgPaint>,
154    pub stroke: Option<SvgPaint>,
155    pub svg_presentation: Option<Rc<Vec<(&'static str, Rc<str>)>>>,
156    /// `text-transform`. gpui has no such text-style field: the shaper is handed a string, so the
157    /// case change is applied to that string by the renderer.
158    pub text_transform: Option<TextTransform>,
159    /// The whitespace-processing half of `white-space`; gpui models only whether a line may wrap,
160    /// so collapsing is applied to the string by the renderer, like `text_transform`.
161    pub white_space: Option<WhiteSpaceMode>,
162    pub content: Option<Rc<str>>,
163    /// `content: none` / `normal` was declared: a later rule that says so takes back the string an
164    /// earlier one gave, where leaving `content` unset says nothing.
165    pub content_none: bool,
166    pub background_clip_text: Option<bool>,
167    /// `-webkit-text-fill-color` overrides foreground `color`, independently of the background
168    /// clipped behind the text.
169    pub text_fill_color: Option<TextFill>,
170    pub background_key_color: Option<gpui::Hsla>,
171    /// Kept apart from the refinement: size/position/repeat are separate properties, often from
172    /// separate rules, folded onto the layers after the cascade.
173    pub background_images: Option<Rc<Vec<BackgroundLayer>>>,
174    pub background_urls: Option<Rc<Vec<BackgroundUrl>>>,
175    pub background_size: Option<Rc<Vec<BackgroundSize>>>,
176    pub background_position: Option<Rc<Vec<(TileLength, TileLength)>>>,
177    pub background_repeat: Option<Rc<Vec<(bool, bool)>>>,
178    pub list_marker: Option<ListMarker>,
179    pub list_marker_inside: Option<bool>,
180    /// The web fonts this element's `font-family` asks for that are not loaded yet: the families of
181    /// the list, up to the one used, that [`set_web_font_families`] named, in order.
182    pub web_font: Option<Rc<[String]>>,
183    pub underline_offset: Option<f32>,
184    pub decoration: DecorationPatch,
185    pub outline: OutlinePatch,
186    /// `currentColor` is the computed `color`, unknown while a declaration is mapped (no inherited
187    /// text property is folded), so targets are recorded and substituted after the cascade.
188    pub current_color: CurrentColorTargets,
189    pub current_color_overrides: CurrentColorTargets,
190    /// `filter: blur()` radius in px. Exact only for a solid, contentless leaf box (the "glow
191    /// blob"), which the renderer repaints as its own shadow.
192    pub blur: Option<f32>,
193    pub filter_url: Option<Rc<str>>,
194    pub scrollbar_width: Option<ScrollbarWidth>,
195    pub scrollbar_color: Option<(gpui::Hsla, gpui::Hsla)>,
196    pub overscroll_x: Option<OverscrollBehavior>,
197    pub overscroll_y: Option<OverscrollBehavior>,
198    /// `contain` includes paint containment: the box clips its content as `overflow: clip` does.
199    pub contain_paint: Option<bool>,
200    /// The axes `contain` size-contains ([`Extras::CONTAIN_WIDTH`], [`Extras::CONTAIN_HEIGHT`]).
201    pub contain_size: Option<u8>,
202    /// `container-type` as the axes it queries ([`crate::container::INLINE`], [`crate::container::BLOCK`]); `Some(0)` is `normal`.
203    pub container_type: Option<u8>,
204    /// `container-name`; `Some(None)` is `none`.
205    pub container_name: Option<Option<Rc<[Rc<str>]>>>,
206    /// `scroll-behavior: smooth`: a programmatic scroll of this box that does not say otherwise glides.
207    pub scroll_smooth: Option<bool>,
208    /// Only a qualifier of the refinement's axis, which stays the truth (see `compute_overflow`).
209    pub overflow_x: Option<OverflowKeyword>,
210    pub overflow_y: Option<OverflowKeyword>,
211    /// `mask-image` (or the `mask` shorthand's images). The three `mask_*` fields are kept apart
212    /// because they cascade apart, and [`Extras::mask_ring`] reads them together.
213    pub mask_images: Option<MaskImages>,
214    pub mask_clips: Option<MaskClips>,
215    pub mask_composite: Option<MaskCompositing>,
216    pub mask: MaskPatch,
217    pub radius_inherit: RadiusInherit,
218    /// `view-transition-name`; `Some(None)` is `none`, `auto` and `match-element` are kept as
219    /// written.
220    pub view_transition_name: Option<Option<Rc<str>>>,
221    /// `view-transition-class`; empty is `none`.
222    pub view_transition_class: Option<Rc<[Rc<str>]>>,
223    /// `mix-blend-mode: plus-lighter` (`Some(false)` is `normal`); only view transition images
224    /// blend.
225    pub plus_lighter: Option<bool>,
226    pub snap: crate::snap::SnapPatch,
227    /// `interpolate-size` as declared (`Some(true)` is `allow-keywords`); it inherits, so the
228    /// renderer reads it through the ancestors.
229    pub interpolate_size: Option<bool>,
230    /// `dynamic-range-limit` as declared; it inherits, so the renderer reads it through the
231    /// ancestors.
232    pub dynamic_range_limit: Option<crate::DynamicRangeLimit>,
233}
234
235#[derive(Clone, Copy, Debug, PartialEq, Eq)]
236pub enum MaskImages {
237    None,
238    TwoOpaque,
239    Other,
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq)]
243pub enum MaskClips {
244    ContentThenBorder,
245    Other,
246}
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249pub enum MaskCompositing {
250    Add,
251    Exclude,
252    Other,
253}
254
255/// The `mask-*` longhands Skathi paints, cascaded apart and folded into layers after the cascade
256/// as the `background-*` ones are.
257#[derive(Clone, Debug, Default, PartialEq)]
258pub struct MaskPatch {
259    pub images: Option<Rc<Vec<BackgroundLayer>>>,
260    pub urls: Option<Rc<Vec<BackgroundUrl>>>,
261    pub size: Option<Rc<Vec<BackgroundSize>>>,
262    pub position: Option<Rc<Vec<(TileLength, TileLength)>>>,
263    pub repeat: Option<Rc<Vec<(bool, bool)>>>,
264    pub luminance: Option<bool>,
265}
266
267impl MaskPatch {
268    fn refine(&mut self, other: &Self) {
269        if other.images.is_some() {
270            self.images = other.images.clone();
271            self.urls = other.urls.clone();
272        }
273        if other.size.is_some() {
274            self.size = other.size.clone();
275        }
276        if other.position.is_some() {
277            self.position = other.position.clone();
278        }
279        if other.repeat.is_some() {
280            self.repeat = other.repeat.clone();
281        }
282        if other.luminance.is_some() {
283            self.luminance = other.luminance;
284        }
285    }
286}
287
288/// The layers of a `mask`, bottom first, and whether they mask by luminance.
289#[derive(Clone, Debug, PartialEq)]
290pub struct MaskStack {
291    pub layers: Vec<PaintLayer>,
292    pub luminance: bool,
293}
294
295#[derive(Clone, Copy, Debug, PartialEq, Eq)]
296pub enum ScrollbarWidth {
297    /// The platform's own width — 14 px here, which is what Windows 11's overlay scrollbar occupies
298    /// when it is not hovered.
299    Auto,
300    /// CSS gives no number; browsers pick something around half, and so do we (8 px).
301    Thin,
302    None,
303}
304
305#[derive(Clone, Copy, Debug, PartialEq, Eq)]
306pub enum OverscrollBehavior {
307    Auto,
308    Contain,
309    None,
310}
311
312impl OverscrollBehavior {
313    pub fn chains(self) -> bool {
314        matches!(self, Self::Auto)
315    }
316}
317
318#[derive(Clone, Copy, Debug, PartialEq, Eq)]
319pub enum TextTransform {
320    None,
321    Uppercase,
322    Lowercase,
323    Capitalize,
324}
325
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327pub enum WhiteSpaceMode {
328    Normal,
329    Nowrap,
330    Pre,
331    PreWrap,
332    PreLine,
333    BreakSpaces,
334}
335
336impl WhiteSpaceMode {
337    pub fn collapses_spaces(self) -> bool {
338        matches!(
339            self,
340            WhiteSpaceMode::Normal | WhiteSpaceMode::Nowrap | WhiteSpaceMode::PreLine
341        )
342    }
343
344    pub fn preserves_newlines(self) -> bool {
345        !matches!(self, WhiteSpaceMode::Normal | WhiteSpaceMode::Nowrap)
346    }
347}
348
349impl TextTransform {
350    pub fn apply(self, text: &str) -> Option<String> {
351        match self {
352            TextTransform::None => None,
353            TextTransform::Uppercase => Some(text.to_uppercase()),
354            TextTransform::Lowercase => Some(text.to_lowercase()),
355            // CSS capitalises the first letter of each WORD and leaves the rest of the word exactly
356            // as authored (it does not lowercase it).
357            TextTransform::Capitalize => {
358                let mut out = String::with_capacity(text.len());
359                let mut at_word_start = true;
360                for ch in text.chars() {
361                    if at_word_start && ch.is_alphabetic() {
362                        out.extend(ch.to_uppercase());
363                        at_word_start = false;
364                    } else {
365                        out.push(ch);
366                        if ch.is_whitespace() {
367                            at_word_start = true;
368                        }
369                    }
370                }
371                Some(out)
372            }
373        }
374    }
375}
376
377#[derive(Clone, Copy, Debug, PartialEq)]
378pub enum TextFill {
379    CurrentColor,
380    Color(Hsla),
381}
382
383#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
384pub enum SvgPaint {
385    None,
386    Current,
387    Color(Hsla),
388    Server,
389}
390
391impl SvgPaint {
392    pub fn as_attr(self) -> std::borrow::Cow<'static, str> {
393        match self {
394            SvgPaint::None => "none".into(),
395            SvgPaint::Current | SvgPaint::Server => "currentColor".into(),
396            SvgPaint::Color(c) => {
397                let c = gpui::Rgba::from(c);
398                let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
399                let (r, g, b) = (q(c.r), q(c.g), q(c.b));
400                let a = (c.a.clamp(0.0, 1.0) * 1000.0).round() / 1000.0;
401                if a >= 1.0 {
402                    format!("rgb({r},{g},{b})").into()
403                } else {
404                    format!("rgba({r},{g},{b},{a})").into()
405                }
406            }
407        }
408    }
409}
410
411#[derive(Clone, Copy, Debug, Default, PartialEq)]
412pub struct DecorationPatch {
413    /// `Some(None)` is the `text-decoration` shorthand's reset to `currentColor`: it ends an
414    /// earlier rule's colour.
415    pub color: Option<Option<Hsla>>,
416    pub thickness: Option<f32>,
417    pub wavy: Option<bool>,
418}
419
420impl DecorationPatch {
421    pub(crate) fn refine(&mut self, other: &Self) {
422        if other.color.is_some() {
423            self.color = other.color;
424        }
425        if other.thickness.is_some() {
426            self.thickness = other.thickness;
427        }
428        if other.wavy.is_some() {
429            self.wavy = other.wavy;
430        }
431    }
432
433    /// Applied to the decoration the whole cascade produced: the colour lives on gpui's decoration,
434    /// and `underline decoration-red-500` is separate rules in either order. A `none` decoration
435    /// (zero thickness, transparent) is left alone so a thickness cannot revive it.
436    pub(crate) fn apply(&self, text: &mut gpui::TextStyleRefinement) {
437        let cancelled = |thickness: gpui::Pixels, color: Option<Hsla>| {
438            thickness == px(0.0) && color == Some(gpui::transparent_black())
439        };
440        if let Some(underline) = text.underline.as_mut() {
441            if !cancelled(underline.thickness, underline.color) {
442                if let Some(Some(color)) = self.color {
443                    underline.color = Some(color);
444                }
445                if let Some(thickness) = self.thickness {
446                    underline.thickness = px(thickness);
447                }
448                if let Some(wavy) = self.wavy {
449                    underline.wavy = wavy;
450                }
451            }
452        }
453        if let Some(strikethrough) = text.strikethrough.as_mut() {
454            if !cancelled(strikethrough.thickness, strikethrough.color) {
455                if let Some(Some(color)) = self.color {
456                    strikethrough.color = Some(color);
457                }
458                if let Some(thickness) = self.thickness {
459                    strikethrough.thickness = px(thickness);
460                }
461            }
462        }
463    }
464}
465
466/// gpui paints a zero-thickness line as nothing, so a declared line starts at CSS `auto`'s usual 1px.
467fn underline_line() -> gpui::UnderlineStyle {
468    gpui::UnderlineStyle {
469        thickness: px(1.0),
470        ..Default::default()
471    }
472}
473
474fn strike_line() -> gpui::StrikethroughStyle {
475    gpui::StrikethroughStyle {
476        thickness: px(1.0),
477        color: None,
478    }
479}
480
481#[derive(Clone, Copy, Debug, Default, PartialEq)]
482pub struct OutlinePatch {
483    pub width: Option<f32>,
484    pub style: Option<gpui::BorderStyle>,
485    pub hidden: Option<bool>,
486    pub color: Option<Option<Hsla>>,
487    pub offset: Option<f32>,
488}
489
490impl OutlinePatch {
491    pub(crate) fn refine(&mut self, other: &Self) {
492        if other.width.is_some() {
493            self.width = other.width;
494        }
495        if other.style.is_some() {
496            self.style = other.style;
497        }
498        if other.hidden.is_some() {
499            self.hidden = other.hidden;
500        }
501        if other.color.is_some() {
502            self.color = other.color;
503        }
504        if other.offset.is_some() {
505            self.offset = other.offset;
506        }
507    }
508
509    pub(crate) fn merge_over(
510        &self,
511        earlier: Option<gpui::Outline>,
512        slot: &mut Option<gpui::Outline>,
513    ) {
514        let Some(mut ring) = earlier else { return };
515        if *self == Self::default() {
516            return;
517        }
518        if self.hidden == Some(true) {
519            ring.width = px(0.0);
520        } else {
521            if let Some(style) = self.style {
522                ring.style = style;
523                if ring.width == px(0.0) {
524                    ring.width = px(3.0);
525                }
526            }
527            if let Some(width) = self.width {
528                ring.width = px(width);
529            }
530        }
531        if let Some(Some(color)) = self.color {
532            ring.color = color;
533        }
534        if let Some(offset) = self.offset {
535            ring.offset = px(offset);
536        }
537        *slot = Some(ring);
538    }
539
540    /// A rung's ring is laid over the base whole, so what the rung left undeclared must come from
541    /// the base ring, not the seed: `:focus { outline-offset: 4px }` keeps the width and colour of
542    /// `outline: 2px solid`.
543    pub(crate) fn inherit_from(&self, base: gpui::Outline, ring: &mut gpui::Outline) {
544        if self.width.is_none() && self.hidden != Some(true) {
545            let medium = self.style.is_some() && ring.width == px(3.0) && base.width > px(0.0);
546            if ring.width == px(0.0) || medium {
547                ring.width = base.width;
548            }
549        }
550        if self.offset.is_none() && ring.offset == px(0.0) {
551            ring.offset = base.offset;
552        }
553        if self.color.is_none() && ring.color == Hsla::default() {
554            ring.color = base.color;
555        }
556        if self.style.is_none() && ring.style == gpui::BorderStyle::Solid {
557            ring.style = base.style;
558        }
559    }
560}
561
562impl Extras {
563    pub(crate) fn refine(&mut self, other: &Extras) {
564        if other.object_fit.is_some() {
565            self.object_fit = other.object_fit;
566        }
567        if other.window_drag.is_some() {
568            self.window_drag = other.window_drag;
569        }
570        if other.window_control.is_some() {
571            self.window_control = other.window_control;
572        }
573        if other.fixed.is_some() {
574            self.fixed = other.fixed;
575        }
576        if other.sticky.is_some() {
577            self.sticky = other.sticky;
578        }
579        if other.appearance_none.is_some() {
580            self.appearance_none = other.appearance_none;
581        }
582        if other.accent_color.is_some() {
583            self.accent_color = other.accent_color;
584        }
585        if other.z_index.is_some() {
586            self.z_index = other.z_index;
587        }
588        if other.isolate.is_some() {
589            self.isolate = other.isolate;
590        }
591        if other.view_transition_name.is_some() {
592            self.view_transition_name = other.view_transition_name.clone();
593        }
594        if other.view_transition_class.is_some() {
595            self.view_transition_class = other.view_transition_class.clone();
596        }
597        if other.plus_lighter.is_some() {
598            self.plus_lighter = other.plus_lighter;
599        }
600        self.snap.refine(&other.snap);
601        if other.interpolate_size.is_some() {
602            self.interpolate_size = other.interpolate_size;
603        }
604        if other.dynamic_range_limit.is_some() {
605            self.dynamic_range_limit = other.dynamic_range_limit;
606        }
607        if other.positioned.is_some() {
608            self.positioned = other.positioned;
609        }
610        if other.pointer_events_none.is_some() {
611            self.pointer_events_none = other.pointer_events_none;
612        }
613        if other.visibility_hidden.is_some() {
614            self.visibility_hidden = other.visibility_hidden;
615        }
616        if other.user_select.is_some() {
617            self.user_select = other.user_select;
618        }
619        if other.inline_level.is_some() {
620            self.inline_level = other.inline_level;
621        }
622        if other.fill.is_some() {
623            self.fill = other.fill;
624        }
625        if other.stroke.is_some() {
626            self.stroke = other.stroke;
627        }
628        if other.white_space.is_some() {
629            self.white_space = other.white_space;
630        }
631        if other.text_transform.is_some() {
632            self.text_transform = other.text_transform;
633        }
634        if other.content.is_some() {
635            self.content = other.content.clone();
636            self.content_none = false;
637        } else if other.content_none {
638            self.content = None;
639            self.content_none = true;
640        }
641        if other.blur.is_some() {
642            self.blur = other.blur;
643            self.drop_shadow = other.drop_shadow;
644            self.filter_url = other.filter_url.clone();
645        }
646        if other.background_clip_text.is_some() {
647            self.background_clip_text = other.background_clip_text;
648        }
649        if other.text_fill_color.is_some() {
650            self.text_fill_color = other.text_fill_color;
651        }
652        if let Some(theirs) = &other.svg_presentation {
653            self.svg_presentation = Some(match self.svg_presentation.take() {
654                None => theirs.clone(),
655                Some(mine) => {
656                    let mut merged = (*mine).clone();
657                    for (name, value) in theirs.iter() {
658                        set_presentation(&mut merged, name, value.clone());
659                    }
660                    Rc::new(merged)
661                }
662            });
663        }
664        if other.background_key_color.is_some() {
665            self.background_key_color = other.background_key_color;
666        }
667        if other.background_images.is_some() {
668            self.background_images = other.background_images.clone();
669            self.background_urls = other.background_urls.clone();
670        }
671        if other.background_size.is_some() {
672            self.background_size = other.background_size.clone();
673        }
674        if other.background_position.is_some() {
675            self.background_position = other.background_position.clone();
676        }
677        if other.background_repeat.is_some() {
678            self.background_repeat = other.background_repeat.clone();
679        }
680        if other.list_marker.is_some() {
681            self.list_marker = other.list_marker;
682        }
683        if other.list_marker_inside.is_some() {
684            self.list_marker_inside = other.list_marker_inside;
685        }
686        if other.web_font.is_some() {
687            self.web_font = other.web_font.clone();
688        }
689        if other.underline_offset.is_some() {
690            self.underline_offset = other.underline_offset;
691        }
692        self.decoration.refine(&other.decoration);
693        self.outline.refine(&other.outline);
694        if other.scrollbar_width.is_some() {
695            self.scrollbar_width = other.scrollbar_width;
696        }
697        if other.scrollbar_color.is_some() {
698            self.scrollbar_color = other.scrollbar_color;
699        }
700        if other.overscroll_x.is_some() {
701            self.overscroll_x = other.overscroll_x;
702        }
703        if other.overscroll_y.is_some() {
704            self.overscroll_y = other.overscroll_y;
705        }
706        if other.contain_paint.is_some() {
707            self.contain_paint = other.contain_paint;
708        }
709        if other.contain_size.is_some() {
710            self.contain_size = other.contain_size;
711        }
712        if other.container_type.is_some() {
713            self.container_type = other.container_type;
714        }
715        if other.container_name.is_some() {
716            self.container_name = other.container_name.clone();
717        }
718        if other.scroll_smooth.is_some() {
719            self.scroll_smooth = other.scroll_smooth;
720        }
721        if other.overflow_x.is_some() {
722            self.overflow_x = other.overflow_x;
723        }
724        if other.overflow_y.is_some() {
725            self.overflow_y = other.overflow_y;
726        }
727        if other.mask_images.is_some() {
728            self.mask_images = other.mask_images;
729        }
730        if other.mask_clips.is_some() {
731            self.mask_clips = other.mask_clips;
732        }
733        if other.mask_composite.is_some() {
734            self.mask_composite = other.mask_composite;
735        }
736        self.mask.refine(&other.mask);
737        self.current_color.0 =
738            (self.current_color.0 & !other.current_color_overrides.0) | other.current_color.0;
739        self.current_color_overrides.0 |= other.current_color_overrides.0;
740        self.radius_inherit.refine(&other.radius_inherit);
741    }
742
743    pub fn mask_ring(&self) -> bool {
744        self.mask_images == Some(MaskImages::TwoOpaque)
745            && self.mask_clips == Some(MaskClips::ContentThenBorder)
746            && self.mask_composite == Some(MaskCompositing::Exclude)
747    }
748
749    pub fn resolve_background_layers(&self) -> Vec<gpui::Background> {
750        let Some(images) = self.background_images.as_ref() else {
751            return Vec::new();
752        };
753        let mut out: Vec<gpui::Background> = images
754            .iter()
755            .map(|layer| self.tiled_gradient(layer))
756            .collect();
757        out.reverse();
758        out
759    }
760
761    pub fn resolve_background_stack(&self) -> Option<Vec<PaintLayer>> {
762        self.background_urls.as_ref().filter(|u| !u.is_empty())?;
763        Some(self.background_tiles().stack(
764            self.background_images.as_deref(),
765            self.background_urls.as_deref(),
766        ))
767    }
768
769    /// The `mask` to paint, or `None` when every layer is `none`. Not for the gradient-border ring
770    /// ([`Extras::mask_ring`]), which the background paints itself.
771    pub fn resolve_mask_stack(&self) -> Option<MaskStack> {
772        if self.mask_ring() {
773            return None;
774        }
775        let m = &self.mask;
776        let tiles = Tiles {
777            size: m.size.as_ref(),
778            position: m.position.as_ref(),
779            repeat: m.repeat.as_ref(),
780        };
781        let layers = tiles.stack(m.images.as_deref(), m.urls.as_deref());
782        (!layers.is_empty()).then(|| MaskStack {
783            layers,
784            luminance: m.luminance == Some(true),
785        })
786    }
787
788    fn background_tiles(&self) -> Tiles<'_> {
789        Tiles {
790            size: self.background_size.as_ref(),
791            position: self.background_position.as_ref(),
792            repeat: self.background_repeat.as_ref(),
793        }
794    }
795
796    fn tiled_gradient(&self, layer: &BackgroundLayer) -> gpui::Background {
797        self.background_tiles().gradient(layer)
798    }
799
800    pub fn z(&self) -> Option<i32> {
801        self.z_index.flatten()
802    }
803
804    /// A superset of what the renderer defers (whether `z-index` applies depends on the parent's
805    /// display); safe for a cache that refuses boundaries conservatively.
806    pub fn may_defer(&self) -> bool {
807        self.z().is_some_and(|z| z != 0) || self.fixed == Some(true)
808    }
809}
810
811/// One declaration block, split into normal/important halves. `None` for a list means "not
812/// declared", so a later rule can override without an empty list reading as `transition: none`.
813pub(crate) struct Converted {
814    pub normal: Option<Rc<StyleRefinement>>,
815    pub important: Option<Rc<StyleRefinement>>,
816    pub normal_transitions: Option<Rc<Vec<TransitionSpec>>>,
817    pub important_transitions: Option<Rc<Vec<TransitionSpec>>>,
818    pub normal_transition_declarations: Option<Rc<Collector>>,
819    pub important_transition_declarations: Option<Rc<Collector>>,
820    pub normal_animations: Option<Rc<Vec<AnimationSpec>>>,
821    pub important_animations: Option<Rc<Vec<AnimationSpec>>>,
822    pub normal_animation_patch: Option<AnimationPatch>,
823    pub important_animation_patch: Option<AnimationPatch>,
824    pub normal_extras: Extras,
825    pub important_extras: Extras,
826    pub normal_custom: Option<Rc<Decls>>,
827    pub important_custom: Option<Rc<Decls>>,
828    pub normal_dynamic: Option<Rc<Decls>>,
829    pub important_dynamic: Option<Rc<Decls>>,
830    pub normal_font: Option<FontDecls>,
831    pub important_font: Option<FontDecls>,
832    /// Kept with the rule and logged when it matches: a compile-time advisory describes the
833    /// stylesheet, not what is wrong with the page.
834    pub diagnostics: Option<Rc<Vec<String>>>,
835}
836
837/// Font-relative declarations from the first one that read an em to the end of the half, plus the
838/// static ones after it so a later `padding-left: 4px` still beats an earlier `padding: 1em`.
839pub type FontDecls = Rc<Vec<Property<'static>>>;
840
841#[derive(Default)]
842struct Half {
843    refinement: Option<Rc<StyleRefinement>>,
844    transitions: Option<Rc<Vec<TransitionSpec>>>,
845    transition_declarations: Option<Rc<Collector>>,
846    animations: Option<Rc<Vec<AnimationSpec>>>,
847    animation_patch: Option<AnimationPatch>,
848    extras: Extras,
849    custom: Option<Rc<Decls>>,
850    dynamic: Option<Rc<Decls>>,
851    font: Option<FontDecls>,
852}
853
854fn apply_static<'i>(
855    p: &Property<'i>,
856    r: &mut StyleRefinement,
857    x: &mut Extras,
858    font: &mut Option<Vec<Property<'static>>>,
859    diagnostics: &mut Vec<String>,
860) {
861    use lightningcss::traits::IntoOwned as _;
862    // A `light-dark()` resolves per element, so it is re-applied with the font-relative ones.
863    let (((), relative), schemed) =
864        noting_light_dark(|| noting_font_units(|| apply(p, r, x, diagnostics)));
865    if relative || schemed || font.is_some() {
866        font.get_or_insert_with(Vec::new)
867            .push(p.clone().into_owned());
868    }
869}
870
871enum Channel {
872    Custom(String, String),
873    Dynamic(String, String),
874    Static,
875}
876
877/// `Property`'s own `ToCss` writes `name: value`, and a property name can never contain `:`, so the
878/// split is exact.
879fn value_text(p: &Property) -> Option<String> {
880    let css = p.to_css_string(false, PrinterOptions::default()).ok()?;
881    let (_, value) = css.split_once(':')?;
882    Some(value.trim().to_string())
883}
884
885/// Insets do not inherit, so both keywords mean `auto`, including the logical spellings under this
886/// engine's horizontal-tb/ltr model.
887fn initial_inset_sides(name: &str, value: &lightningcss::properties::custom::TokenList<'_>) -> u8 {
888    if !single_ident_is(value, "initial") && !single_ident_is(value, "unset") {
889        return 0;
890    }
891    match name {
892        "top" | "inset-block-start" => 0b0001,
893        "right" | "inset-inline-end" => 0b0010,
894        "bottom" | "inset-block-end" => 0b0100,
895        "left" | "inset-inline-start" => 0b1000,
896        "inset-block" => 0b0101,
897        "inset-inline" => 0b1010,
898        "inset" => 0b1111,
899        _ => 0,
900    }
901}
902
903pub(crate) fn decl_pairs(block: &DeclarationBlock) -> Vec<(String, String, bool)> {
904    let mut out = Vec::new();
905    for (props, important) in [
906        (&block.declarations, false),
907        (&block.important_declarations, true),
908    ] {
909        for p in props.iter() {
910            let Some(css) = p.to_css_string(false, PrinterOptions::default()).ok() else {
911                continue;
912            };
913            match css.split_once(':') {
914                Some((name, value)) => {
915                    out.push((name.trim().to_string(), value.trim().to_string(), important))
916                }
917                // A property that prints without a colon cannot exist, but a dropped declaration
918                // would be a lie in a provenance panel.
919                None => out.push((css, String::new(), important)),
920            }
921        }
922    }
923    out
924}
925
926fn channel(p: &Property, diagnostics: &mut Vec<String>) -> Channel {
927    use lightningcss::properties::custom::CustomPropertyName;
928    match p {
929        Property::Custom(c) => match &c.name {
930            CustomPropertyName::Custom(name) if name.0.as_ref() == effect::SHADING => {
931                Channel::Static
932            }
933            CustomPropertyName::Custom(name) if name.0.as_ref() == WINDOW_CONTROL => {
934                Channel::Static
935            }
936            CustomPropertyName::Custom(name) => match value_text(p) {
937                Some(v) => Channel::Custom(name.0.as_ref().to_string(), v),
938                None => {
939                    once(
940                        diagnostics,
941                        format!(
942                            "`{}` could not be serialized back to text and was dropped (v1)",
943                            name.0.as_ref()
944                        ),
945                    );
946                    Channel::Static
947                }
948            },
949            CustomPropertyName::Unknown(name)
950                if has_substitution(&c.value) || has_current_color_function(&c.value) =>
951            {
952                match value_text(p) {
953                    Some(v) => Channel::Dynamic(name.0.as_ref().to_string(), v),
954                    None => Channel::Static,
955                }
956            }
957            CustomPropertyName::Unknown(_) => Channel::Static,
958        },
959        // Inherited and read per element (`light-dark()`, controls): it travels with the custom
960        // properties, under a name `var()` cannot reach.
961        Property::ColorScheme(_) => match value_text(p) {
962            Some(v) => Channel::Custom(COLOR_SCHEME.to_string(), v),
963            None => Channel::Static,
964        },
965        Property::Unparsed(u) if matches!(u.property_id, PropertyId::ColorScheme) => {
966            match value_text(p) {
967                Some(v) => Channel::Custom(COLOR_SCHEME.to_string(), v),
968                None => Channel::Static,
969            }
970        }
971        Property::Unparsed(u)
972            if matches!(u.property_id, PropertyId::ClipPath(_)) && !has_substitution(&u.value) =>
973        {
974            Channel::Static
975        }
976        Property::Unparsed(u) if initial_inset_sides(u.property_id.name(), &u.value) != 0 => {
977            Channel::Static
978        }
979        Property::Unparsed(u) => match value_text(p) {
980            Some(v) => Channel::Dynamic(u.property_id.name().to_string(), v),
981            None => Channel::Static,
982        },
983        _ => Channel::Static,
984    }
985}
986
987pub(crate) fn convert_block(block: &DeclarationBlock) -> Converted {
988    let mut diagnostics: Vec<String> = Vec::new();
989    let diagnostics = &mut diagnostics;
990    let mut convert = |props: &[Property]| -> Half {
991        if props.is_empty() {
992            return Half::default();
993        }
994        let mut r = StyleRefinement::default();
995        let mut extras = Extras::default();
996        let mut transitions = Collector::default();
997        let mut animations = AnimationCollector::default();
998        let mut custom: Decls = Vec::new();
999        let mut dynamic: Decls = Vec::new();
1000        let mut font: Option<Vec<Property<'static>>> = None;
1001        let mut styled = false;
1002        for p in props {
1003            // `-moz-osx-font-smoothing`, `-webkit-touch-callout`: dropped without a word, as
1004            // Chromium drops them (`crate::prefix`).
1005            if crate::prefix::property_dropped(p) {
1006                continue;
1007            }
1008            match channel(p, diagnostics) {
1009                Channel::Custom(name, value) => custom.push((name, value)),
1010                Channel::Dynamic(name, value) => dynamic.push((name, value)),
1011                Channel::Static => {
1012                    if transitions.take(p, diagnostics) {
1013                        continue;
1014                    }
1015                    if animations.take(p, diagnostics) {
1016                        continue;
1017                    }
1018                    let id = p.property_id();
1019                    if dynamic.iter().any(|(n, _)| *n == id.name()) {
1020                        once(
1021                            diagnostics,
1022                            format!(
1023                                "`{}` is declared twice in one rule, once through var() and once \
1024                                 literally — the literal one wins regardless of source order (v1)",
1025                                id.name()
1026                            ),
1027                        );
1028                    }
1029                    apply_static(p, &mut r, &mut extras, &mut font, diagnostics);
1030                    styled = true;
1031                }
1032            }
1033        }
1034        let (animation_list, animation_patch) = animations.finish();
1035        Half {
1036            refinement: styled.then(|| Rc::new(r)),
1037            transition_declarations: transitions.declarations(),
1038            transitions: transitions.finish().map(Rc::new),
1039            animations: animation_list.map(Rc::new),
1040            animation_patch,
1041            extras,
1042            custom: (!custom.is_empty()).then(|| Rc::new(custom)),
1043            dynamic: (!dynamic.is_empty()).then(|| Rc::new(dynamic)),
1044            font: font.map(Rc::new),
1045        }
1046    };
1047    let normal = convert(&block.declarations);
1048    let important = convert(&block.important_declarations);
1049    let diagnostics = std::mem::take(diagnostics);
1050    Converted {
1051        normal: normal.refinement,
1052        important: important.refinement,
1053        normal_transitions: normal.transitions,
1054        important_transitions: important.transitions,
1055        normal_transition_declarations: normal.transition_declarations,
1056        important_transition_declarations: important.transition_declarations,
1057        normal_animations: normal.animations,
1058        important_animations: important.animations,
1059        normal_animation_patch: normal.animation_patch,
1060        important_animation_patch: important.animation_patch,
1061        normal_extras: normal.extras,
1062        important_extras: important.extras,
1063        normal_custom: normal.custom,
1064        important_custom: important.custom,
1065        normal_dynamic: normal.dynamic,
1066        important_dynamic: important.dynamic,
1067        normal_font: normal.font,
1068        important_font: important.font,
1069        diagnostics: (!diagnostics.is_empty()).then(|| Rc::new(diagnostics)),
1070    }
1071}
1072
1073thread_local! {
1074    /// While an element computes: what `currentColor` stands for inside a colour function — the
1075    /// parent's colour in `color` itself, the element's own everywhere else — and whether a
1076    /// declaration read it.
1077    static CURRENT_COLOR: std::cell::Cell<Option<(Hsla, Hsla)>> = const { std::cell::Cell::new(None) };
1078    static CURRENT_COLOR_READ: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1079}
1080
1081/// The `currentColor` context of one element's cascade. `own` is a guess until the cascade has
1082/// computed `color`; [`CurrentColorScope::read`] says whether a second pass with the real one is
1083/// needed.
1084pub(crate) struct CurrentColorScope {
1085    outer: Option<(Hsla, Hsla)>,
1086    outer_read: bool,
1087}
1088
1089impl CurrentColorScope {
1090    pub(crate) fn enter(parent: Hsla, own: Hsla) -> Self {
1091        Self {
1092            outer: CURRENT_COLOR.with(|c| c.replace(Some((parent, own)))),
1093            outer_read: CURRENT_COLOR_READ.with(|r| r.replace(false)),
1094        }
1095    }
1096
1097    pub(crate) fn read(&self) -> bool {
1098        CURRENT_COLOR_READ.with(std::cell::Cell::get)
1099    }
1100}
1101
1102impl Drop for CurrentColorScope {
1103    fn drop(&mut self) {
1104        CURRENT_COLOR.with(|c| c.set(self.outer));
1105        CURRENT_COLOR_READ.with(|r| r.set(self.outer_read));
1106    }
1107}
1108
1109/// `value` with each `currentColor` keyword spelled as the colour it stands for, so that
1110/// `color-mix()` and relative colours over it compute; `None` outside an element's cascade or
1111/// when there is no such keyword.
1112fn current_color_substituted(name: &str, value: &str) -> Option<String> {
1113    const KEYWORD: &str = "currentcolor";
1114    let lower = value.to_ascii_lowercase();
1115    let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'-' || b == b'_';
1116    let bytes = lower.as_bytes();
1117    let starts: Vec<usize> = lower
1118        .match_indices(KEYWORD)
1119        .map(|(at, _)| at)
1120        .filter(|&at| {
1121            let end = at + KEYWORD.len();
1122            (at == 0 || !ident(bytes[at - 1])) && (end == bytes.len() || !ident(bytes[end]))
1123        })
1124        .collect();
1125    if starts.is_empty() {
1126        return None;
1127    }
1128    let (parent, own) = CURRENT_COLOR.with(std::cell::Cell::get)?;
1129    CURRENT_COLOR_READ.with(|r| r.set(true));
1130    let c = gpui::Rgba::from(if name == "color" { parent } else { own });
1131    let literal = format!(
1132        "rgb({} {} {} / {})",
1133        c.r * 255.0,
1134        c.g * 255.0,
1135        c.b * 255.0,
1136        c.a
1137    );
1138    let mut out = String::with_capacity(value.len() + starts.len() * literal.len());
1139    let mut from = 0;
1140    for at in starts {
1141        out.push_str(&value[from..at]);
1142        out.push_str(&literal);
1143        from = at + KEYWORD.len();
1144    }
1145    out.push_str(&value[from..]);
1146    Some(out)
1147}
1148
1149/// Three failures, each advised: invalid substitution (missing variable, cycle), a substituted text
1150/// that does not parse, or a property the mapper does not map. Invalid ones are dropped, as in CSS.
1151pub(crate) fn apply_dynamic(
1152    name: &str,
1153    raw: &str,
1154    vars: &Vars,
1155    env: &crate::Env,
1156    r: &mut StyleRefinement,
1157    x: &mut Extras,
1158    diagnostics: &mut Vec<String>,
1159) {
1160    let value = match vars::substitute_with(raw, vars, env) {
1161        Ok(v) => v,
1162        // An unset `var()` with no fallback invalidates the declaration at computed-value time;
1163        // routine, so silent. The other errors are author mistakes and still speak.
1164        Err(vars::VarError::Unresolved(_)) => return,
1165        Err(e) => {
1166            once(
1167                diagnostics,
1168                format!(
1169                    "`{name}: {raw}` is invalid at computed-value time — {} (the declaration was \
1170                     dropped, as it would be in a browser)",
1171                    e.describe()
1172                ),
1173            );
1174            return;
1175        }
1176    };
1177    let value = crate::rgb_space::rewrite(&value).unwrap_or(value);
1178    use lightningcss::traits::IntoOwned as _;
1179    let parse = |value: &str| {
1180        Property::parse_string(PropertyId::from(name), value, ParserOptions::default())
1181            .ok()
1182            .map(|p| p.into_owned())
1183    };
1184    let property = match parse(&value) {
1185        Some(unresolved @ (Property::Unparsed(_) | Property::Custom(_))) => {
1186            match current_color_substituted(name, &value) {
1187                Some(concrete) => parse(&concrete),
1188                None => Some(unresolved),
1189            }
1190        }
1191        parsed => parsed,
1192    };
1193    let Some(property) = property else {
1194        once(
1195            diagnostics,
1196            format!("`{name}: {value}` did not parse after var() substitution (v1)"),
1197        );
1198        return;
1199    };
1200    // A `transition` is folded into its own list at sheet-compile time and the list is per rule,
1201    // not per element — so a var()-composed one has nowhere to land.
1202    if matches!(
1203        property,
1204        Property::Transition(..)
1205            | Property::TransitionProperty(..)
1206            | Property::TransitionDuration(..)
1207            | Property::TransitionDelay(..)
1208            | Property::TransitionTimingFunction(..)
1209    ) {
1210        once(
1211            diagnostics,
1212            format!(
1213                "`{name}` composed with var() is not honoured (v1) — the transition list is folded \
1214                 once per rule, not per element; declare the transition literally"
1215            ),
1216        );
1217        return;
1218    }
1219    apply(&property, r, x, diagnostics);
1220}
1221
1222pub fn parse_inline(body: &str, diagnostics: &mut Vec<String>) -> StyleRefinement {
1223    let (refinement, transitions, _) = parse_inline_full(body, diagnostics);
1224    if !transitions.is_empty() {
1225        diagnostics.push(
1226            "inline `transition` is parsed but dropped by parse_inline — the caller must use \
1227             parse_inline_with_transitions to honor it"
1228                .into(),
1229        );
1230    }
1231    refinement
1232}
1233
1234pub fn parse_inline_with_transitions(
1235    body: &str,
1236    diagnostics: &mut Vec<String>,
1237) -> (StyleRefinement, Vec<TransitionSpec>) {
1238    let (r, t, _) = parse_inline_full(body, diagnostics);
1239    (r, t)
1240}
1241
1242pub fn parse_inline_full(
1243    body: &str,
1244    diagnostics: &mut Vec<String>,
1245) -> (StyleRefinement, Vec<TransitionSpec>, Extras) {
1246    let inline = parse_inline_style(body, diagnostics);
1247    (
1248        inline.refinement.map(|r| (*r).clone()).unwrap_or_default(),
1249        inline.transitions.map(|t| (*t).clone()).unwrap_or_default(),
1250        inline.extras,
1251    )
1252}
1253
1254#[derive(Clone, Debug, Default)]
1255pub struct InlineMotion {
1256    pub(crate) transitions: Option<Rc<Collector>>,
1257    pub(crate) animations: Option<AnimationPatch>,
1258}
1259impl InlineMotion {
1260    fn is_empty(&self) -> bool {
1261        self.transitions.is_none() && self.animations.is_none()
1262    }
1263}
1264
1265#[derive(Clone, Debug, Default, PartialEq)]
1266pub struct InlinePriority {
1267    pub refinement: Option<Rc<StyleRefinement>>,
1268    pub extras: Extras,
1269    pub custom: Option<Rc<Decls>>,
1270    pub dynamic: Option<Rc<Decls>>,
1271    pub font: Option<FontDecls>,
1272}
1273
1274#[derive(Clone, Debug, Default)]
1275pub struct InlineStyle {
1276    pub normal_motion: Option<InlineMotion>,
1277    pub important_motion: Option<InlineMotion>,
1278    pub refinement: Option<Rc<StyleRefinement>>,
1279    /// `None` = the body declared no `transition` at all (which is what lets a matched rule's list
1280    /// survive); `Some([])` is `transition: none`.
1281    pub transitions: Option<Rc<Vec<TransitionSpec>>>,
1282    /// Inline `animation`: reka-ui's `Presence` writes `animationName = "none"` to cancel an exit
1283    /// animation, so it must be representable.
1284    pub animations: Option<Rc<Vec<AnimationSpec>>>,
1285    /// Longhand-only `animation-*`; folding `animationFillMode = "forwards"` as a list would delete
1286    /// the animation it means to freeze.
1287    pub animation_patch: Option<AnimationPatch>,
1288    pub extras: Extras,
1289    pub custom: Decls,
1290    pub dynamic: Decls,
1291    /// An inline `padding: .5em` is the element's own em, which the parse cannot know.
1292    pub font: Option<FontDecls>,
1293    #[doc(hidden)]
1294    pub priority: Option<Rc<[InlinePriority; 2]>>,
1295}
1296
1297impl InlineStyle {
1298    pub fn is_empty(&self) -> bool {
1299        self.refinement.is_none()
1300            && self.transitions.is_none()
1301            && self.animations.is_none()
1302            && self.animation_patch.is_none()
1303            && self.extras == Extras::default()
1304            && self.custom.is_empty()
1305            && self.dynamic.is_empty()
1306            && self.font.is_none()
1307    }
1308}
1309
1310/// Does the engine apply `name: value`? What `CSS.supports`, `@supports` and the `:style` array form
1311/// answer.
1312pub fn accepts_declaration(name: &str, value: &str) -> bool {
1313    matches!(verdict(name, value), Verdict::Applied | Verdict::Inert)
1314}
1315
1316/// What the mapper does with one declaration.
1317#[derive(Clone, Debug, PartialEq, Eq)]
1318pub enum Verdict {
1319    /// It changes the computed style.
1320    Applied,
1321    /// Accepted without an advisory, and changes nothing here (`tab-size`, `scroll-margin`).
1322    Inert,
1323    /// Parsed, then not applied: the first advisory the mapper gave.
1324    Rejected(String),
1325    /// A vendor-prefixed spelling dropped without an advisory.
1326    Dropped,
1327    /// Not one valid declaration.
1328    Invalid,
1329}
1330
1331pub fn verdict(name: &str, value: &str) -> Verdict {
1332    let name = name.trim();
1333    if name.starts_with("--") {
1334        return if value.contains(';') {
1335            Verdict::Invalid
1336        } else {
1337            Verdict::Applied
1338        };
1339    }
1340    let body = format!("{name}: {value}");
1341    let body = crate::rgb_space::rewrite(&body).unwrap_or(body);
1342    let Ok(block) = DeclarationBlock::parse_string(&body, ParserOptions::default()) else {
1343        return Verdict::Invalid;
1344    };
1345    if block.len() != 1 {
1346        return Verdict::Invalid;
1347    }
1348    let p = block
1349        .declarations
1350        .iter()
1351        .chain(block.important_declarations.iter())
1352        .next();
1353    if p.is_some_and(crate::prefix::property_dropped) {
1354        return Verdict::Dropped;
1355    }
1356    let mut diagnostics = Vec::new();
1357    let changed = match p {
1358        Some(Property::Unparsed(u)) => {
1359            if has_substitution(&u.value) || is_css_wide_keyword(&u.value) {
1360                return Verdict::Applied;
1361            }
1362            let (mut r, mut x) = (StyleRefinement::default(), Extras::default());
1363            if !apply_unparsed(u, &mut r, &mut x, &mut diagnostics) {
1364                return Verdict::Invalid;
1365            }
1366            r != StyleRefinement::default() || x != Extras::default()
1367        }
1368        Some(Property::Custom(c)) if has_substitution(&c.value) => return Verdict::Applied,
1369        _ => {
1370            let style = parse_inline_style(&body, &mut diagnostics);
1371            style
1372                .refinement
1373                .as_deref()
1374                .is_some_and(|s| *s != StyleRefinement::default())
1375                || style.extras != Extras::default()
1376                || style.transitions.is_some()
1377                || style.animations.is_some()
1378                || style.animation_patch.is_some()
1379                || style.font.is_some()
1380                || !style.custom.is_empty()
1381        }
1382    };
1383    if let Some(first) = diagnostics.into_iter().next() {
1384        return Verdict::Rejected(first);
1385    }
1386    if changed {
1387        Verdict::Applied
1388    } else {
1389        Verdict::Inert
1390    }
1391}
1392
1393pub fn parse_inline_style(body: &str, diagnostics: &mut Vec<String>) -> InlineStyle {
1394    let rewritten = crate::rgb_space::rewrite(body);
1395    let body = rewritten.as_deref().unwrap_or(body);
1396    let mut r = StyleRefinement::default();
1397    let mut extras = Extras::default();
1398    let mut normal_transitions = Collector::default();
1399    let mut important_transitions = Collector::default();
1400    let mut normal_animations = AnimationCollector::default();
1401    let mut important_animations = AnimationCollector::default();
1402    let mut custom: Decls = Vec::new();
1403    let mut dynamic: Decls = Vec::new();
1404    let mut font: Option<Vec<Property<'static>>> = None;
1405    let mut styled = false;
1406    let mut priority = None;
1407    // Without it one bad declaration cost the element its whole inline style.
1408    let warnings = std::sync::Arc::new(std::sync::RwLock::new(Vec::new()));
1409    let options = ParserOptions {
1410        error_recovery: true,
1411        warnings: Some(warnings.clone()),
1412        ..ParserOptions::default()
1413    };
1414    let parsed = DeclarationBlock::parse_string(body, options);
1415    if let Ok(skipped) = warnings.read() {
1416        for e in skipped.iter() {
1417            diagnostics.push(format!(
1418                "inline style: {e} in {body:?} — skipped, as a browser skips it"
1419            ));
1420        }
1421    }
1422    match parsed {
1423        Ok(block) => {
1424            for (important, declarations) in [
1425                (false, &block.declarations),
1426                (true, &block.important_declarations),
1427            ] {
1428                let transitions = if important {
1429                    &mut important_transitions
1430                } else {
1431                    &mut normal_transitions
1432                };
1433                let animations = if important {
1434                    &mut important_animations
1435                } else {
1436                    &mut normal_animations
1437                };
1438                for p in declarations {
1439                    if crate::prefix::property_dropped(p) {
1440                        continue;
1441                    }
1442                    match channel(p, diagnostics) {
1443                        Channel::Custom(name, value) => custom.push((name, value)),
1444                        Channel::Dynamic(name, value) => dynamic.push((name, value)),
1445                        Channel::Static => {
1446                            if transitions.take(p, diagnostics) {
1447                                continue;
1448                            }
1449                            if animations.take(p, diagnostics) {
1450                                continue;
1451                            }
1452                            apply_static(p, &mut r, &mut extras, &mut font, diagnostics);
1453                            styled = true;
1454                        }
1455                    }
1456                }
1457            }
1458            if !custom.is_empty() || !dynamic.is_empty() || !block.important_declarations.is_empty()
1459            {
1460                let converted = convert_block(&block);
1461                let half = |important| InlinePriority {
1462                    refinement: if important {
1463                        converted.important.clone()
1464                    } else {
1465                        converted.normal.clone()
1466                    },
1467                    extras: if important {
1468                        converted.important_extras.clone()
1469                    } else {
1470                        converted.normal_extras.clone()
1471                    },
1472                    custom: if important {
1473                        converted.important_custom.clone()
1474                    } else {
1475                        converted.normal_custom.clone()
1476                    },
1477                    dynamic: if important {
1478                        converted.important_dynamic.clone()
1479                    } else {
1480                        converted.normal_dynamic.clone()
1481                    },
1482                    font: if important {
1483                        converted.important_font.clone()
1484                    } else {
1485                        converted.normal_font.clone()
1486                    },
1487                };
1488                priority = Some(Rc::new([half(false), half(true)]));
1489            }
1490        }
1491        Err(e) => diagnostics.push(format!("inline style parse error: {e} in {body:?}")),
1492    }
1493    let normal_motion = InlineMotion {
1494        transitions: normal_transitions.declarations(),
1495        animations: normal_animations.clone().finish().1,
1496    };
1497    let important_motion = InlineMotion {
1498        transitions: important_transitions.declarations(),
1499        animations: important_animations.clone().finish().1,
1500    };
1501    normal_transitions.merge(&important_transitions);
1502    normal_animations.merge(&important_animations);
1503    let (animation_list, animation_patch) = normal_animations.finish();
1504    InlineStyle {
1505        normal_motion: (!normal_motion.is_empty()).then_some(normal_motion),
1506        important_motion: (!important_motion.is_empty()).then_some(important_motion),
1507        refinement: styled.then(|| Rc::new(r)),
1508        transitions: normal_transitions.finish().map(Rc::new),
1509        animations: animation_list.map(Rc::new),
1510        animation_patch,
1511        extras,
1512        custom,
1513        dynamic,
1514        font: font.map(Rc::new),
1515        priority,
1516    }
1517}
1518
1519fn color(c: &CssColor) -> Option<Hsla> {
1520    let [r, g, b, a] = srgb(c)?;
1521    Some(gpui::Rgba { r, g, b, a }.into())
1522}
1523
1524/// A CSS `<color>` as sRGB channels, `None` for anything else, `currentColor` and system colours.
1525pub fn parse_color(text: &str) -> Option<[f32; 4]> {
1526    parse_color_in(text, RgbSpace::Srgb).map(|c| c.map(|v| v.clamp(0.0, 1.0)))
1527}
1528
1529/// A CSS `<color>` in `space`, unclipped: out-of-gamut and HDR components survive.
1530pub fn parse_color_in(text: &str, space: RgbSpace) -> Option<[f32; 4]> {
1531    use lightningcss::traits::Parse as _;
1532    let text = text.trim();
1533    if let Some([r, g, b, a]) = crate::rgb_space::display_p3_linear(text) {
1534        let [r, g, b] = crate::rgb_space::convert_rgb([r, g, b], RgbSpace::DisplayP3Linear, space);
1535        return Some([r, g, b, a]);
1536    }
1537    in_space(&CssColor::parse_string(text).ok()?, space)
1538}
1539
1540fn in_space(c: &CssColor, space: RgbSpace) -> Option<[f32; 4]> {
1541    use lightningcss::values::color::{ColorSpace as _, SRGBLinear, P3, SRGB};
1542    let [r, g, b, a] = match c {
1543        CssColor::LightDark(light, dark) => {
1544            LIGHT_DARK_SEEN.with(|seen| seen.set(true));
1545            let dark_scheme = COLOR_SCHEME_DARK.with(std::cell::Cell::get);
1546            return in_space(if dark_scheme { dark } else { light }, space);
1547        }
1548        CssColor::CurrentColor | CssColor::System(_) => return None,
1549        _ => match space {
1550            RgbSpace::Srgb => {
1551                let c = SRGB::try_from(c).ok()?.resolve_missing();
1552                [c.r, c.g, c.b, c.alpha]
1553            }
1554            RgbSpace::SrgbLinear => {
1555                let c = SRGBLinear::try_from(c).ok()?.resolve_missing();
1556                [c.r, c.g, c.b, c.alpha]
1557            }
1558            RgbSpace::DisplayP3 | RgbSpace::DisplayP3Linear => {
1559                let c = P3::try_from(c).ok()?.resolve_missing();
1560                [c.r, c.g, c.b, c.alpha]
1561            }
1562        },
1563    };
1564    Some(if space == RgbSpace::DisplayP3Linear {
1565        let [r, g, b] = [r, g, b].map(crate::rgb_space::to_linear);
1566        [r, g, b, a]
1567    } else {
1568        [r, g, b, a]
1569    })
1570}
1571
1572/// A concrete colour in sRGB channels. `lab()`, `oklch()`, `color()` and the rest are converted
1573/// and clipped per channel, which is what browsers paint on an sRGB display; `color-mix()` and
1574/// relative colours arrive here already computed.
1575pub(crate) fn srgb(c: &CssColor) -> Option<[f32; 4]> {
1576    use lightningcss::values::color::{ColorSpace, SRGB};
1577    match c {
1578        CssColor::RGBA(c) => Some([
1579            c.red as f32 / 255.0,
1580            c.green as f32 / 255.0,
1581            c.blue as f32 / 255.0,
1582            c.alpha_f32(),
1583        ]),
1584        CssColor::LAB(_) | CssColor::Predefined(_) | CssColor::Float(_) => {
1585            let c = SRGB::try_from(c).ok()?.resolve_missing();
1586            Some([c.r, c.g, c.b, c.alpha].map(|v| v.clamp(0.0, 1.0)))
1587        }
1588        CssColor::LightDark(light, dark) => {
1589            LIGHT_DARK_SEEN.with(|seen| seen.set(true));
1590            srgb(if COLOR_SCHEME_DARK.with(std::cell::Cell::get) {
1591                dark
1592            } else {
1593                light
1594            })
1595        }
1596        CssColor::CurrentColor | CssColor::System(_) => None,
1597    }
1598}
1599
1600/// The name `color-scheme` is carried under among the inherited custom properties.
1601pub const COLOR_SCHEME: &str = "color-scheme";
1602
1603thread_local! {
1604    /// The used color scheme of the element computing; light outside a cascade (a sheet compiling).
1605    static COLOR_SCHEME_DARK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1606    static LIGHT_DARK_SEEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1607}
1608
1609/// Resolves `light-dark()` to its dark half while alive.
1610pub(crate) struct ColorSchemeScope(bool);
1611
1612impl ColorSchemeScope {
1613    pub(crate) fn enter(dark: bool) -> Self {
1614        Self(COLOR_SCHEME_DARK.with(|c| c.replace(dark)))
1615    }
1616}
1617
1618impl Drop for ColorSchemeScope {
1619    fn drop(&mut self) {
1620        COLOR_SCHEME_DARK.with(|c| c.set(self.0));
1621    }
1622}
1623
1624fn noting_light_dark<R>(f: impl FnOnce() -> R) -> (R, bool) {
1625    let outer = LIGHT_DARK_SEEN.with(|seen| seen.replace(false));
1626    let out = f();
1627    let seen = LIGHT_DARK_SEEN.with(|cell| {
1628        let seen = cell.get();
1629        cell.set(outer || seen);
1630        seen
1631    });
1632    (out, seen)
1633}
1634
1635thread_local! {
1636    static REM_BASIS: std::cell::Cell<f32> = const { std::cell::Cell::new(INITIAL_REM_BASIS) };
1637    static VIEWPORT_BASIS: std::cell::Cell<(f32, f32)> =
1638        const { std::cell::Cell::new(INITIAL_VIEWPORT_BASIS) };
1639    /// Set the first time a sheet resolves a viewport unit. Nothing else has to recompile when the
1640    /// window resizes, and almost no sheet uses one.
1641    static VIEWPORT_UNITS_SEEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1642    static CALC_DROPPED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1643    static FONT_SOURCE: std::cell::RefCell<Option<Box<dyn Fn() -> Vec<String>>>> =
1644        const { std::cell::RefCell::new(None) };
1645    static INSTALLED_FONTS: std::cell::RefCell<Option<Rc<std::collections::HashSet<String>>>> =
1646        const { std::cell::RefCell::new(None) };
1647    static FONT_MISSES: std::cell::RefCell<Vec<(String, Option<String>)>> =
1648        const { std::cell::RefCell::new(Vec::new()) };
1649    static WEB_FONTS: std::cell::RefCell<std::collections::HashSet<String>> =
1650        std::cell::RefCell::new(std::collections::HashSet::new());
1651}
1652
1653pub fn set_web_font_families(families: impl IntoIterator<Item = String>) {
1654    let set = families.into_iter().map(|f| f.to_lowercase()).collect();
1655    WEB_FONTS.with(|w| *w.borrow_mut() = set);
1656}
1657
1658fn waiting_web_font(families: &[CssFontFamily]) -> Option<Rc<[String]>> {
1659    use lightningcss::traits::ToCss;
1660    WEB_FONTS.with(|w| {
1661        let w = w.borrow();
1662        if w.is_empty() {
1663            return None;
1664        }
1665        let mut out = Vec::new();
1666        for f in families {
1667            let CssFontFamily::FamilyName(name) = f else {
1668                break;
1669            };
1670            let Ok(css) = name.to_css_string(Default::default()) else {
1671                continue;
1672            };
1673            let clean = css.trim_matches('"');
1674            if w.contains(&clean.to_lowercase()) {
1675                out.push(clean.to_string());
1676            }
1677            if font_installed(clean) != Some(false) {
1678                break;
1679            }
1680        }
1681        Some(Rc::from(out))
1682    })
1683}
1684
1685/// Read lazily on the first `font-family`: enumerating installed families is costly. Without a
1686/// source every named family counts as installed.
1687pub fn set_font_source(source: impl Fn() -> Vec<String> + 'static) {
1688    FONT_SOURCE.with(|s| *s.borrow_mut() = Some(Box::new(source)));
1689    INSTALLED_FONTS.with(|c| *c.borrow_mut() = None);
1690}
1691
1692fn font_installed(name: &str) -> Option<bool> {
1693    let set = INSTALLED_FONTS.with(|c| c.borrow().clone()).or_else(|| {
1694        let names = FONT_SOURCE.with(|s| s.borrow().as_ref().map(|f| f()))?;
1695        let set = Rc::new(names.into_iter().collect::<std::collections::HashSet<_>>());
1696        INSTALLED_FONTS.with(|c| *c.borrow_mut() = Some(set.clone()));
1697        Some(set)
1698    })?;
1699    Some(set.contains(name))
1700}
1701
1702pub fn take_font_misses() -> Vec<(String, Option<String>)> {
1703    FONT_MISSES.with(|m| std::mem::take(&mut *m.borrow_mut()))
1704}
1705
1706fn note_font_miss(asked: String, used: Option<String>) {
1707    FONT_MISSES.with(|m| {
1708        let mut m = m.borrow_mut();
1709        if !m.iter().any(|(a, _)| *a == asked) {
1710            m.push((asked, used));
1711        }
1712    });
1713}
1714
1715/// Maps a generic to a family. The `ui-*` four are Safari-only (Chrome skips them, so do we);
1716/// `emoji` / `math` / `fangsong` are never a list's primary font.
1717fn generic_family(g: &lightningcss::properties::font::GenericFontFamily) -> Option<String> {
1718    use lightningcss::properties::font::GenericFontFamily as G;
1719    let candidates: &[&str] = match g {
1720        G::SystemUI => return Some(".SystemUIFont".into()),
1721        G::SansSerif => &["Arial", "Helvetica", "Liberation Sans"],
1722        G::Serif => &["Times New Roman", "Times", "Liberation Serif"],
1723        G::Monospace => &[
1724            "Consolas",
1725            "Menlo",
1726            "DejaVu Sans Mono",
1727            "Liberation Mono",
1728            "Courier New",
1729        ],
1730        G::Cursive => &["Comic Sans MS"],
1731        G::Fantasy => &["Impact"],
1732        _ => return None,
1733    };
1734    Some(
1735        candidates
1736            .iter()
1737            .find(|c| font_installed(c) != Some(false))
1738            .map_or(".SystemUIFont", |c| *c)
1739            .into(),
1740    )
1741}
1742
1743fn first_available_family(families: &[CssFontFamily]) -> Option<String> {
1744    use lightningcss::traits::ToCss;
1745    let mut first_named = None;
1746    let mut asked_first = None;
1747    for (i, f) in families.iter().enumerate() {
1748        let found = match f {
1749            CssFontFamily::FamilyName(name) => {
1750                let Ok(css) = name.to_css_string(Default::default()) else {
1751                    continue;
1752                };
1753                let clean = css.trim_matches('"').to_string();
1754                if font_installed(&clean) == Some(false) {
1755                    if i == 0 {
1756                        asked_first = Some(clean.clone());
1757                    }
1758                    first_named.get_or_insert(clean);
1759                    None
1760                } else {
1761                    Some(clean)
1762                }
1763            }
1764            CssFontFamily::Generic(g) => generic_family(g),
1765        };
1766        if let Some(used) = found {
1767            if let Some(asked) = asked_first {
1768                note_font_miss(asked, Some(used.clone()));
1769            }
1770            return Some(used);
1771        }
1772    }
1773    if let Some(asked) = asked_first {
1774        note_font_miss(asked, None);
1775    }
1776    first_named
1777}
1778
1779thread_local! {
1780    static COMPOSED_FONTS: std::cell::RefCell<Vec<(String, bool)>> = const { std::cell::RefCell::new(Vec::new()) };
1781    static UNREACHED_FONTS: std::cell::RefCell<Vec<(String, String)>> = const { std::cell::RefCell::new(Vec::new()) };
1782}
1783
1784pub fn set_composed_font_families(families: impl IntoIterator<Item = (String, bool)>) {
1785    let list = families
1786        .into_iter()
1787        .map(|(f, latin)| (f.to_lowercase(), latin))
1788        .collect();
1789    COMPOSED_FONTS.with(|c| *c.borrow_mut() = list);
1790}
1791
1792pub fn take_unreached_fonts() -> Vec<(String, String)> {
1793    UNREACHED_FONTS.with(|m| std::mem::take(&mut *m.borrow_mut()))
1794}
1795
1796fn composed_font_stack(families: &[CssFontFamily]) -> Option<(String, gpui::FontFallbacks)> {
1797    use lightningcss::traits::ToCss;
1798    let composed = COMPOSED_FONTS.with(|c| c.borrow().clone());
1799    if composed.is_empty() {
1800        return None;
1801    }
1802    let mut stack: Vec<(String, Option<bool>)> = Vec::new();
1803    for f in families {
1804        let (name, generic) = match f {
1805            CssFontFamily::FamilyName(name) => {
1806                let Ok(css) = name.to_css_string(Default::default()) else {
1807                    continue;
1808                };
1809                (css.trim_matches('"').to_string(), false)
1810            }
1811            CssFontFamily::Generic(g) => match generic_family(g) {
1812                Some(name) => (name, true),
1813                None => continue,
1814            },
1815        };
1816        let latin = composed
1817            .iter()
1818            .find(|(c, _)| c.eq_ignore_ascii_case(&name))
1819            .map(|c| c.1);
1820        if latin.is_none() && !generic && font_installed(&name) == Some(false) {
1821            continue;
1822        }
1823        if !stack.iter().any(|(s, _)| s.eq_ignore_ascii_case(&name)) {
1824            stack.push((name, latin));
1825        }
1826    }
1827    let (first, latin) = stack.first()?.clone();
1828    if latin.is_none() {
1829        // An installed family draws the text; a composed one after it is reached only by the
1830        // characters it lacks, and DirectWrite's own fallback takes those.
1831        for (name, _) in stack.iter().skip(1).filter(|s| s.1.is_some()) {
1832            UNREACHED_FONTS.with(|u| {
1833                let mut u = u.borrow_mut();
1834                if !u.iter().any(|(n, _)| n == name) {
1835                    u.push((name.clone(), first.clone()));
1836                }
1837            });
1838        }
1839        return Some((first, gpui::FontFallbacks::default()));
1840    }
1841    let rest = stack.into_iter().skip(1).map(|s| s.0).collect();
1842    Some((first, gpui::FontFallbacks::from_fonts(rest)))
1843}
1844
1845pub const INITIAL_REM_BASIS: f32 = 16.0;
1846
1847pub fn rem_basis() -> f32 {
1848    REM_BASIS.with(|c| c.get())
1849}
1850
1851/// Sets the px value of `1rem`, reporting a change. `rem` is flattened at parse time, so
1852/// already-compiled sheets do not move; out-of-range values (0.0 during boot) are refused.
1853pub fn set_rem_basis(px: f32) -> bool {
1854    if !(px.is_finite() && (1.0..=200.0).contains(&px)) {
1855        return false;
1856    }
1857    REM_BASIS.with(|c| {
1858        if (c.get() - px).abs() < f32::EPSILON {
1859            false
1860        } else {
1861            c.set(px);
1862            true
1863        }
1864    })
1865}
1866
1867/// Must be non-zero: 0 would collapse every `vh` before the first `set_env`.
1868pub const INITIAL_VIEWPORT_BASIS: (f32, f32) = (1280.0, 720.0);
1869
1870pub fn viewport_basis() -> (f32, f32) {
1871    VIEWPORT_BASIS.with(|c| c.get())
1872}
1873
1874pub fn uses_viewport_units() -> bool {
1875    VIEWPORT_UNITS_SEEN.with(|c| c.get())
1876}
1877
1878pub fn reset_viewport_units_seen() {
1879    VIEWPORT_UNITS_SEEN.with(|c| c.set(false));
1880}
1881
1882pub(crate) fn noting_viewport_units<R>(f: impl FnOnce() -> R) -> (R, bool) {
1883    let before = VIEWPORT_UNITS_SEEN.with(|c| c.replace(false));
1884    let out = f();
1885    let seen = VIEWPORT_UNITS_SEEN.with(|c| c.get());
1886    VIEWPORT_UNITS_SEEN.with(|c| c.set(before || seen));
1887    (out, seen)
1888}
1889
1890pub fn set_viewport_basis(width: f32, height: f32) -> bool {
1891    if !(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0) {
1892        return false;
1893    }
1894    VIEWPORT_BASIS.with(|c| {
1895        let (w, h) = c.get();
1896        if (w - width).abs() < f32::EPSILON && (h - height).abs() < f32::EPSILON {
1897            false
1898        } else {
1899            c.set((width, height));
1900            true
1901        }
1902    })
1903}
1904
1905/// The small/large/dynamic families are the same number on a desktop window (no collapsing browser
1906/// chrome); resolved rather than dropped because `max-h-[85vh]` is what keeps a dialog inside the
1907/// window.
1908fn viewport_value_px(v: &LengthValue) -> Option<f32> {
1909    let (w, h) = viewport_basis();
1910    let px = match v {
1911        LengthValue::Vw(p)
1912        | LengthValue::Svw(p)
1913        | LengthValue::Lvw(p)
1914        | LengthValue::Dvw(p)
1915        | LengthValue::Vi(p)
1916        | LengthValue::Svi(p)
1917        | LengthValue::Lvi(p)
1918        | LengthValue::Dvi(p) => p / 100.0 * w,
1919        LengthValue::Vh(p)
1920        | LengthValue::Svh(p)
1921        | LengthValue::Lvh(p)
1922        | LengthValue::Dvh(p)
1923        | LengthValue::Vb(p)
1924        | LengthValue::Svb(p)
1925        | LengthValue::Lvb(p)
1926        | LengthValue::Dvb(p) => p / 100.0 * h,
1927        LengthValue::Vmin(p)
1928        | LengthValue::Svmin(p)
1929        | LengthValue::Lvmin(p)
1930        | LengthValue::Dvmin(p) => p / 100.0 * w.min(h),
1931        LengthValue::Vmax(p)
1932        | LengthValue::Svmax(p)
1933        | LengthValue::Lvmax(p)
1934        | LengthValue::Dvmax(p) => p / 100.0 * w.max(h),
1935        _ => return None,
1936    };
1937    VIEWPORT_UNITS_SEEN.with(|c| c.set(true));
1938    Some(px)
1939}
1940
1941fn viewport_unit_px(unit: &str, value: f32) -> Option<f32> {
1942    let (w, h) = viewport_basis();
1943    let basis = match unit {
1944        "vw" | "svw" | "lvw" | "dvw" | "vi" | "svi" | "lvi" | "dvi" => w,
1945        "vh" | "svh" | "lvh" | "dvh" | "vb" | "svb" | "lvb" | "dvb" => h,
1946        "vmin" | "svmin" | "lvmin" | "dvmin" => w.min(h),
1947        "vmax" | "svmax" | "lvmax" | "dvmax" => w.max(h),
1948        _ => return None,
1949    };
1950    VIEWPORT_UNITS_SEEN.with(|c| c.set(true));
1951    Some(value / 100.0 * basis)
1952}
1953
1954fn length_value_px(v: &LengthValue) -> Option<f32> {
1955    match v {
1956        LengthValue::Px(v) => Some(*v),
1957        LengthValue::Rem(v) => Some(v * rem_basis()),
1958        LengthValue::Em(v) => Some(v * em_basis()),
1959        LengthValue::Ch(v) => Some(v * character_basis(false)),
1960        LengthValue::Ex(v) => Some(v * character_basis(true)),
1961        LengthValue::Rch(v) | LengthValue::Rex(v) => Some(v * HALF_EM * rem_basis()),
1962        other => crate::container::unit_px(other).or_else(|| viewport_value_px(other)),
1963    }
1964}
1965
1966// CSS Values 4's fallback when the host cannot measure a font.
1967const HALF_EM: f32 = 0.5;
1968
1969#[derive(Clone, Copy, Debug, PartialEq)]
1970pub struct FontRelativeMetrics {
1971    pub zero_advance: f32,
1972    pub x_height: f32,
1973}
1974
1975thread_local! {
1976    static FONT_METRIC_SOURCE: std::cell::RefCell<Option<Box<dyn Fn(&gpui::Font, f32) -> Option<FontRelativeMetrics>>>> = const { std::cell::RefCell::new(None) };
1977    static FONT_METRIC_GENERATION: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
1978    static FONT_FACE: std::cell::RefCell<Option<gpui::Font>> = const { std::cell::RefCell::new(None) };
1979}
1980
1981/// Installs the host's font metrics. Replacing the source invalidates cached folds, so a style
1982/// computed before host setup cannot retain fallback widths.
1983pub fn set_font_metric_source(
1984    source: impl Fn(&gpui::Font, f32) -> Option<FontRelativeMetrics> + 'static,
1985) {
1986    FONT_METRIC_SOURCE.with(|slot| *slot.borrow_mut() = Some(Box::new(source)));
1987    FONT_METRIC_GENERATION.with(|generation| generation.set(generation.get().wrapping_add(1)));
1988}
1989
1990pub(crate) fn font_metric_generation() -> u32 {
1991    FONT_METRIC_GENERATION.with(|generation| generation.get())
1992}
1993
1994pub(crate) fn with_font_face<R>(font: &gpui::Font, f: impl FnOnce() -> R) -> R {
1995    struct Restore(Option<gpui::Font>);
1996    impl Drop for Restore {
1997        fn drop(&mut self) {
1998            FONT_FACE.with(|slot| *slot.borrow_mut() = self.0.take());
1999        }
2000    }
2001    let _restore = Restore(FONT_FACE.with(|slot| slot.replace(Some(font.clone()))));
2002    f()
2003}
2004
2005fn character_basis(x_height: bool) -> f32 {
2006    let size = em_basis();
2007    let font = FONT_FACE.with(|slot| slot.borrow().clone());
2008    font.and_then(|font| {
2009        FONT_METRIC_SOURCE.with(|slot| {
2010            slot.borrow()
2011                .as_ref()
2012                .and_then(|source| source(&font, size))
2013        })
2014    })
2015    .map(|metrics| {
2016        if x_height {
2017            metrics.x_height
2018        } else {
2019            metrics.zero_advance
2020        }
2021    })
2022    .filter(|value| value.is_finite() && *value > 0.0)
2023    .unwrap_or(HALF_EM * size)
2024}
2025
2026fn font_unit_px(unit: &str, value: f32) -> Option<f32> {
2027    match unit {
2028        "rem" => Some(value * rem_basis()),
2029        "em" => Some(value * em_basis()),
2030        "ch" => Some(value * character_basis(false)),
2031        "ex" => Some(value * character_basis(true)),
2032        "rch" | "rex" => Some(value * HALF_EM * rem_basis()),
2033        _ => None,
2034    }
2035}
2036
2037thread_local! {
2038    static FONT_BASIS: std::cell::Cell<f32> = const { std::cell::Cell::new(f32::NAN) };
2039    static FONT_UNITS_SEEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2040}
2041
2042fn em_basis() -> f32 {
2043    FONT_UNITS_SEEN.with(|c| c.set(true));
2044    let basis = FONT_BASIS.with(|c| c.get());
2045    if basis.is_nan() {
2046        rem_basis()
2047    } else {
2048        basis
2049    }
2050}
2051
2052/// The value read something resolved per element, so it is kept for the cascade to re-apply, like
2053/// an em.
2054pub(crate) fn note_font_relative() {
2055    FONT_UNITS_SEEN.with(|c| c.set(true));
2056}
2057
2058pub(crate) fn with_font_basis<R>(px: f32, f: impl FnOnce() -> R) -> R {
2059    struct Restore(f32);
2060    impl Drop for Restore {
2061        fn drop(&mut self) {
2062            FONT_BASIS.with(|c| c.set(self.0));
2063        }
2064    }
2065    let _restore = Restore(FONT_BASIS.with(|c| c.replace(px)));
2066    f()
2067}
2068
2069pub(crate) fn noting_font_units<R>(f: impl FnOnce() -> R) -> (R, bool) {
2070    let before = FONT_UNITS_SEEN.with(|c| c.replace(false));
2071    let out = f();
2072    let seen = FONT_UNITS_SEEN.with(|c| c.replace(before));
2073    FONT_UNITS_SEEN.with(|c| c.set(before || seen));
2074    (out, seen)
2075}
2076
2077/// Whether `p` sets `font-size`, which resolves its em against the PARENT's font size where every
2078/// other property uses the element's own.
2079pub(crate) fn sets_font_size(p: &Property) -> bool {
2080    matches!(p, Property::FontSize(_))
2081}
2082
2083pub(crate) fn apply_at(
2084    p: &Property,
2085    basis: f32,
2086    r: &mut StyleRefinement,
2087    x: &mut Extras,
2088    diagnostics: &mut Vec<String>,
2089) {
2090    with_font_basis(basis, || apply(p, r, x, diagnostics));
2091}
2092
2093pub(crate) fn font_size_px(l: AbsoluteLength) -> f32 {
2094    match l {
2095        AbsoluteLength::Pixels(p) => f32::from(p),
2096        AbsoluteLength::Rems(r) => r.0 * rem_basis(),
2097    }
2098}
2099
2100fn absolute_font_size_px(k: &lightningcss::properties::font::AbsoluteFontSize) -> f32 {
2101    use lightningcss::properties::font::AbsoluteFontSize as A;
2102    match k {
2103        A::XXSmall => 9.0,
2104        A::XSmall => 10.0,
2105        A::Small => 13.0,
2106        A::Medium => 16.0,
2107        A::Large => 18.0,
2108        A::XLarge => 24.0,
2109        A::XXLarge => 32.0,
2110        A::XXXLarge => 48.0,
2111    }
2112}
2113
2114/// Resolves a linear `calc()` to px; needed for shadcn's radius scale (`calc(var(--radius) -
2115/// 2px)`). A non-finite result is unresolved (`calc(100px / 0)`).
2116fn calc_px<V>(
2117    calc: &lightningcss::values::calc::Calc<V>,
2118    leaf: &dyn Fn(&V) -> Option<f32>,
2119) -> Option<f32> {
2120    calc_term(calc, leaf).filter(|px| px.is_finite())
2121}
2122
2123fn calc_term<V>(
2124    calc: &lightningcss::values::calc::Calc<V>,
2125    leaf: &dyn Fn(&V) -> Option<f32>,
2126) -> Option<f32> {
2127    use lightningcss::values::calc::{Calc, MathFunction};
2128    match calc {
2129        Calc::Value(v) => leaf(v),
2130        Calc::Number(n) => Some(*n),
2131        Calc::Sum(a, b) => Some(calc_term(a, leaf)? + calc_term(b, leaf)?),
2132        Calc::Product(n, v) => Some(n * calc_term(v, leaf)?),
2133        Calc::Function(f) => match &**f {
2134            MathFunction::Calc(c) => calc_term(c, leaf),
2135            MathFunction::Min(list) => list
2136                .iter()
2137                .map(|c| calc_term(c, leaf))
2138                .try_fold(f32::INFINITY, |acc, v| Some(acc.min(v?))),
2139            MathFunction::Max(list) => list
2140                .iter()
2141                .map(|c| calc_term(c, leaf))
2142                .try_fold(f32::NEG_INFINITY, |acc, v| Some(acc.max(v?))),
2143            // `f32::clamp` panics on that, and on a NaN bound.
2144            MathFunction::Clamp(lo, v, hi) => Some(
2145                calc_term(v, leaf)?
2146                    .min(calc_term(hi, leaf)?)
2147                    .max(calc_term(lo, leaf)?),
2148            ),
2149            MathFunction::Abs(v) => Some(calc_term(v, leaf)?.abs()),
2150            MathFunction::Sign(v) => Some(calc_term(v, leaf)?.signum()),
2151            _ => None,
2152        },
2153    }
2154}
2155
2156fn advise_list_marker(diagnostics: &mut Vec<String>) {
2157    warn_once(
2158        diagnostics,
2159        "this list marker is not generated (v1) — the PREDEFINED counter styles (`disc`, \
2160         `circle`, `square`, `decimal`, `decimal-leading-zero`, and the alpha and roman ones) do \
2161         generate a real marker box now. A `@counter-style` rule and a `list-style-image` have no \
2162         model here: the first needs a counter-style engine, the second a raster in the marker \
2163         box. Pick a predefined style, or render the marker as a real element (a `<span>`, or \
2164         `::before { content: \"…\" }`)",
2165    );
2166}
2167
2168fn spacing_px(spacing: &lightningcss::properties::text::Spacing) -> Option<f32> {
2169    use lightningcss::properties::text::Spacing;
2170    match spacing {
2171        Spacing::Normal => Some(0.0),
2172        Spacing::Length(l) => css_length_px(l),
2173    }
2174}
2175
2176fn css_length_px(l: &CssLength) -> Option<f32> {
2177    match l {
2178        CssLength::Value(v) => length_value_px(v),
2179        CssLength::Calc(c) => calc_px(c, &|v: &CssLength| css_length_px(v)),
2180    }
2181}
2182
2183fn lp_leaf_px(lp: &LengthPercentage) -> Option<f32> {
2184    match lp {
2185        DimensionPercentage::Dimension(v) => length_value_px(v),
2186        // A percentage needs the containing block; a calc() that mixes one in is left unresolved
2187        // rather than guessed at.
2188        DimensionPercentage::Percentage(_) => None,
2189        DimensionPercentage::Calc(c) => calc_px(c, &lp_leaf_px),
2190    }
2191}
2192
2193/// `calc_px` for properties whose percentage is not resolved here: a `calc()` mixing one in is
2194/// dropped and advised (`calc_dropped`).
2195fn lp_calc_px(c: &lightningcss::values::calc::Calc<LengthPercentage>) -> Option<f32> {
2196    let v = calc_px(c, &lp_leaf_px);
2197    if v.is_none() {
2198        calc_dropped();
2199    }
2200    v
2201}
2202
2203fn calc_dropped() {
2204    CALC_DROPPED.with(|c| c.set(true));
2205}
2206
2207pub(crate) fn lp_linear(lp: &LengthPercentage) -> Option<(f32, f32)> {
2208    match lp {
2209        DimensionPercentage::Dimension(d) => Some((0.0, length_value_px(d)?)),
2210        DimensionPercentage::Percentage(p) => Some((p.0, 0.0)),
2211        DimensionPercentage::Calc(c) => calc_linear(c),
2212    }
2213}
2214
2215fn calc_linear(c: &lightningcss::values::calc::Calc<LengthPercentage>) -> Option<(f32, f32)> {
2216    use lightningcss::values::calc::{Calc, MathFunction};
2217    match c {
2218        Calc::Value(v) => match &**v {
2219            DimensionPercentage::Dimension(d) => Some((0.0, length_value_px(d)?)),
2220            DimensionPercentage::Percentage(p) => Some((p.0, 0.0)),
2221            DimensionPercentage::Calc(inner) => calc_linear(inner),
2222        },
2223        Calc::Number(_) => None,
2224        Calc::Sum(a, b) => {
2225            let (fa, pa) = calc_linear(a)?;
2226            let (fb, pb) = calc_linear(b)?;
2227            Some((fa + fb, pa + pb))
2228        }
2229        Calc::Product(n, v) => {
2230            let (f, p) = calc_linear(v)?;
2231            Some((n * f, n * p))
2232        }
2233        Calc::Function(f) => match &**f {
2234            MathFunction::Calc(inner) => calc_linear(inner),
2235            _ => calc_px(c, &lp_leaf_px).map(|p| (0.0, p)),
2236        },
2237    }
2238}
2239
2240pub(crate) fn lp_definite(lp: &LengthPercentage) -> Option<DefiniteLength> {
2241    match lp {
2242        DimensionPercentage::Dimension(v) => length_value_px(v).map(|p| px(p).into()),
2243        DimensionPercentage::Percentage(p) => Some(relative(p.0)),
2244        DimensionPercentage::Calc(c) => match calc_px(c, &lp_leaf_px) {
2245            Some(p) => Some(px(p).into()),
2246            None => match calc_linear(c) {
2247                Some((fraction, pixels)) if fraction == 0.0 => Some(px(pixels).into()),
2248                Some((fraction, pixels)) => Some(DefiniteLength::Calc {
2249                    fraction,
2250                    pixels: px(pixels),
2251                }),
2252                None => {
2253                    calc_dropped();
2254                    None
2255                }
2256            },
2257        },
2258    }
2259}
2260
2261fn lpa_length(v: &LengthPercentageOrAuto) -> Option<Length> {
2262    match v {
2263        LengthPercentageOrAuto::Auto => Some(Length::Auto),
2264        LengthPercentageOrAuto::LengthPercentage(lp) => lp_definite(lp).map(Length::Definite),
2265    }
2266}
2267
2268fn size_length(v: &CssSize) -> Option<Length> {
2269    match v {
2270        CssSize::Auto => Some(Length::Auto),
2271        CssSize::LengthPercentage(lp) => lp_definite(lp).map(Length::Definite),
2272        _ => None,
2273    }
2274}
2275
2276fn max_size_length(v: &lightningcss::properties::size::MaxSize) -> Option<Length> {
2277    use lightningcss::properties::size::MaxSize;
2278    match v {
2279        MaxSize::None => Some(Length::Auto),
2280        MaxSize::LengthPercentage(lp) => lp_definite(lp).map(Length::Definite),
2281        _ => None,
2282    }
2283}
2284
2285fn corner(
2286    length: &mut Option<AbsoluteLength>,
2287    relative: &mut Option<Option<gpui::VnCornerRadius>>,
2288    radius: &lightningcss::values::size::Size2D<LengthPercentage>,
2289) -> bool {
2290    let (Some(x), Some(y)) = (lp_definite(&radius.0), lp_definite(&radius.1)) else {
2291        return false;
2292    };
2293    match (x, y) {
2294        (DefiniteLength::Absolute(a), DefiniteLength::Absolute(b)) if a == b => {
2295            *length = Some(a);
2296            *relative = Some(None);
2297        }
2298        (x, y) => {
2299            *length = Some(px(0.).into());
2300            *relative = Some(Some(gpui::VnCornerRadius { x, y }));
2301        }
2302    }
2303    true
2304}
2305
2306fn lp_absolute(lp: &LengthPercentage) -> Option<AbsoluteLength> {
2307    match lp {
2308        DimensionPercentage::Dimension(v) => length_value_px(v).map(|p| px(p).into()),
2309        DimensionPercentage::Calc(c) => lp_calc_px(c).map(|p| px(p).into()),
2310        DimensionPercentage::Percentage(_) => None,
2311    }
2312}
2313
2314fn gap_definite(v: &lightningcss::properties::align::GapValue) -> Option<DefiniteLength> {
2315    use lightningcss::properties::align::GapValue;
2316    match v {
2317        GapValue::LengthPercentage(lp) => lp_definite(lp),
2318        GapValue::Normal => None,
2319    }
2320}
2321
2322fn self_position(v: &SelfPosition) -> gpui::AlignItems {
2323    use gpui::AlignItems as G;
2324    match v {
2325        SelfPosition::Center => G::Center,
2326        SelfPosition::Start | SelfPosition::FlexStart | SelfPosition::SelfStart => G::FlexStart,
2327        SelfPosition::End | SelfPosition::FlexEnd | SelfPosition::SelfEnd => G::FlexEnd,
2328    }
2329}
2330
2331/// `repeat(N, minmax(<min>, 1fr))` — the ONLY track list gpui's `GridTemplate` can express, and
2332/// (not by accident) exactly what Tailwind's `grid-cols-N` / `grid-rows-N` emit.
2333fn grid_template(v: &lightningcss::properties::grid::TrackSizing) -> Option<gpui::GridTemplate> {
2334    use lightningcss::properties::grid::{
2335        RepeatCount, TrackBreadth, TrackListItem, TrackSize, TrackSizing,
2336    };
2337    let TrackSizing::TrackList(list) = v else {
2338        return None;
2339    };
2340    let [TrackListItem::TrackRepeat(repeat)] = list.items.as_slice() else {
2341        return None;
2342    };
2343    let RepeatCount::Number(count) = repeat.count else {
2344        return None;
2345    };
2346    if count < 0 {
2347        return None;
2348    }
2349    let [TrackSize::MinMax { min, max }] = repeat.track_sizes.as_slice() else {
2350        return None;
2351    };
2352    // The max half must be the `1fr` that makes the tracks share the space.
2353    if !matches!(max, TrackBreadth::Flex(f) if *f == 1.0) {
2354        return None;
2355    }
2356    let min_size = match min {
2357        TrackBreadth::Length(DimensionPercentage::Dimension(l))
2358            if length_value_px(l) == Some(0.0) =>
2359        {
2360            gpui::GridTemplateMinSize::Zero
2361        }
2362        TrackBreadth::MinContent => gpui::GridTemplateMinSize::MinContent,
2363        TrackBreadth::MaxContent => gpui::GridTemplateMinSize::MaxContent,
2364        _ => return None,
2365    };
2366    Some(gpui::GridTemplate {
2367        repeat: count as u16,
2368        min_size,
2369    })
2370}
2371
2372/// `None` is a breadth gpui cannot express; the caller drops the whole list, since a
2373/// half-understood track list lays out worse than none.
2374fn track_breadth(b: &lightningcss::properties::grid::TrackBreadth) -> Option<gpui::GridTrackSize> {
2375    use gpui::GridTrackSize as G;
2376    use lightningcss::properties::grid::TrackBreadth as B;
2377    Some(match b {
2378        B::Auto => G::Auto,
2379        B::MinContent => G::MinContent,
2380        B::MaxContent => G::MaxContent,
2381        B::Flex(f) => G::Fr(*f),
2382        B::Length(DimensionPercentage::Dimension(l)) => G::Px(length_value_px(l)?),
2383        B::Length(DimensionPercentage::Percentage(p)) => G::Percent(p.0),
2384        B::Length(DimensionPercentage::Calc(c)) => G::Px(lp_calc_px(c)?),
2385    })
2386}
2387
2388fn track_size(s: &lightningcss::properties::grid::TrackSize) -> Option<gpui::GridTrack> {
2389    use lightningcss::properties::grid::{TrackBreadth as B, TrackSize as S};
2390    match s {
2391        S::TrackBreadth(B::Flex(f)) => Some(gpui::GridTrack::fr(*f)),
2392        S::TrackBreadth(b) => Some(gpui::GridTrack::fixed(track_breadth(b)?)),
2393        S::MinMax { min, max } => Some(gpui::GridTrack {
2394            min: track_breadth(min)?,
2395            max: track_breadth(max)?,
2396        }),
2397        // Approximating with `auto` would silently change the layout, so the list is refused.
2398        S::FitContent(_) => None,
2399    }
2400}
2401
2402/// Written with every list: a refinement cannot unset a field, so an earlier rule's auto-repeat
2403/// would otherwise outlive a later plain list.
2404const NO_AUTO_REPEAT: gpui::GridAutoRepeat = gpui::GridAutoRepeat {
2405    fit: false,
2406    start: 0,
2407    len: 0,
2408};
2409
2410fn grid_tracks(
2411    v: &lightningcss::properties::grid::TrackSizing,
2412) -> Option<(Vec<gpui::GridTrack>, gpui::GridAutoRepeat)> {
2413    use lightningcss::properties::grid::{RepeatCount, TrackListItem, TrackSizing};
2414    let TrackSizing::TrackList(list) = v else {
2415        return None;
2416    };
2417    let mut out: Vec<gpui::GridTrack> = Vec::new();
2418    let mut auto: Option<gpui::GridAutoRepeat> = None;
2419    for item in &list.items {
2420        match item {
2421            TrackListItem::TrackSize(s) => out.push(track_size(s)?),
2422            TrackListItem::TrackRepeat(rep) => {
2423                let one: Vec<gpui::GridTrack> = rep
2424                    .track_sizes
2425                    .iter()
2426                    .map(track_size)
2427                    .collect::<Option<_>>()?;
2428                let fit = match rep.count {
2429                    RepeatCount::Number(count) => {
2430                        if count < 0 || count > 1024 {
2431                            return None;
2432                        }
2433                        for _ in 0..count {
2434                            out.extend(one.iter().copied());
2435                        }
2436                        continue;
2437                    }
2438                    RepeatCount::AutoFill => false,
2439                    RepeatCount::AutoFit => true,
2440                };
2441                if auto.is_some() || one.is_empty() || out.len() + one.len() > u16::MAX as usize {
2442                    return None;
2443                }
2444                auto = Some(gpui::GridAutoRepeat {
2445                    fit,
2446                    start: out.len() as u16,
2447                    len: one.len() as u16,
2448                });
2449                out.extend(one);
2450            }
2451        }
2452    }
2453    if out.is_empty() {
2454        return None;
2455    }
2456    if auto.is_some() && !out.iter().all(fixed_track) {
2457        return None;
2458    }
2459    Some((out, auto.unwrap_or(NO_AUTO_REPEAT)))
2460}
2461
2462fn fixed_track(t: &gpui::GridTrack) -> bool {
2463    use gpui::GridTrackSize as G;
2464    let fixed = |s: G| matches!(s, G::Px(_) | G::Percent(_));
2465    fixed(t.min) || (fixed(t.max) && !matches!(t.min, G::Fr(_)))
2466}
2467
2468/// `None` = a NAMED line or area, which needs the named grid taffy does not model here.
2469fn grid_line(l: &lightningcss::properties::grid::GridLine<'_>) -> Option<gpui::GridPlacement> {
2470    use lightningcss::properties::grid::GridLine as L;
2471    match l {
2472        L::Auto => Some(gpui::GridPlacement::Auto),
2473        L::Line { index, name: None } => Some(gpui::GridPlacement::Line(*index as i16)),
2474        L::Span { index, name: None } if *index > 0 => {
2475            Some(gpui::GridPlacement::Span(*index as u16))
2476        }
2477        _ => None,
2478    }
2479}
2480
2481fn outline_mut(r: &mut StyleRefinement) -> &mut gpui::Outline {
2482    r.vn_outline.get_or_insert(gpui::Outline {
2483        width: px(0.0),
2484        offset: px(0.0),
2485        color: Hsla::default(),
2486        style: gpui::BorderStyle::Solid,
2487    })
2488}
2489
2490#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2491pub enum ListMarker {
2492    None,
2493    Disc,
2494    Circle,
2495    Square,
2496    Decimal,
2497    DecimalLeadingZero,
2498    LowerAlpha,
2499    UpperAlpha,
2500    LowerRoman,
2501    UpperRoman,
2502}
2503
2504impl ListMarker {
2505    pub fn render(self, n: usize) -> Option<String> {
2506        fn alpha(mut n: usize, upper: bool) -> String {
2507            let base = if upper { b'A' } else { b'a' };
2508            let mut out = Vec::new();
2509            while n > 0 {
2510                n -= 1;
2511                out.push(base + (n % 26) as u8);
2512                n /= 26;
2513            }
2514            out.reverse();
2515            String::from_utf8(out).unwrap_or_default()
2516        }
2517        fn roman(mut n: usize, upper: bool) -> String {
2518            const TABLE: [(usize, &str); 13] = [
2519                (1000, "m"),
2520                (900, "cm"),
2521                (500, "d"),
2522                (400, "cd"),
2523                (100, "c"),
2524                (90, "xc"),
2525                (50, "l"),
2526                (40, "xl"),
2527                (10, "x"),
2528                (9, "ix"),
2529                (5, "v"),
2530                (4, "iv"),
2531                (1, "i"),
2532            ];
2533            let mut out = String::new();
2534            for (value, glyph) in TABLE {
2535                while n >= value {
2536                    out.push_str(glyph);
2537                    n -= value;
2538                }
2539            }
2540            if upper {
2541                out.to_uppercase()
2542            } else {
2543                out
2544            }
2545        }
2546        match self {
2547            ListMarker::None => None,
2548            ListMarker::Disc => Some("\u{2022}".into()),
2549            ListMarker::Circle => Some("\u{25e6}".into()),
2550            ListMarker::Square => Some("\u{25aa}".into()),
2551            ListMarker::Decimal => Some(format!("{n}.")),
2552            ListMarker::DecimalLeadingZero => Some(format!("{n:02}.")),
2553            ListMarker::LowerAlpha => Some(format!("{}.", alpha(n, false))),
2554            ListMarker::UpperAlpha => Some(format!("{}.", alpha(n, true))),
2555            ListMarker::LowerRoman => Some(format!("{}.", roman(n, false))),
2556            ListMarker::UpperRoman => Some(format!("{}.", roman(n, true))),
2557        }
2558    }
2559}
2560
2561fn list_marker(style: &lightningcss::properties::list::ListStyleType<'_>) -> Option<ListMarker> {
2562    use lightningcss::properties::list::{
2563        CounterStyle as C, ListStyleType as T, PredefinedCounterStyle as P,
2564    };
2565    match style {
2566        T::None => Some(ListMarker::None),
2567        T::CounterStyle(C::Predefined(p)) => Some(match p {
2568            P::Disc => ListMarker::Disc,
2569            P::Circle => ListMarker::Circle,
2570            P::Square => ListMarker::Square,
2571            P::Decimal => ListMarker::Decimal,
2572            P::DecimalLeadingZero => ListMarker::DecimalLeadingZero,
2573            P::LowerAlpha | P::LowerLatin => ListMarker::LowerAlpha,
2574            P::UpperAlpha | P::UpperLatin => ListMarker::UpperAlpha,
2575            P::LowerRoman => ListMarker::LowerRoman,
2576            P::UpperRoman => ListMarker::UpperRoman,
2577            _ => return None,
2578        }),
2579        _ => None,
2580    }
2581}
2582
2583#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2584pub struct CurrentColorTargets(pub u16);
2585
2586impl CurrentColorTargets {
2587    pub const BORDER: u16 = 1 << 0;
2588    pub const OUTLINE: u16 = 1 << 1;
2589    pub const BACKGROUND: u16 = 1 << 2;
2590    pub const FILL: u16 = 1 << 3;
2591    pub const STROKE: u16 = 1 << 4;
2592    pub const DECORATION: u16 = 1 << 5;
2593    pub const BORDER_TOP: u16 = 1 << 6;
2594    pub const BORDER_RIGHT: u16 = 1 << 7;
2595    pub const BORDER_BOTTOM: u16 = 1 << 8;
2596    pub const BORDER_LEFT: u16 = 1 << 9;
2597
2598    pub fn has(self, bit: u16) -> bool {
2599        self.0 & bit != 0
2600    }
2601}
2602
2603/// CSS matches a background geometry list to the image list by index and repeats the shorter one.
2604fn cycled<T: Copy>(list: Option<&Rc<Vec<T>>>, i: usize) -> Option<T> {
2605    let list = list.filter(|l| !l.is_empty())?;
2606    Some(list[i % list.len()])
2607}
2608
2609/// The size, position and repeat lists of a `background` or a `mask`, cycled over its layers.
2610struct Tiles<'a> {
2611    size: Option<&'a Rc<Vec<BackgroundSize>>>,
2612    position: Option<&'a Rc<Vec<(TileLength, TileLength)>>>,
2613    repeat: Option<&'a Rc<Vec<(bool, bool)>>>,
2614}
2615
2616impl Tiles<'_> {
2617    /// A layer with no explicit two-axis size is not tiled: a gradient has no intrinsic size, so
2618    /// `auto`, `cover` and `contain` all resolve to the box itself.
2619    fn gradient(&self, layer: &BackgroundLayer) -> gpui::Background {
2620        let index = layer.index as usize;
2621        let mut background = layer.background;
2622        if let Some(BackgroundSize::Explicit(Some(w), Some(h))) = cycled(self.size, index) {
2623            let position = cycled(self.position, index)
2624                .unwrap_or((TileLength::Fraction(0.0), TileLength::Fraction(0.0)));
2625            let repeat = cycled(self.repeat, index).unwrap_or((true, true));
2626            background = background.tiled(
2627                (w.value(), h.value()),
2628                (w.is_fraction(), h.is_fraction()),
2629                (position.0.value(), position.1.value()),
2630                (position.0.is_fraction(), position.1.is_fraction()),
2631                repeat,
2632            );
2633        }
2634        background
2635    }
2636
2637    /// Every layer, bottom first.
2638    fn stack(
2639        &self,
2640        images: Option<&Vec<BackgroundLayer>>,
2641        urls: Option<&Vec<BackgroundUrl>>,
2642    ) -> Vec<PaintLayer> {
2643        let mut stack: Vec<(u16, PaintLayer)> = Vec::new();
2644        for layer in images.into_iter().flatten() {
2645            stack.push((layer.index, PaintLayer::Gradient(self.gradient(layer))));
2646        }
2647        for u in urls.into_iter().flatten() {
2648            let i = u.index as usize;
2649            stack.push((
2650                u.index,
2651                PaintLayer::Image {
2652                    url: u.url.clone(),
2653                    size: cycled(self.size, i).unwrap_or(BackgroundSize::Explicit(None, None)),
2654                    position: cycled(self.position, i)
2655                        .unwrap_or((TileLength::Fraction(0.0), TileLength::Fraction(0.0))),
2656                    repeat: cycled(self.repeat, i).unwrap_or((true, true)),
2657                },
2658            ));
2659        }
2660        stack.sort_by_key(|(index, _)| *index);
2661        stack.into_iter().rev().map(|(_, layer)| layer).collect()
2662    }
2663}
2664
2665#[derive(Clone, Debug, PartialEq)]
2666pub struct BackgroundUrl {
2667    pub index: u16,
2668    pub url: Rc<str>,
2669}
2670
2671#[derive(Clone, Copy, Debug, PartialEq)]
2672pub enum BackgroundSize {
2673    Explicit(Option<TileLength>, Option<TileLength>),
2674    Cover,
2675    Contain,
2676}
2677
2678#[derive(Clone, Debug, PartialEq)]
2679pub enum PaintLayer {
2680    Gradient(gpui::Background),
2681    Image {
2682        url: Rc<str>,
2683        size: BackgroundSize,
2684        position: (TileLength, TileLength),
2685        repeat: (bool, bool),
2686    },
2687}
2688
2689#[derive(Clone, Copy, Debug, PartialEq)]
2690pub struct BackgroundLayer {
2691    pub index: u16,
2692    pub background: gpui::Background,
2693}
2694
2695#[derive(Clone, Copy, Debug, PartialEq)]
2696pub enum TileLength {
2697    Pixels(f32),
2698    Fraction(f32),
2699}
2700
2701impl TileLength {
2702    pub fn value(self) -> f32 {
2703        match self {
2704            TileLength::Pixels(v) | TileLength::Fraction(v) => v,
2705        }
2706    }
2707
2708    pub fn is_fraction(self) -> bool {
2709        matches!(self, TileLength::Fraction(_))
2710    }
2711
2712    fn from_length_percentage(v: &LengthPercentage) -> Option<Self> {
2713        match v {
2714            DimensionPercentage::Percentage(p) => Some(TileLength::Fraction(p.0)),
2715            DimensionPercentage::Dimension(d) => length_value_px(d).map(TileLength::Pixels),
2716            DimensionPercentage::Calc(c) => lp_calc_px(c).map(TileLength::Pixels),
2717        }
2718    }
2719}
2720
2721#[derive(Clone, Copy, Debug)]
2722struct Stop {
2723    color: Hsla,
2724    position: Option<StopPosition>,
2725}
2726
2727#[derive(Clone, Copy, Debug, PartialEq)]
2728enum StopPosition {
2729    Fraction(f32),
2730    Pixels(f32),
2731    /// `calc(fraction + pixels)`, e.g. `calc(100% - 20px)`.
2732    Calc(f32, f32),
2733}
2734
2735impl StopPosition {
2736    fn of(fraction: f32, pixels: f32) -> Self {
2737        match (fraction, pixels) {
2738            (f, p) if p == 0.0 => StopPosition::Fraction(f),
2739            (f, p) if f == 0.0 => StopPosition::Pixels(p),
2740            (f, p) => StopPosition::Calc(f, p),
2741        }
2742    }
2743
2744    fn parts(self) -> (f32, f32) {
2745        match self {
2746            StopPosition::Fraction(f) => (f, 0.0),
2747            StopPosition::Pixels(p) => (0.0, p),
2748            StopPosition::Calc(f, p) => (f, p),
2749        }
2750    }
2751}
2752
2753fn resolve_stop_positions(stops: &mut [Stop]) {
2754    let n = stops.len();
2755    if n == 0 {
2756        return;
2757    }
2758    if stops[0].position.is_none() {
2759        stops[0].position = Some(StopPosition::Fraction(0.0));
2760    }
2761    if stops[n - 1].position.is_none() {
2762        stops[n - 1].position = Some(StopPosition::Fraction(1.0));
2763    }
2764
2765    let mut anchor = 0;
2766    for i in 1..n {
2767        if stops[i].position.is_none() {
2768            continue;
2769        }
2770        if i > anchor + 1 {
2771            let gap = (i - anchor) as f32;
2772            let ends = match (stops[anchor].position, stops[i].position) {
2773                (Some(StopPosition::Fraction(_)), Some(StopPosition::Pixels(_)))
2774                | (Some(StopPosition::Pixels(_)), Some(StopPosition::Fraction(_))) => None,
2775                (Some(a), Some(b)) => Some((a.parts(), b.parts())),
2776                _ => None,
2777            };
2778            for (step, slot) in (anchor + 1..i).enumerate() {
2779                let t = (step + 1) as f32 / gap;
2780                stops[slot].position = Some(match ends {
2781                    Some(((af, ap), (bf, bp))) => {
2782                        StopPosition::of(af + (bf - af) * t, ap + (bp - ap) * t)
2783                    }
2784                    None => StopPosition::Fraction(slot as f32 / (n - 1).max(1) as f32),
2785                });
2786            }
2787        }
2788        anchor = i;
2789    }
2790
2791    // Non-decreasing, per unit: comparing a fraction against a length would be comparing two
2792    // different quantities, so a change of unit resets the floor.
2793    let mut floor: Option<StopPosition> = None;
2794    for stop in stops.iter_mut() {
2795        match (&mut stop.position, floor) {
2796            (Some(StopPosition::Fraction(p)), Some(StopPosition::Fraction(f))) => *p = p.max(f),
2797            (Some(StopPosition::Pixels(p)), Some(StopPosition::Pixels(f))) => *p = p.max(f),
2798            _ => {}
2799        }
2800        floor = stop.position;
2801    }
2802}
2803
2804fn hint_stop(before: Hsla, after: Hsla, position: StopPosition) -> Stop {
2805    Stop {
2806        color: mix_hsla(before, after),
2807        position: Some(position),
2808    }
2809}
2810
2811/// The midpoint of two colours, hue averaged the short way round so amber→yellow→amber does not
2812/// come back cyan.
2813fn mix_hsla(a: Hsla, b: Hsla) -> Hsla {
2814    let mut hue_delta = b.h - a.h;
2815    if hue_delta > 0.5 {
2816        hue_delta -= 1.0;
2817    } else if hue_delta < -0.5 {
2818        hue_delta += 1.0;
2819    }
2820    Hsla {
2821        h: (a.h + hue_delta * 0.5).rem_euclid(1.0),
2822        s: (a.s + b.s) * 0.5,
2823        l: (a.l + b.l) * 0.5,
2824        a: (a.a + b.a) * 0.5,
2825    }
2826}
2827
2828fn stop_position_lp(v: &LengthPercentage) -> Option<StopPosition> {
2829    match v {
2830        DimensionPercentage::Percentage(p) => Some(StopPosition::Fraction(p.0)),
2831        DimensionPercentage::Dimension(d) => length_value_px(d).map(StopPosition::Pixels),
2832        DimensionPercentage::Calc(c) => match calc_linear(c) {
2833            Some((fraction, pixels)) if fraction.is_finite() && pixels.is_finite() => {
2834                Some(StopPosition::of(fraction, pixels))
2835            }
2836            _ => {
2837                calc_dropped();
2838                None
2839            }
2840        },
2841    }
2842}
2843
2844fn stop_position_angle(
2845    v: &DimensionPercentage<lightningcss::values::angle::Angle>,
2846) -> Option<StopPosition> {
2847    match v {
2848        DimensionPercentage::Percentage(p) => Some(StopPosition::Fraction(p.0)),
2849        DimensionPercentage::Dimension(a) => Some(StopPosition::Fraction(a.to_degrees() / 360.0)),
2850        DimensionPercentage::Calc(_) => {
2851            calc_dropped();
2852            None
2853        }
2854    }
2855}
2856
2857fn collect_stops<P: Clone>(
2858    items: &[lightningcss::values::gradient::GradientItem<P>],
2859    position_of: &dyn Fn(&P) -> Option<StopPosition>,
2860) -> Option<Vec<Stop>> {
2861    use lightningcss::values::gradient::GradientItem;
2862
2863    let mut stops: Vec<Stop> = Vec::with_capacity(items.len());
2864    let mut pending_hints: Vec<StopPosition> = Vec::new();
2865    for item in items {
2866        match item {
2867            GradientItem::ColorStop(s) => {
2868                let color = color(&s.color)?;
2869                for hint in pending_hints.drain(..) {
2870                    if let Some(before) = stops.last().map(|s: &Stop| s.color) {
2871                        stops.push(hint_stop(before, color, hint));
2872                    }
2873                }
2874                stops.push(Stop {
2875                    color,
2876                    position: s.position.as_ref().and_then(|p| position_of(p)),
2877                });
2878            }
2879            GradientItem::Hint(h) => {
2880                if let Some(p) = position_of(h) {
2881                    pending_hints.push(p);
2882                }
2883            }
2884        }
2885    }
2886    if stops.is_empty() {
2887        return None;
2888    }
2889    resolve_stop_positions(&mut stops);
2890    Some(stops)
2891}
2892
2893fn gradient_center(position: &lightningcss::values::position::Position) -> ((f32, f32), bool) {
2894    use lightningcss::values::position::{
2895        HorizontalPositionKeyword as H, PositionComponent as P, VerticalPositionKeyword as V,
2896    };
2897
2898    fn component<S: Copy>(c: &P<S>, from_start: impl Fn(S) -> bool) -> (f32, bool) {
2899        let absolute = |v: &LengthPercentage| match v {
2900            DimensionPercentage::Dimension(d) => length_value_px(d),
2901            DimensionPercentage::Calc(c) => lp_calc_px(c),
2902            DimensionPercentage::Percentage(_) => None,
2903        };
2904        match c {
2905            P::Center => (0.5, false),
2906            P::Length(DimensionPercentage::Percentage(p)) => (p.0, false),
2907            P::Length(v) => absolute(v).map(|px| (px, true)).unwrap_or((0.5, false)),
2908            P::Side { side, offset } => {
2909                let near = from_start(*side);
2910                match offset {
2911                    None => (if near { 0.0 } else { 1.0 }, false),
2912                    Some(DimensionPercentage::Percentage(p)) => {
2913                        (if near { p.0 } else { 1.0 - p.0 }, false)
2914                    }
2915                    // A length measured from the FAR side would need the box. `right 10px` is not a
2916                    // shape stylesheets write; the near side is, and it is exact.
2917                    Some(v) => match absolute(v) {
2918                        Some(px) if near => (px, true),
2919                        _ => (if near { 0.0 } else { 1.0 }, false),
2920                    },
2921                }
2922            }
2923        }
2924    }
2925
2926    let (x, x_px) = component(&position.x, |s| matches!(s, H::Left));
2927    let (y, y_px) = component(&position.y, |s| matches!(s, V::Top));
2928    match (x_px, y_px) {
2929        (true, true) => ((x, y), true),
2930        (true, false) => ((0.0, y), false),
2931        (false, true) => ((x, 0.0), false),
2932        (false, false) => ((x, y), false),
2933    }
2934}
2935
2936fn with_resolved_stops(background: gpui::Background, stops: &[Stop]) -> gpui::Background {
2937    let packed: Vec<gpui::LinearColorStop> = stops
2938        .iter()
2939        .map(|s| {
2940            let value = match s.position {
2941                Some(StopPosition::Pixels(v)) | Some(StopPosition::Fraction(v)) => v,
2942                Some(StopPosition::Calc(..)) | None => 0.0,
2943            };
2944            gpui::linear_color_stop(s.color, value)
2945        })
2946        .collect();
2947    let mut background = background.with_stops(&packed);
2948    for (i, stop) in stops.iter().enumerate().take(gpui::GRADIENT_STOPS) {
2949        match stop.position {
2950            Some(StopPosition::Pixels(_)) => background = background.stop_in_pixels(i),
2951            Some(StopPosition::Calc(f, p)) => background = background.stop_at_calc(i, f, p),
2952            _ => {}
2953        }
2954    }
2955    background
2956}
2957
2958/// Splits a long stop list into bands, each with transparent hard-stop guards at shared edges: each
2959/// pixel is opaque in one band only, so there is no seam or double blend.
2960fn band_stops(stops: &[Stop]) -> Vec<Vec<Stop>> {
2961    const REAL_PER_BAND: usize = gpui::GRADIENT_STOPS - 2;
2962    if stops.len() <= gpui::GRADIENT_STOPS {
2963        return vec![stops.to_vec()];
2964    }
2965    let transparent = |at: Option<StopPosition>| Stop {
2966        color: Hsla {
2967            h: 0.0,
2968            s: 0.0,
2969            l: 0.0,
2970            a: 0.0,
2971        },
2972        position: at,
2973    };
2974    let mut bands = Vec::new();
2975    let mut start = 0;
2976    while start + 1 < stops.len() {
2977        let end = (start + REAL_PER_BAND - 1).min(stops.len() - 1);
2978        let mut band: Vec<Stop> = Vec::with_capacity(gpui::GRADIENT_STOPS);
2979        if start > 0 {
2980            band.push(transparent(stops[start].position));
2981        }
2982        band.extend_from_slice(&stops[start..=end]);
2983        if end + 1 < stops.len() {
2984            band.push(transparent(stops[end].position));
2985        }
2986        bands.push(band);
2987        start = end;
2988    }
2989    bands
2990}
2991
2992fn mask_images<'a>(
2993    images: impl Iterator<Item = &'a lightningcss::values::image::Image<'a>>,
2994) -> MaskImages {
2995    use lightningcss::values::image::Image;
2996    let images: Vec<_> = images.collect();
2997    if images.iter().all(|i| matches!(i, Image::None)) {
2998        MaskImages::None
2999    } else if images.len() == 2 && images.iter().all(|i| opaque_mask_layer(i)) {
3000        MaskImages::TwoOpaque
3001    } else {
3002        MaskImages::Other
3003    }
3004}
3005
3006fn opaque_mask_layer(image: &lightningcss::values::image::Image<'_>) -> bool {
3007    use lightningcss::values::gradient::{Gradient, GradientItem};
3008    use lightningcss::values::image::Image;
3009    fn opaque<D>(items: &[GradientItem<D>]) -> bool {
3010        items.iter().all(|item| match item {
3011            GradientItem::ColorStop(stop) => color(&stop.color).is_some_and(|c| c.a >= 1.0),
3012            GradientItem::Hint(_) => true,
3013        })
3014    }
3015    let Image::Gradient(gradient) = image else {
3016        return false;
3017    };
3018    match gradient.as_ref() {
3019        Gradient::Linear(g) | Gradient::RepeatingLinear(g) => opaque(&g.items),
3020        Gradient::Radial(g) | Gradient::RepeatingRadial(g) => opaque(&g.items),
3021        Gradient::Conic(g) | Gradient::RepeatingConic(g) => opaque(&g.items),
3022        Gradient::WebKitGradient(_) => false,
3023    }
3024}
3025
3026fn mask_clips<'a>(
3027    clips: impl Iterator<Item = &'a lightningcss::properties::masking::MaskClip>,
3028) -> MaskClips {
3029    use lightningcss::properties::masking::{GeometryBox as B, MaskClip as C};
3030    let clips: Vec<_> = clips.collect();
3031    match clips.as_slice() {
3032        [C::GeometryBox(B::ContentBox), C::GeometryBox(B::BorderBox)] => {
3033            MaskClips::ContentThenBorder
3034        }
3035        _ => MaskClips::Other,
3036    }
3037}
3038
3039fn mask_compositing(c: lightningcss::properties::masking::MaskComposite) -> MaskCompositing {
3040    use lightningcss::properties::masking::MaskComposite as C;
3041    match c {
3042        C::Add => MaskCompositing::Add,
3043        C::Exclude => MaskCompositing::Exclude,
3044        C::Subtract | C::Intersect => MaskCompositing::Other,
3045    }
3046}
3047
3048fn webkit_mask_compositing(keyword: &str) -> MaskCompositing {
3049    match keyword.to_ascii_lowercase().as_str() {
3050        "source-over" => MaskCompositing::Add,
3051        "xor" | "destination-out" => MaskCompositing::Exclude,
3052        _ => MaskCompositing::Other,
3053    }
3054}
3055
3056fn advise_mask(x: &Extras, diagnostics: &mut Vec<String>) {
3057    let excluded = x.mask_composite == Some(MaskCompositing::Exclude)
3058        && x.mask_images
3059            .is_some_and(|images| images != MaskImages::TwoOpaque);
3060    if x.mask_composite == Some(MaskCompositing::Other) || excluded {
3061        warn_once(
3062            diagnostics,
3063            "`mask-composite` other than `add` is not applied (v1): the mask layers are added. \
3064             The one exception is the gradient-border ring (two opaque layers, the top one \
3065             clipped to `content-box`, composited with `exclude`). Combine the layers into one \
3066             image instead",
3067        );
3068    }
3069}
3070
3071/// `-webkit-` mask properties are not read; `true` when `prefix` names only them. The ring
3072/// (two opaque layers) is let through.
3073fn webkit_mask(
3074    prefix: lightningcss::vendor_prefix::VendorPrefix,
3075    property: &str,
3076    ring: bool,
3077    diagnostics: &mut Vec<String>,
3078) -> bool {
3079    use lightningcss::vendor_prefix::VendorPrefix;
3080    if prefix.contains(VendorPrefix::None) || prefix.is_empty() {
3081        return false;
3082    }
3083    if !ring {
3084        warn_once(
3085            diagnostics,
3086            &format!(
3087                "`-webkit-{property}` is not supported and is ignored — use `{property}`, which \
3088                 takes the same values"
3089            ),
3090        );
3091    }
3092    true
3093}
3094
3095fn collect_mask_images<'a>(
3096    images: impl Iterator<Item = &'a lightningcss::values::image::Image<'a>>,
3097    x: &mut Extras,
3098    diagnostics: &mut Vec<String>,
3099) {
3100    let mut layers: Vec<BackgroundLayer> = Vec::new();
3101    let mut urls: Vec<BackgroundUrl> = Vec::new();
3102    for (index, image) in images.enumerate() {
3103        let index = index.min(u16::MAX as usize) as u16;
3104        if let lightningcss::values::image::Image::Url(u) = image {
3105            let url = u.url.trim();
3106            if url.starts_with('#') {
3107                warn_once(
3108                    diagnostics,
3109                    "`mask-image: url(#…)` names an SVG `<mask>` element, which is not supported \
3110                     (v1); the layer is left out. Point the URL at an image file, or write the \
3111                     mask as a gradient",
3112                );
3113            } else if !url.is_empty() {
3114                urls.push(BackgroundUrl {
3115                    index,
3116                    url: Rc::from(url),
3117                });
3118            }
3119            continue;
3120        }
3121        if let Some((backgrounds, _)) = gradient_layer(image, diagnostics) {
3122            layers.extend(
3123                backgrounds
3124                    .into_iter()
3125                    .map(|background| BackgroundLayer { index, background }),
3126            );
3127        }
3128    }
3129    x.mask.images = Some(Rc::new(layers));
3130    x.mask.urls = Some(Rc::new(urls));
3131}
3132
3133fn mask_luminance<'a>(
3134    modes: impl Iterator<Item = &'a lightningcss::properties::masking::MaskMode>,
3135    diagnostics: &mut Vec<String>,
3136) -> bool {
3137    use lightningcss::properties::masking::MaskMode as M;
3138    let modes: Vec<bool> = modes.map(|m| *m == M::Luminance).collect();
3139    let luminance = modes.first().copied().unwrap_or(false);
3140    if modes.iter().any(|&m| m != luminance) {
3141        warn_once(
3142            diagnostics,
3143            "`mask-mode` differs between mask layers, which is not supported (v1): the first \
3144             layer's mode applies to all of them. Give every layer the same mode",
3145        );
3146    }
3147    luminance
3148}
3149
3150fn advise_mask_clip<'a>(
3151    clips: impl Iterator<Item = &'a lightningcss::properties::masking::MaskClip>,
3152    diagnostics: &mut Vec<String>,
3153) {
3154    use lightningcss::properties::masking::{GeometryBox as B, MaskClip as C};
3155    if clips
3156        .into_iter()
3157        .any(|c| *c != C::GeometryBox(B::BorderBox))
3158    {
3159        warn_once(
3160            diagnostics,
3161            "`mask-clip` other than `border-box` is not applied (v1): the mask is clipped at the \
3162             border box. Size and position the mask layers to fit instead",
3163        );
3164    }
3165}
3166
3167fn mask_position(
3168    position: &lightningcss::values::position::Position,
3169    diagnostics: &mut Vec<String>,
3170) -> (TileLength, TileLength) {
3171    (
3172        position_component(&position.x, true, diagnostics),
3173        position_component(&position.y, false, diagnostics),
3174    )
3175}
3176
3177fn advise_mask_box<'a>(
3178    boxes: impl Iterator<Item = &'a lightningcss::properties::masking::GeometryBox>,
3179    property: &str,
3180    diagnostics: &mut Vec<String>,
3181) {
3182    use lightningcss::properties::masking::GeometryBox as B;
3183    if boxes.into_iter().any(|b| *b != B::BorderBox) {
3184        warn_once(
3185            diagnostics,
3186            &format!(
3187                "`{property}` other than `border-box` is not applied (v1): the mask is laid out \
3188                 and clipped at the border box. Size and position the mask layers to fit instead"
3189            ),
3190        );
3191    }
3192}
3193
3194fn collect_background_images<'a>(
3195    images: impl Iterator<Item = &'a lightningcss::values::image::Image<'a>>,
3196    x: &mut Extras,
3197    diagnostics: &mut Vec<String>,
3198) {
3199    let mut layers: Vec<BackgroundLayer> = Vec::new();
3200    let mut urls: Vec<BackgroundUrl> = Vec::new();
3201    for (index, image) in images.enumerate() {
3202        if let lightningcss::values::image::Image::Url(u) = image {
3203            if !u.url.trim().is_empty() {
3204                urls.push(BackgroundUrl {
3205                    index: index.min(u16::MAX as usize) as u16,
3206                    url: Rc::from(u.url.as_ref()),
3207                });
3208            }
3209            continue;
3210        }
3211        let Some((backgrounds, key)) = gradient_layer(image, diagnostics) else {
3212            continue;
3213        };
3214        if x.background_key_color.is_none() || index == 0 {
3215            x.background_key_color = Some(key);
3216        }
3217        for background in backgrounds {
3218            layers.push(BackgroundLayer {
3219                index: index.min(u16::MAX as usize) as u16,
3220                background,
3221            });
3222        }
3223    }
3224    x.background_images = Some(Rc::new(layers));
3225    x.background_urls = Some(Rc::new(urls));
3226}
3227
3228fn background_size(size: &lightningcss::properties::background::BackgroundSize) -> BackgroundSize {
3229    use lightningcss::properties::background::BackgroundSize as BS;
3230    match size {
3231        BS::Cover => BackgroundSize::Cover,
3232        BS::Contain => BackgroundSize::Contain,
3233        BS::Explicit { width, height } => {
3234            let axis = |v: &LengthPercentageOrAuto| match v {
3235                LengthPercentageOrAuto::Auto => None,
3236                LengthPercentageOrAuto::LengthPercentage(lp) => {
3237                    TileLength::from_length_percentage(lp)
3238                }
3239            };
3240            BackgroundSize::Explicit(axis(width), axis(height))
3241        }
3242    }
3243}
3244
3245fn background_repeat(
3246    repeat: &lightningcss::properties::background::BackgroundRepeat,
3247) -> (bool, bool) {
3248    use lightningcss::properties::background::BackgroundRepeatKeyword as K;
3249    // Both still repeat, and both differ from `repeat` only by a sub-tile amount; treating them as
3250    // `repeat` is the closer of the two available answers.
3251    let on = |k: &K| !matches!(k, K::NoRepeat);
3252    (on(&repeat.x), on(&repeat.y))
3253}
3254
3255fn background_position(
3256    position: &lightningcss::properties::background::BackgroundPosition,
3257    diagnostics: &mut Vec<String>,
3258) -> (TileLength, TileLength) {
3259    (
3260        position_component(&position.x, true, diagnostics),
3261        position_component(&position.y, false, diagnostics),
3262    )
3263}
3264
3265fn position_component<S: Copy>(
3266    component: &lightningcss::values::position::PositionComponent<S>,
3267    horizontal: bool,
3268    diagnostics: &mut Vec<String>,
3269) -> TileLength
3270where
3271    S: PositionSide,
3272{
3273    use lightningcss::values::position::PositionComponent as P;
3274    let absolute = |v: &LengthPercentage| match v {
3275        DimensionPercentage::Dimension(d) => length_value_px(d),
3276        DimensionPercentage::Calc(c) => lp_calc_px(c),
3277        DimensionPercentage::Percentage(_) => None,
3278    };
3279    match component {
3280        P::Center => TileLength::Fraction(0.5),
3281        P::Length(DimensionPercentage::Percentage(p)) => TileLength::Fraction(p.0),
3282        P::Length(v) => absolute(v)
3283            .map(TileLength::Pixels)
3284            .unwrap_or(TileLength::Fraction(0.0)),
3285        P::Side { side, offset } => {
3286            let near = side.is_near_edge();
3287            match offset {
3288                None => TileLength::Fraction(if near { 0.0 } else { 1.0 }),
3289                Some(DimensionPercentage::Percentage(p)) => {
3290                    TileLength::Fraction(if near { p.0 } else { 1.0 - p.0 })
3291                }
3292                Some(v) if near => absolute(v)
3293                    .map(TileLength::Pixels)
3294                    .unwrap_or(TileLength::Fraction(0.0)),
3295                Some(_) => {
3296                    warn_once(
3297                        diagnostics,
3298                        &format!(
3299                            "`background-position: {} <length>` is placed flush against that edge \
3300                             (v1) — an offset from the FAR edge is a fraction of the box minus a \
3301                             length, and the tile carries one number per axis. Write it from the \
3302                             near edge (`left`/`top`), or as a percentage, both of which are exact",
3303                            if horizontal { "right" } else { "bottom" }
3304                        ),
3305                    );
3306                    TileLength::Fraction(1.0)
3307                }
3308            }
3309        }
3310    }
3311}
3312
3313pub(crate) trait PositionSide {
3314    fn is_near_edge(self) -> bool;
3315}
3316
3317impl PositionSide for lightningcss::values::position::HorizontalPositionKeyword {
3318    fn is_near_edge(self) -> bool {
3319        matches!(self, Self::Left)
3320    }
3321}
3322
3323impl PositionSide for lightningcss::values::position::VerticalPositionKeyword {
3324    fn is_near_edge(self) -> bool {
3325        matches!(self, Self::Top)
3326    }
3327}
3328
3329fn gradient_layer(
3330    img: &lightningcss::values::image::Image<'_>,
3331    diagnostics: &mut Vec<String>,
3332) -> Option<(Vec<gpui::Background>, Hsla)> {
3333    use lightningcss::values::gradient::{
3334        Circle, Ellipse, EndingShape, Gradient, LineDirection, ShapeExtent,
3335    };
3336    use lightningcss::values::image::Image;
3337    use lightningcss::values::position::{
3338        HorizontalPositionKeyword as H, VerticalPositionKeyword as V,
3339    };
3340
3341    let gradient = match img {
3342        Image::Gradient(g) => g.as_ref(),
3343        Image::Url(_) => return None,
3344        Image::ImageSet(_) => {
3345            warn_once(
3346                diagnostics,
3347                "background-image: image-set() is not painted (v1) — write one source as a plain \
3348                 `url()`, which is; there is no resolution negotiation here",
3349            );
3350            return None;
3351        }
3352        Image::None => return None,
3353    };
3354
3355    let (background, stops) = match gradient {
3356        Gradient::Linear(l) | Gradient::RepeatingLinear(l) => {
3357            let stops = collect_stops(&l.items, &stop_position_lp)?;
3358            let angle = match &l.direction {
3359                LineDirection::Angle(a) => Some(a.to_degrees()),
3360                LineDirection::Vertical(V::Top) => Some(0.0),
3361                LineDirection::Vertical(V::Bottom) => Some(180.0),
3362                LineDirection::Horizontal(H::Right) => Some(90.0),
3363                LineDirection::Horizontal(H::Left) => Some(270.0),
3364                LineDirection::Corner { .. } => None,
3365            };
3366            let background = match angle {
3367                Some(angle) => gpui::linear_gradient_stops(angle, &[]),
3368                None => {
3369                    let LineDirection::Corner {
3370                        horizontal,
3371                        vertical,
3372                    } = &l.direction
3373                    else {
3374                        unreachable!("only a corner direction leaves the angle unresolved")
3375                    };
3376                    gpui::linear_gradient_stops(0.0, &[]).to_corner(match (horizontal, vertical) {
3377                        (H::Right, V::Top) => 0,
3378                        (H::Right, V::Bottom) => 1,
3379                        (H::Left, V::Bottom) => 2,
3380                        (H::Left, V::Top) => 3,
3381                    })
3382                }
3383            };
3384            (background, stops)
3385        }
3386        Gradient::Radial(r) | Gradient::RepeatingRadial(r) => {
3387            let stops = collect_stops(&r.items, &stop_position_lp)?;
3388            let (center, center_px) = gradient_center(&r.position);
3389            let extent = |e: &ShapeExtent| match e {
3390                ShapeExtent::ClosestSide => 1u8,
3391                ShapeExtent::FarthestSide => 2,
3392                ShapeExtent::ClosestCorner => 3,
3393                ShapeExtent::FarthestCorner => 4,
3394            };
3395            let background = gpui::radial_gradient(&[]).at(center, center_px);
3396            let background = match &r.shape {
3397                EndingShape::Circle(Circle::Extent(e)) => background.with_extent(extent(e), false),
3398                EndingShape::Circle(Circle::Radius(len)) => match css_length_px(len) {
3399                    Some(radius) => background.with_radii((radius, radius), true),
3400                    None => background.with_extent(4, false),
3401                },
3402                EndingShape::Ellipse(Ellipse::Extent(e)) => background.with_extent(extent(e), true),
3403                EndingShape::Ellipse(Ellipse::Size { x, y }) => {
3404                    let axis = |v: &LengthPercentage| match v {
3405                        DimensionPercentage::Percentage(p) => Some((p.0, false)),
3406                        DimensionPercentage::Dimension(d) => length_value_px(d).map(|v| (v, true)),
3407                        DimensionPercentage::Calc(c) => lp_calc_px(c).map(|v| (v, true)),
3408                    };
3409                    match (axis(x), axis(y)) {
3410                        // Both axes have to agree on the unit, because one flag covers the pair.
3411                        (Some((rx, true)), Some((ry, true))) => {
3412                            background.with_radii((rx, ry), true)
3413                        }
3414                        (Some((rx, false)), Some((ry, false))) => {
3415                            background.with_radii((rx, ry), false)
3416                        }
3417                        _ => background.with_extent(4, true),
3418                    }
3419                }
3420            };
3421            (background, stops)
3422        }
3423        Gradient::Conic(c) | Gradient::RepeatingConic(c) => {
3424            let stops = collect_stops(&c.items, &stop_position_angle)?;
3425            let (center, center_px) = gradient_center(&c.position);
3426            (
3427                gpui::conic_gradient(c.angle.to_degrees(), &[]).at(center, center_px),
3428                stops,
3429            )
3430        }
3431        Gradient::WebKitGradient(_) => {
3432            warn_once(
3433                diagnostics,
3434                "the legacy `-webkit-gradient()` is not painted (v1) — write the standard \
3435                 `linear-gradient()`, which does",
3436            );
3437            return None;
3438        }
3439    };
3440
3441    let repeating = matches!(
3442        gradient,
3443        Gradient::RepeatingLinear(_) | Gradient::RepeatingRadial(_) | Gradient::RepeatingConic(_)
3444    );
3445    let background = background.repeating(repeating);
3446
3447    let key = if stops.len() == 1 {
3448        stops[0].color
3449    } else {
3450        mix_hsla(stops[0].color, stops[stops.len() - 1].color)
3451    };
3452    let layers = band_stops(&stops)
3453        .into_iter()
3454        .map(|band| with_resolved_stops(background, &band))
3455        .collect();
3456    Some((layers, key))
3457}
3458
3459pub(crate) fn once(diagnostics: &mut Vec<String>, msg: String) {
3460    if !diagnostics.iter().any(|d| *d == msg) {
3461        diagnostics.push(msg);
3462    }
3463}
3464
3465fn unsupported(diagnostics: &mut Vec<String>, what: &str) {
3466    once(diagnostics, format!("unsupported value for {what} (v1)"));
3467}
3468
3469fn warn_once(diagnostics: &mut Vec<String>, msg: &str) {
3470    once(diagnostics, msg.to_string());
3471}
3472
3473pub(crate) fn apply_current_color(
3474    r: &mut StyleRefinement,
3475    targets: CurrentColorTargets,
3476    color: Hsla,
3477) {
3478    let sides = [
3479        r.vn_border_colors.top,
3480        r.vn_border_colors.right,
3481        r.vn_border_colors.bottom,
3482        r.vn_border_colors.left,
3483    ];
3484    if sides.iter().all(|side| *side == Some(None))
3485        || (targets.has(CurrentColorTargets::BORDER)
3486            && r.border_color.is_none()
3487            && sides.iter().all(Option::is_none))
3488    {
3489        r.border_color = Some(color);
3490    }
3491    // A currentColor placeholder belongs to this refinement, not every state that contributed to
3492    // Extras.
3493    for slot in [
3494        &mut r.vn_border_colors.top,
3495        &mut r.vn_border_colors.right,
3496        &mut r.vn_border_colors.bottom,
3497        &mut r.vn_border_colors.left,
3498    ] {
3499        if *slot == Some(None) {
3500            *slot = Some(Some(color));
3501        }
3502    }
3503    if targets.has(CurrentColorTargets::OUTLINE) {
3504        if let Some(outline) = r.vn_outline.as_mut() {
3505            outline.color = color;
3506        }
3507    }
3508    if targets.has(CurrentColorTargets::BACKGROUND) {
3509        r.background = Some(gpui::Fill::Color(color.into()));
3510    }
3511}
3512
3513pub(crate) fn border_needs_current_color(r: &StyleRefinement) -> bool {
3514    [
3515        r.vn_border_colors.top,
3516        r.vn_border_colors.right,
3517        r.vn_border_colors.bottom,
3518        r.vn_border_colors.left,
3519    ]
3520    .contains(&Some(None))
3521}
3522
3523fn border_side_color(
3524    slot: &mut Option<Option<Hsla>>,
3525    bit: u16,
3526    value: &CssColor,
3527    extras: &mut Extras,
3528    diagnostics: &mut Vec<String>,
3529) {
3530    let resolved = match value {
3531        CssColor::CurrentColor => None,
3532        value => match color(value) {
3533            Some(color) => Some(color),
3534            None => {
3535                unresolved_color(diagnostics, "border-color");
3536                return;
3537            }
3538        },
3539    };
3540    *slot = Some(resolved);
3541    extras.current_color_overrides.0 |= bit | CurrentColorTargets::BORDER;
3542    extras.current_color.0 &= !(bit | CurrentColorTargets::BORDER);
3543    if matches!(value, CssColor::CurrentColor) {
3544        extras.current_color.0 |= bit;
3545    }
3546}
3547
3548fn all_border_colors(
3549    r: &mut StyleRefinement,
3550    x: &mut Extras,
3551    colors: [&CssColor; 4],
3552    diagnostics: &mut Vec<String>,
3553) {
3554    border_side_color(
3555        &mut r.vn_border_colors.top,
3556        CurrentColorTargets::BORDER_TOP,
3557        colors[0],
3558        x,
3559        diagnostics,
3560    );
3561    border_side_color(
3562        &mut r.vn_border_colors.right,
3563        CurrentColorTargets::BORDER_RIGHT,
3564        colors[1],
3565        x,
3566        diagnostics,
3567    );
3568    border_side_color(
3569        &mut r.vn_border_colors.bottom,
3570        CurrentColorTargets::BORDER_BOTTOM,
3571        colors[2],
3572        x,
3573        diagnostics,
3574    );
3575    border_side_color(
3576        &mut r.vn_border_colors.left,
3577        CurrentColorTargets::BORDER_LEFT,
3578        colors[3],
3579        x,
3580        diagnostics,
3581    );
3582    r.border_color = color(colors[0]);
3583    if colors
3584        .iter()
3585        .all(|value| matches!(value, CssColor::CurrentColor))
3586    {
3587        x.current_color.0 |= CurrentColorTargets::BORDER;
3588    }
3589}
3590
3591fn unresolved_color(diagnostics: &mut Vec<String>, what: &str) {
3592    once(
3593        diagnostics,
3594        format!(
3595            "`{what}` value does not resolve to a concrete color (v1) — system colors \
3596             (`Canvas`, `ButtonText`, …) are not computed; write the color, or use \
3597             `light-dark()` with `color-scheme` where it must follow the theme"
3598        ),
3599    );
3600}
3601
3602/// The device-pixel blur radius gpui draws at most (`MAX_GLYPH_SHADOW_SIGMA` is half of it).
3603const MAX_TEXT_SHADOW_BLUR_DEVICE_PX: f32 = 2. * gpui::MAX_GLYPH_SHADOW_SIGMA;
3604
3605/// `None` drops the declaration, as a browser drops an invalid one.
3606fn text_shadows(
3607    shadows: &[lightningcss::properties::text::TextShadow],
3608    diagnostics: &mut Vec<String>,
3609) -> Option<Vec<gpui::TextShadow>> {
3610    let mut out = Vec::with_capacity(shadows.len());
3611    for s in shadows {
3612        if css_length_px(&s.spread) != Some(0.0) {
3613            once(
3614                diagnostics,
3615                "`text-shadow` was dropped: it takes no spread distance (a fourth length), and \
3616                 browsers drop the whole declaration for one. Remove the fourth length"
3617                    .into(),
3618            );
3619            return None;
3620        }
3621        let (Some(x), Some(y), Some(blur)) = (
3622            css_length_px(&s.x_offset),
3623            css_length_px(&s.y_offset),
3624            css_length_px(&s.blur),
3625        ) else {
3626            once(
3627                diagnostics,
3628                "`text-shadow` was dropped: an offset or blur radius does not resolve to a length \
3629                 here. Use px, em, rem or a calc() of them"
3630                    .into(),
3631            );
3632            return None;
3633        };
3634        if blur < 0.0 {
3635            once(
3636                diagnostics,
3637                "`text-shadow` was dropped: a blur radius cannot be negative, and browsers drop \
3638                 the declaration. Use 0 for a sharp shadow"
3639                    .into(),
3640            );
3641            return None;
3642        }
3643        if blur > MAX_TEXT_SHADOW_BLUR_DEVICE_PX / 2.0 {
3644            once(
3645                diagnostics,
3646                format!(
3647                    "`text-shadow` blur radius {blur}px is drawn at most {}px wide in device \
3648                     pixels ({}px at 2x); a softer shadow needs `filter: drop-shadow()`",
3649                    MAX_TEXT_SHADOW_BLUR_DEVICE_PX,
3650                    MAX_TEXT_SHADOW_BLUR_DEVICE_PX / 2.0
3651                ),
3652            );
3653        }
3654        let color = match &s.color {
3655            CssColor::CurrentColor => None,
3656            c => match color(c) {
3657                Some(c) => Some(c),
3658                None => {
3659                    unresolved_color(diagnostics, "text-shadow");
3660                    continue;
3661                }
3662            },
3663        };
3664        out.push(gpui::TextShadow {
3665            color,
3666            offset: gpui::point(px(x), px(y)),
3667            blur_radius: px(blur),
3668        });
3669    }
3670    Some(out)
3671}
3672
3673/// A `text-shadow` list as `getComputedStyle` writes it: colour first, every length, `none` when empty.
3674pub fn text_shadow_css(shadows: &[gpui::TextShadow], current_color: Hsla) -> String {
3675    if shadows.is_empty() {
3676        return "none".into();
3677    }
3678    let rgb = |c: Hsla| {
3679        let c = gpui::Rgba::from(c);
3680        let channel = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
3681        let (r, g, b) = (channel(c.r), channel(c.g), channel(c.b));
3682        if c.a >= 1.0 {
3683            format!("rgb({r}, {g}, {b})")
3684        } else {
3685            let a = (c.a.clamp(0.0, 1.0) * 1000.0).round() / 1000.0;
3686            format!("rgba({r}, {g}, {b}, {a})")
3687        }
3688    };
3689    shadows
3690        .iter()
3691        .map(|s| {
3692            format!(
3693                "{} {}px {}px {}px",
3694                rgb(s.color.unwrap_or(current_color)),
3695                f32::from(s.offset.x),
3696                f32::from(s.offset.y),
3697                f32::from(s.blur_radius)
3698            )
3699        })
3700        .collect::<Vec<_>>()
3701        .join(", ")
3702}
3703
3704#[path = "effect.rs"]
3705pub(crate) mod effect;
3706
3707fn object_position(p: &Property, diagnostics: &mut Vec<String>) -> Option<gpui::ObjectPosition> {
3708    use lightningcss::traits::Parse;
3709    use lightningcss::values::position::{Position, PositionComponent as C};
3710    fn axis<S: PositionSide + Copy>(c: &C<S>) -> Option<(f32, f32)> {
3711        let linear = |v: &LengthPercentage| match v {
3712            DimensionPercentage::Dimension(d) => Some((0.0, length_value_px(d)?)),
3713            DimensionPercentage::Percentage(p) => Some((p.0, 0.0)),
3714            DimensionPercentage::Calc(c) => calc_linear(c),
3715        };
3716        match c {
3717            C::Center => Some((0.5, 0.0)),
3718            C::Length(v) => linear(v),
3719            C::Side { side, offset } => {
3720                let (f, px) = offset.as_ref().map_or(Some((0.0, 0.0)), linear)?;
3721                Some(if side.is_near_edge() {
3722                    (f, px)
3723                } else {
3724                    (1.0 - f, -px)
3725                })
3726            }
3727        }
3728    }
3729    let raw = value_text(p)?;
3730    let resolved = Position::parse_string(&raw)
3731        .ok()
3732        .and_then(|pos| Some((axis(&pos.x)?, axis(&pos.y)?)));
3733    let Some(((x_fraction, x_offset), (y_fraction, y_offset))) = resolved else {
3734        once(
3735            diagnostics,
3736            format!(
3737                "unsupported value for object-position: {raw} — expected one to four keywords, \
3738                 lengths or percentages, as in `left 10px top 20%`"
3739            ),
3740        );
3741        return None;
3742    };
3743    Some(gpui::ObjectPosition {
3744        x_fraction,
3745        x_offset: px(x_offset),
3746        y_fraction,
3747        y_offset: px(y_offset),
3748    })
3749}
3750
3751fn object_fit(
3752    value: &lightningcss::properties::custom::TokenList,
3753    diagnostics: &mut Vec<String>,
3754) -> Option<ObjectFit> {
3755    match single_ident(value, "object-fit", diagnostics) {
3756        Some("fill") => Some(ObjectFit::Fill),
3757        Some("contain") => Some(ObjectFit::Contain),
3758        Some("cover") => Some(ObjectFit::Cover),
3759        Some("scale-down") => Some(ObjectFit::ScaleDown),
3760        Some("none") => Some(ObjectFit::None),
3761        other => {
3762            once(
3763                diagnostics,
3764                format!(
3765                    "unsupported value for object-fit: {} — expected fill | contain | cover | \
3766                     scale-down | none",
3767                    other.unwrap_or("<not a keyword>")
3768                ),
3769            );
3770            None
3771        }
3772    }
3773}
3774
3775pub(crate) const WINDOW_CONTROL: &str = "--window-control";
3776
3777fn single_ident<'a>(
3778    value: &'a lightningcss::properties::custom::TokenList<'_>,
3779    what: &str,
3780    diagnostics: &mut Vec<String>,
3781) -> Option<&'a str> {
3782    use lightningcss::properties::custom::{Token, TokenOrValue};
3783    let mut idents = value.0.iter().filter_map(|t| match t {
3784        TokenOrValue::Token(Token::Ident(s)) => Some(s.as_ref()),
3785        _ => None,
3786    });
3787    let first = idents.next();
3788    if idents.next().is_some() {
3789        once(
3790            diagnostics,
3791            format!("`{what}` takes a single keyword — the declaration was dropped"),
3792        );
3793        return None;
3794    }
3795    first
3796}
3797
3798fn clip_path(v: &CssClipPath<'_>, diagnostics: &mut Vec<String>) -> Option<gpui::VnClipPath> {
3799    use gpui::{VnClipBox, VnClipPath, VnShapeRadius};
3800    use lightningcss::properties::masking::GeometryBox as G;
3801    use lightningcss::values::shape::{BasicShape, ShapeRadius};
3802    let reference = |b: &G| match b {
3803        G::MarginBox => VnClipBox::Margin,
3804        G::BorderBox | G::StrokeBox | G::ViewBox => VnClipBox::Border,
3805        G::PaddingBox => VnClipBox::Padding,
3806        G::ContentBox | G::FillBox => VnClipBox::Content,
3807    };
3808    let radius = |r: &ShapeRadius| match r {
3809        ShapeRadius::LengthPercentage(lp) => lp_definite(lp).map(VnShapeRadius::Length),
3810        ShapeRadius::ClosestSide => Some(VnShapeRadius::ClosestSide),
3811        ShapeRadius::FarthestSide => Some(VnShapeRadius::FarthestSide),
3812    };
3813    let unsupported = |diagnostics: &mut Vec<String>, what: &str| {
3814        clip_path_unsupported(diagnostics, what);
3815        None
3816    };
3817    match v {
3818        CssClipPath::None => Some(VnClipPath::None),
3819        CssClipPath::Box(b) => Some(VnClipPath::Box(reference(b))),
3820        CssClipPath::Url(_) => unsupported(diagnostics, "url()"),
3821        CssClipPath::Shape {
3822            shape,
3823            reference_box,
3824        } => {
3825            let reference = reference(reference_box);
3826            match &**shape {
3827                BasicShape::Inset(inset) => {
3828                    let r = &inset.rect;
3829                    let insets = [
3830                        lp_definite(&r.0)?,
3831                        lp_definite(&r.1)?,
3832                        lp_definite(&r.2)?,
3833                        lp_definite(&r.3)?,
3834                    ];
3835                    let corner = |c: &lightningcss::values::size::Size2D<LengthPercentage>| {
3836                        Some(gpui::VnCornerRadius {
3837                            x: lp_definite(&c.0)?,
3838                            y: lp_definite(&c.1)?,
3839                        })
3840                    };
3841                    let b = &inset.radius;
3842                    let radii = [
3843                        corner(&b.top_left)?,
3844                        corner(&b.top_right)?,
3845                        corner(&b.bottom_right)?,
3846                        corner(&b.bottom_left)?,
3847                    ];
3848                    Some(VnClipPath::Inset {
3849                        reference,
3850                        insets,
3851                        radii,
3852                    })
3853                }
3854                BasicShape::Circle(c) => {
3855                    let r = radius(&c.radius)?;
3856                    let center = shape_center(&c.position)?;
3857                    Some(VnClipPath::Ellipse {
3858                        reference,
3859                        center,
3860                        radius: [r, r],
3861                        circle: true,
3862                    })
3863                }
3864                BasicShape::Ellipse(e) => {
3865                    let (rx, ry) = (radius(&e.radius_x)?, radius(&e.radius_y)?);
3866                    let center = shape_center(&e.position)?;
3867                    Some(VnClipPath::Ellipse {
3868                        reference,
3869                        center,
3870                        radius: [rx, ry],
3871                        circle: false,
3872                    })
3873                }
3874                BasicShape::Polygon(polygon) => match clip_path_polygon(polygon) {
3875                    Some(points) => Some(VnClipPath::Polygon {
3876                        reference,
3877                        fill_rule: fill_rule(polygon.fill_rule),
3878                        points: points.into(),
3879                    }),
3880                    None => unsupported(
3881                        diagnostics,
3882                        "polygon() with a vertex that is no length or percentage",
3883                    ),
3884                },
3885            }
3886        }
3887    }
3888}
3889
3890fn clip_path_unsupported(diagnostics: &mut Vec<String>, what: &str) {
3891    warn_once(
3892        diagnostics,
3893        &format!(
3894            "`clip-path: {what}` is not applied (v1) and the element paints unclipped — \
3895             `inset()`, `circle()`, `ellipse()`, `polygon()`, `path()` and a box \
3896             (`padding-box`…) are honoured"
3897        ),
3898    );
3899}
3900
3901fn fill_rule(rule: lightningcss::values::shape::FillRule) -> gpui::VnFillRule {
3902    match rule {
3903        lightningcss::values::shape::FillRule::Nonzero => gpui::VnFillRule::NonZero,
3904        lightningcss::values::shape::FillRule::Evenodd => gpui::VnFillRule::EvenOdd,
3905    }
3906}
3907
3908fn clip_path_polygon(
3909    polygon: &lightningcss::values::shape::Polygon,
3910) -> Option<Vec<[DefiniteLength; 2]>> {
3911    use lightningcss::traits::{Parse, ToCss};
3912    polygon
3913        .points
3914        .iter()
3915        .map(|point| {
3916            let text = point
3917                .to_css_string(lightningcss::stylesheet::PrinterOptions::default())
3918                .ok()?;
3919            let mut depth = 0i32;
3920            let split = text.char_indices().find_map(|(i, c)| {
3921                match c {
3922                    '(' => depth += 1,
3923                    ')' => depth -= 1,
3924                    ' ' if depth == 0 => return Some(i),
3925                    _ => {}
3926                }
3927                None
3928            })?;
3929            let x = LengthPercentage::parse_string(text[..split].trim()).ok()?;
3930            let y = LengthPercentage::parse_string(text[split..].trim()).ok()?;
3931            Some([lp_definite(&x)?, lp_definite(&y)?])
3932        })
3933        .collect()
3934}
3935
3936fn clip_path_path(
3937    tokens: &lightningcss::properties::custom::TokenList<'_>,
3938) -> Option<Result<gpui::VnClipPath, String>> {
3939    use gpui::{VnClipBox, VnFillRule};
3940    use lightningcss::properties::custom::{Token, TokenOrValue};
3941    let mut path = None;
3942    let mut reference = None;
3943    for t in &tokens.0 {
3944        match t {
3945            TokenOrValue::Function(f)
3946                if f.name.0.as_ref().eq_ignore_ascii_case("path") && path.is_none() =>
3947            {
3948                path = Some(&f.arguments);
3949            }
3950            TokenOrValue::Token(Token::Ident(id)) if path.is_some() && reference.is_none() => {
3951                reference = Some(match id.as_ref().to_ascii_lowercase().as_str() {
3952                    "margin-box" => VnClipBox::Margin,
3953                    "border-box" | "stroke-box" | "view-box" => VnClipBox::Border,
3954                    "padding-box" => VnClipBox::Padding,
3955                    "content-box" | "fill-box" => VnClipBox::Content,
3956                    other => return Some(Err(format!("`{other}` is no <geometry-box>"))),
3957                });
3958            }
3959            TokenOrValue::Token(Token::WhiteSpace(_)) => {}
3960            _ if path.is_none() => return None,
3961            _ => return Some(Err("unexpected text after `path()`".into())),
3962        }
3963    }
3964    let arguments = path?;
3965    let mut fill_rule = None;
3966    let mut data = None;
3967    let mut comma = false;
3968    for t in &arguments.0 {
3969        match t {
3970            TokenOrValue::Token(Token::WhiteSpace(_)) => {}
3971            TokenOrValue::Token(Token::Ident(id)) if fill_rule.is_none() && data.is_none() => {
3972                fill_rule = Some(match id.as_ref().to_ascii_lowercase().as_str() {
3973                    "nonzero" => VnFillRule::NonZero,
3974                    "evenodd" => VnFillRule::EvenOdd,
3975                    other => return Some(Err(format!("`{other}` is no <fill-rule>"))),
3976                });
3977            }
3978            TokenOrValue::Token(Token::Comma) if fill_rule.is_some() && !comma => comma = true,
3979            TokenOrValue::Token(Token::String(d))
3980                if data.is_none() && (fill_rule.is_none() || comma) =>
3981            {
3982                data = Some(d.as_ref().to_string());
3983            }
3984            _ => {
3985                return Some(Err(
3986                    "`path()` takes an optional fill rule, a comma and a string".into(),
3987                ))
3988            }
3989        }
3990    }
3991    let Some(data) = data else {
3992        return Some(Err("`path()` has no path string".into()));
3993    };
3994    Some(
3995        crate::path_data::parse(&data).map(|verbs| gpui::VnClipPath::Path {
3996            reference: reference.unwrap_or_default(),
3997            fill_rule: fill_rule.unwrap_or_default(),
3998            verbs: verbs.into(),
3999        }),
4000    )
4001}
4002
4003fn shape_center(
4004    position: &lightningcss::values::position::Position,
4005) -> Option<[DefiniteLength; 2]> {
4006    use lightningcss::values::position::PositionComponent as P;
4007    fn component<S: PositionSide + Copy>(c: &P<S>) -> Option<DefiniteLength> {
4008        match c {
4009            P::Center => Some(relative(0.5)),
4010            P::Length(lp) => lp_definite(lp),
4011            P::Side { side, offset } => {
4012                let near = side.is_near_edge();
4013                let Some(offset) = offset else {
4014                    return Some(relative(if near { 0.0 } else { 1.0 }));
4015                };
4016                let offset = lp_definite(offset)?;
4017                if near {
4018                    return Some(offset);
4019                }
4020                match offset {
4021                    DefiniteLength::Fraction(f) => Some(relative(1.0 - f)),
4022                    DefiniteLength::Absolute(AbsoluteLength::Pixels(p)) => {
4023                        Some(DefiniteLength::Calc {
4024                            fraction: 1.0,
4025                            pixels: -p,
4026                        })
4027                    }
4028                    DefiniteLength::Calc { fraction, pixels } => Some(DefiniteLength::Calc {
4029                        fraction: 1.0 - fraction,
4030                        pixels: -pixels,
4031                    }),
4032                    DefiniteLength::Absolute(AbsoluteLength::Rems(_)) => None,
4033                }
4034            }
4035        }
4036    }
4037    Some([component(&position.x)?, component(&position.y)?])
4038}
4039
4040fn clip_rect_is_empty(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
4041    use lightningcss::properties::custom::{Token, TokenOrValue};
4042
4043    fn scan(
4044        tokens: &[lightningcss::properties::custom::TokenOrValue<'_>],
4045        saw_rect: &mut bool,
4046        numbers: &mut Vec<f32>,
4047    ) {
4048        for t in tokens {
4049            match t {
4050                // lightningcss keeps a function's arguments NESTED rather than flat, so `rect(0, 0,
4051                // 0, 0)` is one `Function` whose arguments are the four numbers.
4052                TokenOrValue::Function(f) => {
4053                    if f.name.0.as_ref() == "rect" {
4054                        *saw_rect = true;
4055                    }
4056                    scan(&f.arguments.0, saw_rect, numbers);
4057                }
4058                TokenOrValue::Token(Token::Function(name)) if name.as_ref() == "rect" => {
4059                    *saw_rect = true
4060                }
4061                TokenOrValue::Token(Token::Number { value, .. }) => numbers.push(*value),
4062                TokenOrValue::Length(l) => numbers.push(length_value_px(l).unwrap_or(f32::NAN)),
4063                TokenOrValue::Token(Token::Dimension { value, .. }) => numbers.push(*value),
4064                _ => {}
4065            }
4066        }
4067    }
4068
4069    let mut saw_rect = false;
4070    let mut numbers: Vec<f32> = Vec::new();
4071    scan(&value.0, &mut saw_rect, &mut numbers);
4072    saw_rect
4073        && numbers.len() == 4
4074        && ((numbers[0] - numbers[2]).abs() < f32::EPSILON
4075            || (numbers[3] - numbers[1]).abs() < f32::EPSILON)
4076}
4077
4078fn is_css_wide_keyword(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
4079    single_ident_raw(value).is_some_and(|v| {
4080        matches!(
4081            v.to_ascii_lowercase().as_str(),
4082            "inherit" | "initial" | "unset" | "revert" | "revert-layer"
4083        )
4084    })
4085}
4086
4087fn single_ident_is(
4088    value: &lightningcss::properties::custom::TokenList<'_>,
4089    expected: &str,
4090) -> bool {
4091    single_ident_raw(value).is_some_and(|v| v.eq_ignore_ascii_case(expected))
4092}
4093
4094fn font_features(
4095    value: &lightningcss::properties::custom::TokenList<'_>,
4096    property: &str,
4097) -> Option<gpui::FontFeatures> {
4098    use lightningcss::properties::custom::{Token, TokenOrValue};
4099    if is_css_wide_keyword(value) {
4100        return Some(gpui::FontFeatures::default());
4101    }
4102    let mut pairs: Vec<(String, u32)> = Vec::new();
4103    if property == "font-variant-numeric" {
4104        for t in value.0.iter() {
4105            let TokenOrValue::Token(Token::Ident(name)) = t else {
4106                continue;
4107            };
4108            let tag = match name.as_ref() {
4109                "normal" => continue,
4110                "lining-nums" => "lnum",
4111                "oldstyle-nums" => "onum",
4112                "proportional-nums" => "pnum",
4113                "tabular-nums" => "tnum",
4114                "diagonal-fractions" => "frac",
4115                "stacked-fractions" => "afrc",
4116                "ordinal" => "ordn",
4117                "slashed-zero" => "zero",
4118                _ => return None,
4119            };
4120            pairs.push((tag.to_string(), 1));
4121        }
4122        return Some(gpui::FontFeatures(std::sync::Arc::new(pairs)));
4123    }
4124    if property == "font-kerning" {
4125        return match single_ident_raw(value)?.to_ascii_lowercase().as_str() {
4126            "auto" | "normal" => Some(gpui::FontFeatures::default()),
4127            "none" => Some(gpui::FontFeatures(std::sync::Arc::new(vec![(
4128                "kern".into(),
4129                0,
4130            )]))),
4131            _ => None,
4132        };
4133    }
4134    if property == "font-variant-ligatures" {
4135        for t in value.0.iter() {
4136            let TokenOrValue::Token(Token::Ident(name)) = t else {
4137                continue;
4138            };
4139            let set: &[(&str, u32)] = match name.as_ref() {
4140                "normal" => continue,
4141                "none" => &[
4142                    ("liga", 0),
4143                    ("clig", 0),
4144                    ("dlig", 0),
4145                    ("hlig", 0),
4146                    ("calt", 0),
4147                ],
4148                "common-ligatures" => &[("liga", 1), ("clig", 1)],
4149                "no-common-ligatures" => &[("liga", 0), ("clig", 0)],
4150                "discretionary-ligatures" => &[("dlig", 1)],
4151                "no-discretionary-ligatures" => &[("dlig", 0)],
4152                "historical-ligatures" => &[("hlig", 1)],
4153                "no-historical-ligatures" => &[("hlig", 0)],
4154                "contextual" => &[("calt", 1)],
4155                "no-contextual" => &[("calt", 0)],
4156                _ => return None,
4157            };
4158            pairs.extend(set.iter().map(|(tag, v)| (tag.to_string(), *v)));
4159        }
4160        return Some(gpui::FontFeatures(std::sync::Arc::new(pairs)));
4161    }
4162
4163    let mut pending: Option<String> = None;
4164    for t in value.0.iter() {
4165        match t {
4166            TokenOrValue::Token(Token::WhiteSpace(_)) | TokenOrValue::Token(Token::Comma) => {}
4167            TokenOrValue::Token(Token::String(tag)) => {
4168                if let Some(previous) = pending.take() {
4169                    pairs.push((previous, 1));
4170                }
4171                if tag.len() != 4 {
4172                    return None;
4173                }
4174                pending = Some(tag.to_string());
4175            }
4176            TokenOrValue::Token(Token::Number { value, .. }) => {
4177                pairs.push((pending.take()?, *value as u32));
4178            }
4179            TokenOrValue::Token(Token::Ident(word)) => match word.as_ref() {
4180                "on" => pairs.push((pending.take()?, 1)),
4181                "off" => pairs.push((pending.take()?, 0)),
4182                "normal" => {}
4183                _ => return None,
4184            },
4185            _ => return None,
4186        }
4187    }
4188    if let Some(previous) = pending {
4189        pairs.push((previous, 1));
4190    }
4191    Some(gpui::FontFeatures(std::sync::Arc::new(pairs)))
4192}
4193
4194fn single_length_px(value: &lightningcss::properties::custom::TokenList<'_>) -> Option<f32> {
4195    use lightningcss::properties::custom::{Token, TokenOrValue};
4196    let mut found = None;
4197    for t in value.0.iter() {
4198        match t {
4199            TokenOrValue::Token(Token::WhiteSpace(_)) => {}
4200            TokenOrValue::Length(l) => {
4201                if found.is_some() {
4202                    return None;
4203                }
4204                found = length_value_px(l);
4205            }
4206            TokenOrValue::Token(Token::Dimension { value, unit, .. }) => {
4207                if found.is_some() {
4208                    return None;
4209                }
4210                found = match unit.as_ref() {
4211                    "px" => Some(*value),
4212                    other => match font_unit_px(other, *value)
4213                        .or_else(|| viewport_unit_px(other, *value))
4214                        .or_else(|| crate::container::unit_name_px(other, *value))
4215                    {
4216                        Some(px) => Some(px),
4217                        None => return None,
4218                    },
4219                };
4220            }
4221            TokenOrValue::Token(Token::Number { value, .. }) if *value == 0.0 => {
4222                if found.is_some() {
4223                    return None;
4224                }
4225                found = Some(0.0);
4226            }
4227            _ => return None,
4228        }
4229    }
4230    found
4231}
4232
4233fn has_substitution(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
4234    use lightningcss::properties::custom::{TokenOrValue, UnresolvedColor};
4235    value.0.iter().any(|token| match token {
4236        TokenOrValue::Var(_) | TokenOrValue::Env(_) => true,
4237        TokenOrValue::Function(function) => {
4238            function.name.0.starts_with("--") || has_substitution(&function.arguments)
4239        }
4240        TokenOrValue::UnresolvedColor(
4241            UnresolvedColor::RGB { alpha, .. } | UnresolvedColor::HSL { alpha, .. },
4242        ) => has_substitution(alpha),
4243        TokenOrValue::UnresolvedColor(UnresolvedColor::LightDark { light, dark }) => {
4244            has_substitution(light) || has_substitution(dark)
4245        }
4246        _ => false,
4247    })
4248}
4249
4250/// `color-mix(in srgb, currentColor 40%, red)` and `oklch(from currentColor l c h)` depend on the
4251/// element's computed `color`, so they are resolved per element like a `var()`.
4252fn has_current_color_function(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
4253    use lightningcss::properties::custom::{Token, TokenOrValue};
4254    fn mentions(value: &lightningcss::properties::custom::TokenList<'_>) -> bool {
4255        value.0.iter().any(|token| match token {
4256            TokenOrValue::Token(Token::Ident(id)) => id.eq_ignore_ascii_case("currentcolor"),
4257            TokenOrValue::Color(lightningcss::values::color::CssColor::CurrentColor) => true,
4258            TokenOrValue::Function(f) => mentions(&f.arguments),
4259            _ => false,
4260        })
4261    }
4262    value.0.iter().any(|token| match token {
4263        TokenOrValue::Function(f) => mentions(&f.arguments),
4264        _ => false,
4265    })
4266}
4267
4268enum ContentValue {
4269    Text(Rc<str>),
4270    None,
4271    Unsupported(String),
4272}
4273
4274fn content_string(value: &lightningcss::properties::custom::TokenList<'_>) -> ContentValue {
4275    use lightningcss::properties::custom::{Token, TokenOrValue};
4276    let mut out = String::new();
4277    let mut saw_string = false;
4278    for t in value.0.iter() {
4279        match t {
4280            TokenOrValue::Token(Token::WhiteSpace(_)) => {}
4281            TokenOrValue::Token(Token::String(sv)) => {
4282                out.push_str(sv.as_ref());
4283                saw_string = true;
4284            }
4285            TokenOrValue::Token(Token::Ident(id)) if matches!(id.as_ref(), "none" | "normal") => {
4286                return ContentValue::None;
4287            }
4288            TokenOrValue::Token(Token::Function(f)) => {
4289                return ContentValue::Unsupported(format!("{}()", f.as_ref()));
4290            }
4291            TokenOrValue::Url(_) => return ContentValue::Unsupported("url()".into()),
4292            TokenOrValue::Token(Token::Ident(id)) => {
4293                return ContentValue::Unsupported(id.as_ref().to_string());
4294            }
4295            TokenOrValue::Var(_) => return ContentValue::Unsupported("var()".into()),
4296            _ => return ContentValue::Unsupported("that value".into()),
4297        }
4298    }
4299    if saw_string {
4300        ContentValue::Text(Rc::from(out.as_str()))
4301    } else {
4302        ContentValue::None
4303    }
4304}
4305
4306fn single_ident_raw<'a>(
4307    value: &'a lightningcss::properties::custom::TokenList<'_>,
4308) -> Option<&'a str> {
4309    use lightningcss::properties::custom::{Token, TokenOrValue};
4310    let mut found = None;
4311    for t in value.0.iter() {
4312        match t {
4313            TokenOrValue::Token(Token::WhiteSpace(_)) => {}
4314            TokenOrValue::Token(Token::Ident(id)) => {
4315                if found.is_some() {
4316                    return None;
4317                }
4318                found = Some(id.as_ref());
4319            }
4320            _ => return None,
4321        }
4322    }
4323    found
4324}
4325
4326fn single_number(value: &lightningcss::properties::custom::TokenList<'_>) -> Option<f32> {
4327    use lightningcss::properties::custom::{Token, TokenOrValue};
4328    let mut found = None;
4329    for t in value.0.iter() {
4330        match t {
4331            TokenOrValue::Token(Token::WhiteSpace(_)) => {}
4332            TokenOrValue::Token(Token::Number { value, .. }) => {
4333                if found.is_some() {
4334                    return None;
4335                }
4336                found = Some(*value);
4337            }
4338            _ => return None,
4339        }
4340    }
4341    found
4342}
4343
4344fn window_drag(
4345    property: &str,
4346    value: &lightningcss::properties::custom::TokenList,
4347    diagnostics: &mut Vec<String>,
4348) -> Option<WindowDrag> {
4349    match single_ident(value, property, diagnostics) {
4350        Some("move") | Some("drag") => Some(WindowDrag::Move),
4351        Some("none") | Some("no-drag") => Some(WindowDrag::None),
4352        other => {
4353            once(
4354                diagnostics,
4355                format!(
4356                    "unsupported value for `{property}`: {} — expected `move` | `none` \
4357                     (or the legacy `drag` | `no-drag`)",
4358                    other.unwrap_or("<not a keyword>")
4359                ),
4360            );
4361            None
4362        }
4363    }
4364}
4365
4366fn scrollbar_width(
4367    value: &lightningcss::properties::custom::TokenList,
4368    diagnostics: &mut Vec<String>,
4369) -> Option<ScrollbarWidth> {
4370    match single_ident(value, "scrollbar-width", diagnostics) {
4371        Some("auto") => Some(ScrollbarWidth::Auto),
4372        Some("thin") => Some(ScrollbarWidth::Thin),
4373        Some("none") => Some(ScrollbarWidth::None),
4374        other => {
4375            once(
4376                diagnostics,
4377                format!(
4378                    "unsupported value for `scrollbar-width`: {} — expected `auto` | `thin`                      | `none`",
4379                    other.unwrap_or("<not a keyword>")
4380                ),
4381            );
4382            None
4383        }
4384    }
4385}
4386
4387/// Unknown properties arrive as a raw token list, so there is no typed `CssColor` for `red`;
4388/// re-parse it as one.
4389fn named_color(ident: &str) -> Option<Hsla> {
4390    match Property::parse_string(PropertyId::from("color"), ident, ParserOptions::default()) {
4391        Ok(Property::Color(c)) => color(&c),
4392        _ => None,
4393    }
4394}
4395
4396fn scrollbar_color(
4397    value: &lightningcss::properties::custom::TokenList,
4398    diagnostics: &mut Vec<String>,
4399) -> Option<(Hsla, Hsla)> {
4400    use lightningcss::properties::custom::{
4401        CustomProperty, CustomPropertyName, Token, TokenOrValue,
4402    };
4403    let tokens: Vec<_> = value
4404        .0
4405        .iter()
4406        .filter(|token| !token.is_whitespace())
4407        .collect();
4408    if matches!(tokens.as_slice(), [TokenOrValue::Token(Token::Ident(id))] if id.as_ref().eq_ignore_ascii_case("auto"))
4409    {
4410        return None;
4411    }
4412    let property = Property::Custom(CustomProperty {
4413        name: CustomPropertyName::Unknown(lightningcss::values::ident::Ident(
4414            "scrollbar-color".into(),
4415        )),
4416        value: value.clone(),
4417    });
4418    if tokens.len() == 2 {
4419        if let Some(raw) = value_text(&property) {
4420            if let Ok(Property::BorderColor(pair)) = Property::parse_string(
4421                PropertyId::from("border-color"),
4422                &raw,
4423                ParserOptions::default(),
4424            ) {
4425                if let (Some(thumb), Some(track)) = (color(&pair.top), color(&pair.right)) {
4426                    return Some((thumb, track));
4427                }
4428            }
4429        }
4430    }
4431    once(
4432        diagnostics,
4433        "`scrollbar-color` requires auto or two valid colours (thumb then track)".to_string(),
4434    );
4435    None
4436}
4437
4438/// `contain` as (paint containment, size-contained axes): layout and style containment change
4439/// nothing visible here.
4440fn contain(
4441    value: &lightningcss::properties::custom::TokenList,
4442    diagnostics: &mut Vec<String>,
4443) -> Option<(bool, u8)> {
4444    use lightningcss::properties::custom::{Token, TokenOrValue};
4445    let (mut paint, mut size) = (false, 0);
4446    for token in value.0.iter().filter(|t| !t.is_whitespace()) {
4447        let TokenOrValue::Token(Token::Ident(id)) = token else {
4448            unsupported(diagnostics, "contain");
4449            return None;
4450        };
4451        match id.to_ascii_lowercase().as_str() {
4452            "none" | "layout" | "style" => {}
4453            "paint" | "content" => paint = true,
4454            "strict" => (paint, size) = (true, Extras::CONTAIN_WIDTH | Extras::CONTAIN_HEIGHT),
4455            "size" => size = Extras::CONTAIN_WIDTH | Extras::CONTAIN_HEIGHT,
4456            "inline-size" => size |= Extras::CONTAIN_WIDTH,
4457            _ => {
4458                unsupported(diagnostics, "contain");
4459                return None;
4460            }
4461        }
4462    }
4463    Some((paint, size))
4464}
4465
4466fn container_axes(
4467    t: &lightningcss::properties::contain::ContainerType,
4468    diagnostics: &mut Vec<String>,
4469) -> u8 {
4470    use lightningcss::properties::contain::ContainerType as T;
4471    match t {
4472        T::Normal => 0,
4473        T::ScrollState => {
4474            once(
4475                diagnostics,
4476                "`container-type: scroll-state` is not supported: scroll-state container \
4477                 queries are not implemented, so the element is not a query container"
4478                    .to_string(),
4479            );
4480            0
4481        }
4482        T::InlineSize => crate::container::INLINE,
4483        T::Size => crate::container::INLINE | crate::container::BLOCK,
4484    }
4485}
4486
4487fn container_names(
4488    names: &lightningcss::properties::contain::ContainerNameList,
4489) -> Option<Rc<[Rc<str>]>> {
4490    use lightningcss::properties::contain::ContainerNameList as L;
4491    match names {
4492        L::None => None,
4493        L::Names(list) => Some(list.iter().map(|n| Rc::from(n.0 .0.as_ref())).collect()),
4494    }
4495}
4496
4497/// The size containment `contain` and `container-type` ask for, which layout applies.
4498pub(crate) fn apply_size_containment(r: &mut StyleRefinement, x: &Extras) {
4499    let axes = x.contain_size.unwrap_or(0) | x.container_type.unwrap_or(0);
4500    if axes != 0 {
4501        r.vn_contain_size = Some(axes);
4502    }
4503}
4504
4505fn overscroll(
4506    property: &str,
4507    value: &lightningcss::properties::custom::TokenList,
4508    diagnostics: &mut Vec<String>,
4509) -> Option<OverscrollBehavior> {
4510    match single_ident(value, property, diagnostics) {
4511        Some("auto") => Some(OverscrollBehavior::Auto),
4512        Some("contain") => Some(OverscrollBehavior::Contain),
4513        Some("none") => Some(OverscrollBehavior::None),
4514        other => {
4515            once(
4516                diagnostics,
4517                format!(
4518                    "unsupported value for `{property}`: {} — expected `auto` | `contain`                      | `none`",
4519                    other.unwrap_or("<not a keyword>")
4520                ),
4521            );
4522            None
4523        }
4524    }
4525}
4526
4527fn window_control(
4528    value: &lightningcss::properties::custom::TokenList,
4529    diagnostics: &mut Vec<String>,
4530) -> Option<WindowControl> {
4531    match single_ident(value, WINDOW_CONTROL, diagnostics) {
4532        Some("minimize") => Some(WindowControl::Minimize),
4533        Some("maximize") => Some(WindowControl::Maximize),
4534        Some("close") => Some(WindowControl::Close),
4535        Some("none") => Some(WindowControl::None),
4536        other => {
4537            once(
4538                diagnostics,
4539                format!(
4540                    "unsupported value for `{WINDOW_CONTROL}`: {} — expected \
4541                     `minimize` | `maximize` | `close` | `none`",
4542                    other.unwrap_or("<not a keyword>")
4543                ),
4544            );
4545            None
4546        }
4547    }
4548}
4549
4550fn apply(p: &Property, r: &mut StyleRefinement, x: &mut Extras, diagnostics: &mut Vec<String>) {
4551    CALC_DROPPED.with(|c| c.set(false));
4552    apply_property(p, r, x, diagnostics);
4553    if CALC_DROPPED.with(|c| c.replace(false)) {
4554        once(
4555            diagnostics,
4556            format!(
4557                "`{}`: this calc() is dropped (v1) — a calc() that mixes a percentage with a \
4558                 length is resolved at layout only by the sizing properties (width/height and \
4559                 their min/max, inset, margin, padding, gap, flex-basis) and at paint by \
4560                 border-radius, and only in its linear form (sums and scalings; min()/max()/clamp() over a percentage are \
4561                 not). Here the declaration is ignored, as if it were invalid. Write the \
4562                 length or the percentage alone, or move the offset into a sizing property",
4563                p.property_id().name()
4564            ),
4565        );
4566    }
4567}
4568
4569/// gpui's `aspect_ratio` encoding, since a refinement cannot clear a field: `0` is `auto` (no
4570/// preferred ratio, or a degenerate one), a negative ratio is `auto && <ratio>` (a replaced
4571/// element's natural ratio wins over it), a positive one is the ratio alone.
4572fn aspect_ratio(auto: bool, ratio: Option<&lightningcss::values::ratio::Ratio>) -> f32 {
4573    match ratio {
4574        Some(r) if r.0 > 0.0 && r.1 > 0.0 && (r.0 / r.1).is_finite() => {
4575            let value = r.0 / r.1;
4576            if auto {
4577                -value
4578            } else {
4579                value
4580            }
4581        }
4582        _ => 0.0,
4583    }
4584}
4585
4586fn flex_direction(d: &CssFlexDirection) -> gpui::FlexDirection {
4587    match d {
4588        CssFlexDirection::Row => gpui::FlexDirection::Row,
4589        CssFlexDirection::RowReverse => gpui::FlexDirection::RowReverse,
4590        CssFlexDirection::Column => gpui::FlexDirection::Column,
4591        CssFlexDirection::ColumnReverse => gpui::FlexDirection::ColumnReverse,
4592    }
4593}
4594
4595fn flex_wrap(w: &lightningcss::properties::flex::FlexWrap) -> gpui::FlexWrap {
4596    use lightningcss::properties::flex::FlexWrap as W;
4597    match w {
4598        W::NoWrap => gpui::FlexWrap::NoWrap,
4599        W::Wrap => gpui::FlexWrap::Wrap,
4600        W::WrapReverse => gpui::FlexWrap::WrapReverse,
4601    }
4602}
4603
4604fn apply_property(
4605    p: &Property,
4606    r: &mut StyleRefinement,
4607    x: &mut Extras,
4608    diagnostics: &mut Vec<String>,
4609) {
4610    use Property::*;
4611    match p {
4612        Display(d) => {
4613            use lightningcss::properties::display::{Display as D, DisplayOutside};
4614            // Reset on every `display` declaration, so a later `display: flex` un-does an earlier
4615            // `display: inline-flex` rather than leaving the flag behind (`refine` is later-wins
4616            // per FIELD).
4617            x.inline_level = Some(matches!(
4618                d,
4619                D::Pair(p) if matches!(p.outside, DisplayOutside::Inline)
4620            ));
4621            r.display = Some(match d {
4622                D::Keyword(DisplayKeyword::None) => gpui::Display::None,
4623                D::Pair(pair) => match pair.inside {
4624                    DisplayInside::Flex(_) => gpui::Display::Flex,
4625                    DisplayInside::Grid => gpui::Display::Grid,
4626                    _ => gpui::Display::Block,
4627                },
4628                _ => gpui::Display::Block,
4629            });
4630        }
4631        FlexDirection(d, _) => r.flex_direction = Some(flex_direction(d)),
4632        FlexFlow(v, _) => {
4633            r.flex_direction = Some(flex_direction(&v.direction));
4634            r.flex_wrap = Some(flex_wrap(&v.wrap));
4635        }
4636        FlexGrow(v, _) => r.flex_grow = Some(*v),
4637        FlexShrink(v, _) => r.flex_shrink = Some(*v),
4638        Order(v, _) => r.vn_order = Some(*v),
4639        ContainerType(t) => x.container_type = Some(container_axes(t, diagnostics)),
4640        ContainerName(names) => x.container_name = Some(container_names(names)),
4641        Container(c) => {
4642            x.container_type = Some(container_axes(&c.container_type, diagnostics));
4643            x.container_name = Some(container_names(&c.name));
4644        }
4645        FlexBasis(v, _) => r.flex_basis = lpa_length(v),
4646        Flex(v, _) => {
4647            r.flex_grow = Some(v.grow);
4648            r.flex_shrink = Some(v.shrink);
4649            r.flex_basis = lpa_length(&v.basis);
4650        }
4651        FlexWrap(v, _) => r.flex_wrap = Some(flex_wrap(v)),
4652        AlignItems(v, _) => {
4653            use gpui::AlignItems as G;
4654            let mapped = match v {
4655                lightningcss::properties::align::AlignItems::Stretch => Some(G::Stretch),
4656                lightningcss::properties::align::AlignItems::SelfPosition { value, .. } => {
4657                    Some(self_position(value))
4658                }
4659                lightningcss::properties::align::AlignItems::BaselinePosition(_) => {
4660                    Some(G::Baseline)
4661                }
4662                _ => None,
4663            };
4664            match mapped {
4665                Some(m) => r.align_items = Some(m),
4666                None => unsupported(diagnostics, "align-items"),
4667            }
4668        }
4669        AlignSelf(v, _) => {
4670            use lightningcss::properties::align::AlignSelf as A;
4671            let mapped = match v {
4672                // `self-auto`: inherit the parent's align-items. gpui spells that as "unset", and a
4673                // refinement cannot express "clear" — so leave the field alone rather than pin it
4674                // to Stretch.
4675                A::Auto => None,
4676                A::Stretch => Some(gpui::AlignItems::Stretch),
4677                A::BaselinePosition(_) => Some(gpui::AlignItems::Baseline),
4678                A::SelfPosition { value, .. } => Some(self_position(value)),
4679                A::Normal => None,
4680            };
4681            match mapped {
4682                Some(m) => r.align_self = Some(m),
4683                // `auto`/`normal` mean "defer to the parent", which is already what an unset
4684                // refinement does — but say so, because a rule that MEANT to undo an earlier
4685                // `self-center` will not.
4686                None => unsupported(
4687                    diagnostics,
4688                    "align-self: auto/normal — cannot undo an earlier align-self",
4689                ),
4690            }
4691        }
4692        AlignContent(v, _) => {
4693            use gpui::AlignContent as G;
4694            use lightningcss::properties::align::AlignContent as A;
4695            let mapped = match v {
4696                A::ContentDistribution(d) => {
4697                    use lightningcss::properties::align::ContentDistribution as CD;
4698                    Some(match d {
4699                        CD::SpaceBetween => G::SpaceBetween,
4700                        CD::SpaceAround => G::SpaceAround,
4701                        CD::SpaceEvenly => G::SpaceEvenly,
4702                        CD::Stretch => G::Stretch,
4703                    })
4704                }
4705                A::ContentPosition { value, .. } => Some(match value {
4706                    ContentPosition::Center => G::Center,
4707                    ContentPosition::Start | ContentPosition::FlexStart => G::FlexStart,
4708                    ContentPosition::End | ContentPosition::FlexEnd => G::FlexEnd,
4709                }),
4710                _ => None,
4711            };
4712            match mapped {
4713                Some(m) => r.align_content = Some(m),
4714                None => unsupported(diagnostics, "align-content"),
4715            }
4716        }
4717        JustifyContent(v, _) => {
4718            use gpui::JustifyContent as G;
4719            let mapped = match v {
4720                lightningcss::properties::align::JustifyContent::ContentDistribution(d) => {
4721                    use lightningcss::properties::align::ContentDistribution as CD;
4722                    Some(match d {
4723                        CD::SpaceBetween => G::SpaceBetween,
4724                        CD::SpaceAround => G::SpaceAround,
4725                        CD::SpaceEvenly => G::SpaceEvenly,
4726                        CD::Stretch => G::Stretch,
4727                    })
4728                }
4729                lightningcss::properties::align::JustifyContent::ContentPosition {
4730                    value, ..
4731                } => match value {
4732                    ContentPosition::Center => Some(G::Center),
4733                    ContentPosition::Start | ContentPosition::FlexStart => Some(G::FlexStart),
4734                    ContentPosition::End | ContentPosition::FlexEnd => Some(G::FlexEnd),
4735                },
4736                _ => None,
4737            };
4738            match mapped {
4739                Some(m) => r.justify_content = Some(m),
4740                None => unsupported(diagnostics, "justify-content"),
4741            }
4742        }
4743        Gap(gap) => {
4744            if let Some(v) = gap_definite(&gap.row) {
4745                r.gap.height = Some(v);
4746            }
4747            if let Some(v) = gap_definite(&gap.column) {
4748                r.gap.width = Some(v);
4749            }
4750        }
4751        RowGap(v) => r.gap.height = gap_definite(v),
4752        ColumnGap(v) => r.gap.width = gap_definite(v),
4753        Width(v) => r.size.width = size_length(v),
4754        Height(v) => r.size.height = size_length(v),
4755        MinWidth(v) => r.min_size.width = size_length(v),
4756        MinHeight(v) => r.min_size.height = size_length(v),
4757        MaxWidth(v) => r.max_size.width = max_size_length(v),
4758        MaxHeight(v) => r.max_size.height = max_size_length(v),
4759        InlineSize(v) => r.size.width = size_length(v),
4760        BlockSize(v) => r.size.height = size_length(v),
4761        MinInlineSize(v) => r.min_size.width = size_length(v),
4762        MinBlockSize(v) => r.min_size.height = size_length(v),
4763        MaxInlineSize(v) => r.max_size.width = max_size_length(v),
4764        MaxBlockSize(v) => r.max_size.height = max_size_length(v),
4765        Padding(v) => {
4766            r.padding.top = lp_definite_of_lpa(&v.top);
4767            r.padding.right = lp_definite_of_lpa(&v.right);
4768            r.padding.bottom = lp_definite_of_lpa(&v.bottom);
4769            r.padding.left = lp_definite_of_lpa(&v.left);
4770        }
4771        PaddingTop(v) => r.padding.top = lp_definite_of_lpa(v),
4772        PaddingRight(v) => r.padding.right = lp_definite_of_lpa(v),
4773        PaddingBottom(v) => r.padding.bottom = lp_definite_of_lpa(v),
4774        PaddingLeft(v) => r.padding.left = lp_definite_of_lpa(v),
4775        Margin(v) => {
4776            r.margin.top = lpa_length(&v.top);
4777            r.margin.right = lpa_length(&v.right);
4778            r.margin.bottom = lpa_length(&v.bottom);
4779            r.margin.left = lpa_length(&v.left);
4780        }
4781        MarginTop(v) => r.margin.top = lpa_length(v),
4782        MarginRight(v) => r.margin.right = lpa_length(v),
4783        MarginBottom(v) => r.margin.bottom = lpa_length(v),
4784        MarginLeft(v) => r.margin.left = lpa_length(v),
4785        PaddingInline(v) => {
4786            r.padding.left = lp_definite_of_lpa(&v.inline_start);
4787            r.padding.right = lp_definite_of_lpa(&v.inline_end);
4788        }
4789        PaddingBlock(v) => {
4790            r.padding.top = lp_definite_of_lpa(&v.block_start);
4791            r.padding.bottom = lp_definite_of_lpa(&v.block_end);
4792        }
4793        PaddingInlineStart(v) => r.padding.left = lp_definite_of_lpa(v),
4794        PaddingInlineEnd(v) => r.padding.right = lp_definite_of_lpa(v),
4795        PaddingBlockStart(v) => r.padding.top = lp_definite_of_lpa(v),
4796        PaddingBlockEnd(v) => r.padding.bottom = lp_definite_of_lpa(v),
4797        MarginInline(v) => {
4798            r.margin.left = lpa_length(&v.inline_start);
4799            r.margin.right = lpa_length(&v.inline_end);
4800        }
4801        MarginBlock(v) => {
4802            r.margin.top = lpa_length(&v.block_start);
4803            r.margin.bottom = lpa_length(&v.block_end);
4804        }
4805        MarginInlineStart(v) => r.margin.left = lpa_length(v),
4806        MarginInlineEnd(v) => r.margin.right = lpa_length(v),
4807        MarginBlockStart(v) => r.margin.top = lpa_length(v),
4808        MarginBlockEnd(v) => r.margin.bottom = lpa_length(v),
4809        Position(v) => {
4810            use lightningcss::properties::position::Position as P;
4811            x.fixed = Some(matches!(v, P::Fixed));
4812            x.sticky = Some(matches!(v, P::Sticky(_)));
4813            x.positioned = Some(!matches!(v, P::Static));
4814            r.position = Some(match v {
4815                P::Absolute => gpui::Position::Absolute,
4816                // `fixed` becomes taffy's one out-of-flow mode, resolved against the parent, plus a
4817                // deferred layer; this matches when the parent is the window (portalled overlays)
4818                // and diverges inside a smaller ancestor. The renderer advises, since only it sees
4819                // ancestors.
4820                P::Fixed => gpui::Position::Absolute,
4821                P::Static | P::Relative => gpui::Position::Relative,
4822                _ => gpui::Position::Relative,
4823            });
4824        }
4825        // Recorded as written: `auto` is not `0`, because only an integer makes a stacking context.
4826        ZIndex(v) => {
4827            use lightningcss::properties::position::ZIndex as Z;
4828            match v {
4829                Z::Integer(n) => x.z_index = Some(Some(*n)),
4830                Z::Auto => x.z_index = Some(None),
4831            }
4832        }
4833        Transform(list, _) => apply_transform(list, r, diagnostics),
4834        // Seeded with the initial `50% 50%` so declaring the origin alone does not spell
4835        // `transform: none`.
4836        TransformOrigin(pos, _) => {
4837            use lightningcss::values::position::{
4838                HorizontalPositionKeyword as H, PositionComponent as P,
4839                VerticalPositionKeyword as V,
4840            };
4841            fn axis<S: Copy>(
4842                c: &P<S>,
4843                keyword: impl Fn(&S) -> Option<f32>,
4844            ) -> Option<TransformLength> {
4845                match c {
4846                    P::Center => Some(TransformLength::Fraction(0.5)),
4847                    P::Length(DimensionPercentage::Dimension(l)) => {
4848                        length_value_px(l).map(TransformLength::Pixels)
4849                    }
4850                    P::Length(DimensionPercentage::Percentage(p)) => {
4851                        Some(TransformLength::Fraction(p.0))
4852                    }
4853                    P::Length(DimensionPercentage::Calc(_)) => {
4854                        calc_dropped();
4855                        None
4856                    }
4857                    P::Side { side, offset: None } => keyword(side).map(TransformLength::Fraction),
4858                    P::Side { .. } => None,
4859                }
4860            }
4861            let x = axis(&pos.x, |s: &H| {
4862                Some(match s {
4863                    H::Left => 0.0,
4864                    H::Right => 1.0,
4865                })
4866            });
4867            let y = axis(&pos.y, |s: &V| {
4868                Some(match s {
4869                    V::Top => 0.0,
4870                    V::Bottom => 1.0,
4871                })
4872            });
4873            match (x, y) {
4874                (Some(x), Some(y)) => {
4875                    let spec = r.vn_transform.get_or_insert(TransformSpec::IDENTITY);
4876                    spec.origin = (x, y);
4877                }
4878                _ => unsupported(
4879                    diagnostics,
4880                    "transform-origin with a calc() or keyword-plus-offset component — lengths, \
4881                     percentages and the bare `left/right/top/bottom/center` keywords are modelled",
4882                ),
4883            }
4884        }
4885        // `-webkit-line-clamp` is honoured on its own (below, in the unknown-property bucket where
4886        // lightningcss leaves it), so these are genuinely inert rather than a missing feature.
4887        BoxOrient(..) | BoxAlign(..) | BoxPack(..) => {}
4888        // gpui draws one unbroken rule, so `none` is what it already does and only `auto` diverges.
4889        TextDecorationSkipInk(v, _) => {
4890            use lightningcss::properties::text::TextDecorationSkipInk as Skip;
4891            if !matches!(v, Skip::None) {
4892                warn_once(
4893                    diagnostics,
4894                    "`text-decoration-skip-ink: auto` is not applied (v1) — gpui draws one                      unbroken underline and does not lift it around descenders. `none` (draw it                      straight through) is what it already does",
4895                );
4896            }
4897        }
4898        // Colour, style and thickness live on gpui's decoration, so they land here only if this
4899        // block produced a line; otherwise `Extras::decoration` applies them after the cascade.
4900        TextDecorationColor(c, _) => match color(c) {
4901            Some(v) => {
4902                x.decoration.color = Some(Some(v));
4903                let mut hit = false;
4904                if let Some(u) = r.text.underline.as_mut() {
4905                    u.color = Some(v);
4906                    hit = true;
4907                }
4908                if let Some(s) = r.text.strikethrough.as_mut() {
4909                    s.color = Some(v);
4910                    hit = true;
4911                }
4912                let _ = hit;
4913            }
4914            None => unresolved_color(diagnostics, "text-decoration-color"),
4915        },
4916        TextDecorationStyle(s, _) => {
4917            use lightningcss::properties::text::TextDecorationStyle as S;
4918            x.decoration.wavy = Some(matches!(s, S::Wavy));
4919            if let Some(u) = r.text.underline.as_mut() {
4920                u.wavy = matches!(s, S::Wavy);
4921            }
4922            if !matches!(s, S::Solid | S::Wavy) {
4923                unsupported(
4924                    diagnostics,
4925                    "text-decoration-style — gpui draws a solid or a wavy line, so `double`, \
4926                     `dotted` and `dashed` fall back to solid",
4927                );
4928            }
4929        }
4930        TextDecorationThickness(t) => {
4931            use lightningcss::properties::text::TextDecorationThickness as T;
4932            if let T::LengthPercentage(DimensionPercentage::Dimension(l)) = t {
4933                if let Some(w) = length_value_px(l) {
4934                    x.decoration.thickness = Some(w);
4935                    if let Some(u) = r.text.underline.as_mut() {
4936                        u.thickness = px(w);
4937                    }
4938                    if let Some(s) = r.text.strikethrough.as_mut() {
4939                        s.thickness = px(w);
4940                    }
4941                }
4942            }
4943        }
4944        // `text-decoration` shorthand: the line half is the part that renders, and it must run
4945        // BEFORE colour/style so they have something to land on.
4946        TextDecoration(d, _) => {
4947            use lightningcss::properties::text::TextDecorationLine as TDL;
4948            if d.line.contains(TDL::Underline) {
4949                r.text.underline = Some(underline_line());
4950            }
4951            if d.line.contains(TDL::LineThrough) {
4952                r.text.strikethrough = Some(strike_line());
4953            }
4954            x.decoration.color = Some(color(&d.color));
4955            if let Some(c) = color(&d.color) {
4956                if let Some(u) = r.text.underline.as_mut() {
4957                    u.color = Some(c);
4958                }
4959                if let Some(s) = r.text.strikethrough.as_mut() {
4960                    s.color = Some(c);
4961                }
4962            }
4963            if d.line.is_empty() {
4964                unsupported(
4965                    diagnostics,
4966                    "text-decoration: none — cannot undo an earlier underline",
4967                );
4968            }
4969        }
4970        Fill(p) => x.fill = Some(svg_paint(p, "fill", diagnostics)),
4971        Stroke(p) => x.stroke = Some(svg_paint(p, "stroke", diagnostics)),
4972        FillOpacity(_) | FillRule(_) | StrokeOpacity(_) | StrokeWidth(_) | StrokeLinecap(_)
4973        | StrokeLinejoin(_) | StrokeMiterlimit(_) | StrokeDasharray(_) | StrokeDashoffset(_)
4974        | ShapeRendering(_) => {
4975            if let (Some(name), Some(value)) = (presentation_name(p), value_text(p)) {
4976                let value = presentation_value(name, value);
4977                let list = x.svg_presentation.get_or_insert_with(Default::default);
4978                set_presentation(Rc::make_mut(list), name, value.into());
4979            }
4980        }
4981        BoxSizing(v, _) => {
4982            use lightningcss::properties::size::BoxSizing as BS;
4983            if matches!(v, BS::ContentBox) {
4984                warn_once(
4985                    diagnostics,
4986                    "`box-sizing: content-box` is not supported (v1) — taffy sizes every box as \
4987                     `border-box`, so padding and border stay INSIDE the declared width/height",
4988                );
4989            }
4990        }
4991        Top(v) => r.inset.top = lpa_length(v),
4992        Right(v) => r.inset.right = lpa_length(v),
4993        Bottom(v) => r.inset.bottom = lpa_length(v),
4994        Left(v) => r.inset.left = lpa_length(v),
4995        Inset(v) => {
4996            r.inset.top = lpa_length(&v.top);
4997            r.inset.right = lpa_length(&v.right);
4998            r.inset.bottom = lpa_length(&v.bottom);
4999            r.inset.left = lpa_length(&v.left);
5000        }
5001        InsetInline(v) => {
5002            r.inset.left = lpa_length(&v.inline_start);
5003            r.inset.right = lpa_length(&v.inline_end);
5004        }
5005        InsetBlock(v) => {
5006            r.inset.top = lpa_length(&v.block_start);
5007            r.inset.bottom = lpa_length(&v.block_end);
5008        }
5009        InsetInlineStart(v) => r.inset.left = lpa_length(v),
5010        InsetInlineEnd(v) => r.inset.right = lpa_length(v),
5011        InsetBlockStart(v) => r.inset.top = lpa_length(v),
5012        InsetBlockEnd(v) => r.inset.bottom = lpa_length(v),
5013        Overflow(v) => {
5014            r.overflow.x = Some(overflow(v.x));
5015            r.overflow.y = Some(overflow(v.y));
5016            x.overflow_x = Some(v.x);
5017            x.overflow_y = Some(v.y);
5018        }
5019        // One axis each: the other axis's computed value depends on this one, known only after the
5020        // cascade (`compute_overflow`).
5021        OverflowX(v) => {
5022            r.overflow.x = Some(overflow(*v));
5023            x.overflow_x = Some(*v);
5024        }
5025        OverflowY(v) => {
5026            r.overflow.y = Some(overflow(*v));
5027            x.overflow_y = Some(*v);
5028        }
5029        Visibility(v) => {
5030            use lightningcss::properties::display::Visibility as V;
5031            x.visibility_hidden = Some(!matches!(v, V::Visible));
5032            r.visibility = Some(match v {
5033                V::Visible => gpui::Visibility::Visible,
5034                V::Hidden => gpui::Visibility::Hidden,
5035                V::Collapse => gpui::Visibility::Hidden,
5036            });
5037        }
5038        AspectRatio(v) => r.aspect_ratio = Some(aspect_ratio(v.auto, v.ratio.as_ref())),
5039        Opacity(v) => r.opacity = Some(v.0),
5040        // `color: currentColor` IS `color: inherit` — the property resolves against itself — and
5041        // inheriting is what not writing the field does.
5042        Color(CssColor::CurrentColor) => {}
5043        Color(c) => match color(c) {
5044            Some(c) => r.text.color = Some(c),
5045            None => unresolved_color(diagnostics, "color"),
5046        },
5047        BackgroundColor(CssColor::CurrentColor) => {
5048            x.current_color.0 |= CurrentColorTargets::BACKGROUND;
5049        }
5050        BackgroundColor(c) => match color(c) {
5051            Some(c) => {
5052                r.background = Some(gpui::Fill::Color(c.into()));
5053                x.background_key_color = Some(c);
5054            }
5055            None => unresolved_color(diagnostics, "background-color"),
5056        },
5057        Background(layers) => {
5058            if let Some(last) = layers.last() {
5059                if last.color == CssColor::CurrentColor {
5060                    x.current_color.0 |= CurrentColorTargets::BACKGROUND;
5061                } else if let Some(c) = color(&last.color) {
5062                    r.background = Some(gpui::Fill::Color(c.into()));
5063                    x.background_key_color = Some(c);
5064                }
5065            }
5066            collect_background_images(layers.iter().map(|l| &l.image), x, diagnostics);
5067            x.background_size = Some(Rc::new(
5068                layers.iter().map(|l| background_size(&l.size)).collect(),
5069            ));
5070            x.background_position = Some(Rc::new(
5071                layers
5072                    .iter()
5073                    .map(|l| background_position(&l.position, diagnostics))
5074                    .collect(),
5075            ));
5076            x.background_repeat = Some(Rc::new(
5077                layers
5078                    .iter()
5079                    .map(|l| background_repeat(&l.repeat))
5080                    .collect(),
5081            ));
5082        }
5083        BackgroundImage(images) => {
5084            collect_background_images(images.iter(), x, diagnostics);
5085        }
5086        BackgroundSize(sizes) => {
5087            x.background_size = Some(Rc::new(sizes.iter().map(background_size).collect()));
5088        }
5089        BackgroundPosition(positions) => {
5090            x.background_position = Some(Rc::new(
5091                positions
5092                    .iter()
5093                    .map(|p| background_position(p, diagnostics))
5094                    .collect(),
5095            ));
5096        }
5097        BackgroundPositionX(list) => {
5098            let previous = x.background_position.clone();
5099            x.background_position = Some(Rc::new(
5100                list.iter()
5101                    .enumerate()
5102                    .map(|(i, h)| {
5103                        let y = previous
5104                            .as_ref()
5105                            .filter(|p| !p.is_empty())
5106                            .map(|p| p[i % p.len()].1)
5107                            .unwrap_or(TileLength::Fraction(0.0));
5108                        (position_component(h, true, diagnostics), y)
5109                    })
5110                    .collect(),
5111            ));
5112        }
5113        BackgroundPositionY(list) => {
5114            let previous = x.background_position.clone();
5115            x.background_position = Some(Rc::new(
5116                list.iter()
5117                    .enumerate()
5118                    .map(|(i, v)| {
5119                        let h = previous
5120                            .as_ref()
5121                            .filter(|p| !p.is_empty())
5122                            .map(|p| p[i % p.len()].0)
5123                            .unwrap_or(TileLength::Fraction(0.0));
5124                        (h, position_component(v, false, diagnostics))
5125                    })
5126                    .collect(),
5127            ));
5128        }
5129        BackgroundRepeat(list) => {
5130            x.background_repeat = Some(Rc::new(list.iter().map(background_repeat).collect()));
5131        }
5132        BackgroundAttachment(_) | BackgroundOrigin(_) => {}
5133        BackgroundClip(v, _) => {
5134            use lightningcss::properties::background::BackgroundClip as BC;
5135            if matches!(v.first(), Some(BC::Text)) {
5136                x.background_clip_text = Some(true);
5137            } else {
5138                warn_once(
5139                    diagnostics,
5140                    "`background-clip` is ignored (v1) — the background always fills the padding \
5141                     box (`padding-box`, the value a rounded box wants anyway)",
5142                );
5143            }
5144        }
5145        Mask(layers, prefix) => {
5146            let images = mask_images(layers.iter().map(|l| &l.image));
5147            x.mask_images = Some(images);
5148            x.mask_clips = Some(mask_clips(layers.iter().map(|l| &l.clip)));
5149            x.mask_composite = Some(
5150                layers
5151                    .first()
5152                    .map_or(MaskCompositing::Add, |l| mask_compositing(l.composite)),
5153            );
5154            if webkit_mask(
5155                *prefix,
5156                "mask",
5157                images == MaskImages::TwoOpaque,
5158                diagnostics,
5159            ) {
5160                return;
5161            }
5162            collect_mask_images(layers.iter().map(|l| &l.image), x, diagnostics);
5163            x.mask.size = Some(Rc::new(
5164                layers.iter().map(|l| background_size(&l.size)).collect(),
5165            ));
5166            x.mask.position = Some(Rc::new(
5167                layers
5168                    .iter()
5169                    .map(|l| mask_position(&l.position, diagnostics))
5170                    .collect(),
5171            ));
5172            x.mask.repeat = Some(Rc::new(
5173                layers
5174                    .iter()
5175                    .map(|l| background_repeat(&l.repeat))
5176                    .collect(),
5177            ));
5178            x.mask.luminance = Some(mask_luminance(layers.iter().map(|l| &l.mode), diagnostics));
5179            if !(images == MaskImages::TwoOpaque
5180                && x.mask_clips == Some(MaskClips::ContentThenBorder))
5181            {
5182                advise_mask_box(layers.iter().map(|l| &l.origin), "mask-origin", diagnostics);
5183                advise_mask_clip(layers.iter().map(|l| &l.clip), diagnostics);
5184            }
5185            advise_mask(x, diagnostics);
5186        }
5187        MaskImage(images, prefix) => {
5188            let kinds = mask_images(images.iter());
5189            x.mask_images = Some(kinds);
5190            if webkit_mask(
5191                *prefix,
5192                "mask-image",
5193                kinds == MaskImages::TwoOpaque,
5194                diagnostics,
5195            ) {
5196                return;
5197            }
5198            collect_mask_images(images.iter(), x, diagnostics);
5199            advise_mask(x, diagnostics);
5200        }
5201        MaskClip(clips, prefix) => {
5202            let kinds = mask_clips(clips.iter());
5203            x.mask_clips = Some(kinds);
5204            if !webkit_mask(*prefix, "mask-clip", true, diagnostics)
5205                && kinds != MaskClips::ContentThenBorder
5206            {
5207                advise_mask_clip(clips.iter(), diagnostics);
5208            }
5209        }
5210        MaskSize(sizes, prefix) => {
5211            if !webkit_mask(*prefix, "mask-size", false, diagnostics) {
5212                x.mask.size = Some(Rc::new(sizes.iter().map(background_size).collect()));
5213            }
5214        }
5215        MaskPosition(positions, prefix) => {
5216            if !webkit_mask(*prefix, "mask-position", false, diagnostics) {
5217                x.mask.position = Some(Rc::new(
5218                    positions
5219                        .iter()
5220                        .map(|p| mask_position(p, diagnostics))
5221                        .collect(),
5222                ));
5223            }
5224        }
5225        MaskPositionX(list) => {
5226            let previous = x.mask.position.clone();
5227            x.mask.position = Some(Rc::new(
5228                list.iter()
5229                    .enumerate()
5230                    .map(|(i, h)| {
5231                        let y = previous
5232                            .as_ref()
5233                            .filter(|p| !p.is_empty())
5234                            .map(|p| p[i % p.len()].1)
5235                            .unwrap_or(TileLength::Fraction(0.0));
5236                        (position_component(h, true, diagnostics), y)
5237                    })
5238                    .collect(),
5239            ));
5240        }
5241        MaskPositionY(list) => {
5242            let previous = x.mask.position.clone();
5243            x.mask.position = Some(Rc::new(
5244                list.iter()
5245                    .enumerate()
5246                    .map(|(i, v)| {
5247                        let h = previous
5248                            .as_ref()
5249                            .filter(|p| !p.is_empty())
5250                            .map(|p| p[i % p.len()].0)
5251                            .unwrap_or(TileLength::Fraction(0.0));
5252                        (h, position_component(v, false, diagnostics))
5253                    })
5254                    .collect(),
5255            ));
5256        }
5257        MaskRepeat(list, prefix) => {
5258            if !webkit_mask(*prefix, "mask-repeat", false, diagnostics) {
5259                x.mask.repeat = Some(Rc::new(list.iter().map(background_repeat).collect()));
5260            }
5261        }
5262        MaskOrigin(boxes, prefix) => {
5263            if !webkit_mask(*prefix, "mask-origin", false, diagnostics) {
5264                advise_mask_box(boxes.iter(), "mask-origin", diagnostics);
5265            }
5266        }
5267        MaskMode(modes) => x.mask.luminance = Some(mask_luminance(modes.iter(), diagnostics)),
5268        MaskComposite(list) => {
5269            x.mask_composite = Some(
5270                list.first()
5271                    .map_or(MaskCompositing::Add, |c| mask_compositing(*c)),
5272            );
5273            advise_mask(x, diagnostics);
5274        }
5275        WebKitMaskComposite(list) => {
5276            use lightningcss::traits::ToCss;
5277            let first = list
5278                .first()
5279                .and_then(|c| c.to_css_string(Default::default()).ok());
5280            x.mask_composite = Some(webkit_mask_compositing(
5281                first.as_deref().unwrap_or("source-over"),
5282            ));
5283            advise_mask(x, diagnostics);
5284        }
5285        BorderColor(v) => {
5286            all_border_colors(r, x, [&v.top, &v.right, &v.bottom, &v.left], diagnostics)
5287        }
5288        Border(b) => {
5289            if let Some(w) = border_width_px(&b.width) {
5290                let w: AbsoluteLength = px(w).into();
5291                r.border_widths.top = Some(w);
5292                r.border_widths.right = Some(w);
5293                r.border_widths.bottom = Some(w);
5294                r.border_widths.left = Some(w);
5295            }
5296            all_border_colors(r, x, [&b.color; 4], diagnostics);
5297            set_border_style(r, b.style, SIDES_ALL, diagnostics);
5298        }
5299        BorderWidth(v) => {
5300            r.border_widths.top = border_width_px(&v.top).map(|w| px(w).into());
5301            r.border_widths.right = border_width_px(&v.right).map(|w| px(w).into());
5302            r.border_widths.bottom = border_width_px(&v.bottom).map(|w| px(w).into());
5303            r.border_widths.left = border_width_px(&v.left).map(|w| px(w).into());
5304        }
5305        BorderTopColor(c) => border_side_color(
5306            &mut r.vn_border_colors.top,
5307            CurrentColorTargets::BORDER_TOP,
5308            c,
5309            x,
5310            diagnostics,
5311        ),
5312        BorderRightColor(c) => border_side_color(
5313            &mut r.vn_border_colors.right,
5314            CurrentColorTargets::BORDER_RIGHT,
5315            c,
5316            x,
5317            diagnostics,
5318        ),
5319        BorderBottomColor(c) => border_side_color(
5320            &mut r.vn_border_colors.bottom,
5321            CurrentColorTargets::BORDER_BOTTOM,
5322            c,
5323            x,
5324            diagnostics,
5325        ),
5326        BorderLeftColor(c) => border_side_color(
5327            &mut r.vn_border_colors.left,
5328            CurrentColorTargets::BORDER_LEFT,
5329            c,
5330            x,
5331            diagnostics,
5332        ),
5333        BorderTop(b) => {
5334            r.border_widths.top = border_width_px(&b.width).map(|w| px(w).into());
5335            border_side_color(
5336                &mut r.vn_border_colors.top,
5337                CurrentColorTargets::BORDER_TOP,
5338                &b.color,
5339                x,
5340                diagnostics,
5341            );
5342            set_border_style(r, b.style, SIDE_TOP, diagnostics);
5343        }
5344        BorderRight(b) => {
5345            r.border_widths.right = border_width_px(&b.width).map(|w| px(w).into());
5346            border_side_color(
5347                &mut r.vn_border_colors.right,
5348                CurrentColorTargets::BORDER_RIGHT,
5349                &b.color,
5350                x,
5351                diagnostics,
5352            );
5353            set_border_style(r, b.style, SIDE_RIGHT, diagnostics);
5354        }
5355        BorderBottom(b) => {
5356            r.border_widths.bottom = border_width_px(&b.width).map(|w| px(w).into());
5357            border_side_color(
5358                &mut r.vn_border_colors.bottom,
5359                CurrentColorTargets::BORDER_BOTTOM,
5360                &b.color,
5361                x,
5362                diagnostics,
5363            );
5364            set_border_style(r, b.style, SIDE_BOTTOM, diagnostics);
5365        }
5366        BorderLeft(b) => {
5367            r.border_widths.left = border_width_px(&b.width).map(|w| px(w).into());
5368            border_side_color(
5369                &mut r.vn_border_colors.left,
5370                CurrentColorTargets::BORDER_LEFT,
5371                &b.color,
5372                x,
5373                diagnostics,
5374            );
5375            set_border_style(r, b.style, SIDE_LEFT, diagnostics);
5376        }
5377        BorderTopWidth(v) => r.border_widths.top = border_width_px(v).map(|w| px(w).into()),
5378        BorderRightWidth(v) => r.border_widths.right = border_width_px(v).map(|w| px(w).into()),
5379        BorderBottomWidth(v) => r.border_widths.bottom = border_width_px(v).map(|w| px(w).into()),
5380        BorderLeftWidth(v) => r.border_widths.left = border_width_px(v).map(|w| px(w).into()),
5381        BorderStyle(v) => {
5382            set_border_style(r, v.left, SIDE_LEFT, diagnostics);
5383            set_border_style(r, v.bottom, SIDE_BOTTOM, diagnostics);
5384            set_border_style(r, v.right, SIDE_RIGHT, diagnostics);
5385            set_border_style(r, v.top, SIDE_TOP, diagnostics);
5386        }
5387        BorderTopStyle(v) => set_border_style(r, *v, SIDE_TOP, diagnostics),
5388        BorderRightStyle(v) => set_border_style(r, *v, SIDE_RIGHT, diagnostics),
5389        BorderBottomStyle(v) => set_border_style(r, *v, SIDE_BOTTOM, diagnostics),
5390        BorderLeftStyle(v) => set_border_style(r, *v, SIDE_LEFT, diagnostics),
5391        BorderRadius(v, _) => {
5392            let mut wrote = 0;
5393            if corner(
5394                &mut r.corner_radii.top_left,
5395                &mut r.vn_corner_radii.top_left,
5396                &v.top_left,
5397            ) {
5398                wrote |= RadiusInherit::TOP_LEFT;
5399            }
5400            if corner(
5401                &mut r.corner_radii.top_right,
5402                &mut r.vn_corner_radii.top_right,
5403                &v.top_right,
5404            ) {
5405                wrote |= RadiusInherit::TOP_RIGHT;
5406            }
5407            if corner(
5408                &mut r.corner_radii.bottom_right,
5409                &mut r.vn_corner_radii.bottom_right,
5410                &v.bottom_right,
5411            ) {
5412                wrote |= RadiusInherit::BOTTOM_RIGHT;
5413            }
5414            if corner(
5415                &mut r.corner_radii.bottom_left,
5416                &mut r.vn_corner_radii.bottom_left,
5417                &v.bottom_left,
5418            ) {
5419                wrote |= RadiusInherit::BOTTOM_LEFT;
5420            }
5421            x.radius_inherit.write(wrote, false);
5422        }
5423        BorderTopLeftRadius(v, _) => {
5424            if corner(
5425                &mut r.corner_radii.top_left,
5426                &mut r.vn_corner_radii.top_left,
5427                v,
5428            ) {
5429                x.radius_inherit.write(RadiusInherit::TOP_LEFT, false);
5430            }
5431        }
5432        BorderTopRightRadius(v, _) => {
5433            if corner(
5434                &mut r.corner_radii.top_right,
5435                &mut r.vn_corner_radii.top_right,
5436                v,
5437            ) {
5438                x.radius_inherit.write(RadiusInherit::TOP_RIGHT, false);
5439            }
5440        }
5441        BorderBottomRightRadius(v, _) => {
5442            if corner(
5443                &mut r.corner_radii.bottom_right,
5444                &mut r.vn_corner_radii.bottom_right,
5445                v,
5446            ) {
5447                x.radius_inherit.write(RadiusInherit::BOTTOM_RIGHT, false);
5448            }
5449        }
5450        BorderBottomLeftRadius(v, _) => {
5451            if corner(
5452                &mut r.corner_radii.bottom_left,
5453                &mut r.vn_corner_radii.bottom_left,
5454                v,
5455            ) {
5456                x.radius_inherit.write(RadiusInherit::BOTTOM_LEFT, false);
5457            }
5458        }
5459        GridTemplateColumns(v) => match grid_template(v) {
5460            Some(t) => r.grid_cols = Some(t),
5461            None => match grid_tracks(v) {
5462                Some((tracks, auto)) => {
5463                    r.vn_grid_cols = Some(tracks);
5464                    r.vn_grid_cols_auto = Some(auto);
5465                }
5466                None => unsupported(
5467                    diagnostics,
5468                    "grid-template-columns — `fit-content()`, named lines, a `calc()` breadth \
5469                     with a percentage in it, and a `repeat(auto-fill|auto-fit, …)` next to a \
5470                     track that is not fixed-size (invalid CSS) are not modelled; every track \
5471                     list of lengths, percentages, `auto`, `min-content`, `max-content`, \
5472                     `<flex>`, `minmax()` and `repeat()` (counted or auto) is",
5473                ),
5474            },
5475        },
5476        GridTemplateRows(v) => match grid_template(v) {
5477            Some(t) => r.grid_rows = Some(t),
5478            None => match grid_tracks(v) {
5479                Some((tracks, auto)) => {
5480                    r.vn_grid_rows = Some(tracks);
5481                    r.vn_grid_rows_auto = Some(auto);
5482                }
5483                None => unsupported(
5484                    diagnostics,
5485                    "grid-template-rows — `fit-content()`, named lines, a `calc()` breadth with \
5486                     a percentage in it, and a `repeat(auto-fill|auto-fit, …)` next to a track \
5487                     that is not fixed-size (invalid CSS) are not modelled; every track list of \
5488                     lengths, percentages, `auto`, `min-content`, `max-content`, `<flex>`, \
5489                     `minmax()` and `repeat()` (counted or auto) is",
5490                ),
5491            },
5492        },
5493        GridColumnStart(l) | GridColumnEnd(l) | GridRowStart(l) | GridRowEnd(l) => {
5494            let Some(placement) = grid_line(l) else {
5495                unsupported(
5496                    diagnostics,
5497                    "grid-row/grid-column with a NAMED line or area — the named grid is not \
5498                     modelled; use line numbers or `span N`",
5499                );
5500                return;
5501            };
5502            let loc = r.grid_location.get_or_insert_default();
5503            match p {
5504                GridColumnStart(_) => loc.column.start = placement,
5505                GridColumnEnd(_) => loc.column.end = placement,
5506                GridRowStart(_) => loc.row.start = placement,
5507                _ => loc.row.end = placement,
5508            }
5509        }
5510        GridColumn(v) => match (grid_line(&v.start), grid_line(&v.end)) {
5511            (Some(s), Some(e)) => {
5512                let loc = r.grid_location.get_or_insert_default();
5513                loc.column = s..e;
5514            }
5515            _ => unsupported(
5516                diagnostics,
5517                "grid-column with a NAMED line or area — use line numbers or `span N`",
5518            ),
5519        },
5520        GridRow(v) => match (grid_line(&v.start), grid_line(&v.end)) {
5521            (Some(s), Some(e)) => {
5522                let loc = r.grid_location.get_or_insert_default();
5523                loc.row = s..e;
5524            }
5525            _ => unsupported(
5526                diagnostics,
5527                "grid-row with a NAMED line or area — use line numbers or `span N`",
5528            ),
5529        },
5530        GridArea(v) => {
5531            match (
5532                grid_line(&v.row_start),
5533                grid_line(&v.row_end),
5534                grid_line(&v.column_start),
5535                grid_line(&v.column_end),
5536            ) {
5537                (Some(rs), Some(re), Some(cs), Some(ce)) => {
5538                    let loc = r.grid_location.get_or_insert_default();
5539                    loc.row = rs..re;
5540                    loc.column = cs..ce;
5541                }
5542                _ => unsupported(
5543                    diagnostics,
5544                    "grid-area naming a template AREA — `grid-template-areas` is not modelled; \
5545                     the four-line form (`grid-area: 1 / 1 / 3 / 2`) is",
5546                ),
5547            }
5548        }
5549        GridAutoFlow(v) => {
5550            use lightningcss::properties::grid::GridAutoFlow as F;
5551            let dense = v.contains(F::Dense);
5552            r.vn_grid_auto_flow = Some(if v.contains(F::Column) {
5553                if dense {
5554                    gpui::GridAutoFlow::ColumnDense
5555                } else {
5556                    gpui::GridAutoFlow::Column
5557                }
5558            } else if dense {
5559                gpui::GridAutoFlow::RowDense
5560            } else {
5561                gpui::GridAutoFlow::Row
5562            });
5563        }
5564        GridTemplateAreas(_) | GridTemplate(_) | Grid(_) => unsupported(
5565            diagnostics,
5566            "grid-template-areas (and the `grid` / `grid-template` shorthands that carry it) — \
5567             the named grid is not modelled. Declare `grid-template-columns`/`-rows` and place \
5568             items with `grid-column`/`grid-row` line numbers",
5569        ),
5570        GridAutoColumns(list) | GridAutoRows(list) => {
5571            match list.0.iter().map(track_size).collect::<Option<Vec<_>>>() {
5572                Some(tracks) => {
5573                    if matches!(p, GridAutoColumns(_)) {
5574                        r.vn_grid_auto_cols = Some(tracks);
5575                    } else {
5576                        r.vn_grid_auto_rows = Some(tracks);
5577                    }
5578                }
5579                None => unsupported(
5580                    diagnostics,
5581                    "grid-auto-columns / grid-auto-rows — fit-content() and percentage-dependent calc() \
5582                     track sizes are not modelled; use lengths, percentages, auto, min-content, \
5583                     max-content, flex, or minmax()",
5584                ),
5585            }
5586        }
5587        JustifyItems(v) => {
5588            use lightningcss::properties::align::JustifyItems as J;
5589            match v {
5590                J::Normal => r.vn_justify_items = Some(gpui::AlignItems::Stretch),
5591                J::Stretch => r.vn_justify_items = Some(gpui::AlignItems::Stretch),
5592                J::BaselinePosition(_) => r.vn_justify_items = Some(gpui::AlignItems::Baseline),
5593                J::SelfPosition { value, .. } => {
5594                    r.vn_justify_items = Some(self_position(value));
5595                }
5596                J::Legacy(_) => unsupported(diagnostics, "justify-items: legacy"),
5597                J::Left { .. } => r.vn_justify_items = Some(gpui::AlignItems::FlexStart),
5598                J::Right { .. } => r.vn_justify_items = Some(gpui::AlignItems::FlexEnd),
5599            }
5600        }
5601        JustifySelf(v) => {
5602            use lightningcss::properties::align::JustifySelf as J;
5603            match v {
5604                J::Auto | J::Normal | J::Stretch => {
5605                    r.vn_justify_self = Some(gpui::AlignSelf::Stretch)
5606                }
5607                J::BaselinePosition(_) => r.vn_justify_self = Some(gpui::AlignSelf::Baseline),
5608                J::SelfPosition { value, .. } => r.vn_justify_self = Some(self_position(value)),
5609                J::Left { .. } => r.vn_justify_self = Some(gpui::AlignSelf::FlexStart),
5610                J::Right { .. } => r.vn_justify_self = Some(gpui::AlignSelf::FlexEnd),
5611            }
5612        }
5613        PlaceItems(v) => {
5614            use lightningcss::properties::align::{AlignItems as A, JustifyItems as J};
5615            match &v.align {
5616                A::Stretch | A::Normal => r.align_items = Some(gpui::AlignItems::Stretch),
5617                A::BaselinePosition(_) => r.align_items = Some(gpui::AlignItems::Baseline),
5618                A::SelfPosition { value, .. } => r.align_items = Some(self_position(value)),
5619            }
5620            match &v.justify {
5621                J::Normal | J::Stretch => r.vn_justify_items = Some(gpui::AlignItems::Stretch),
5622                J::BaselinePosition(_) => r.vn_justify_items = Some(gpui::AlignItems::Baseline),
5623                J::SelfPosition { value, .. } => r.vn_justify_items = Some(self_position(value)),
5624                J::Legacy(_) => unsupported(diagnostics, "place-items: legacy justify"),
5625                J::Left { .. } => r.vn_justify_items = Some(gpui::AlignItems::FlexStart),
5626                J::Right { .. } => r.vn_justify_items = Some(gpui::AlignItems::FlexEnd),
5627            }
5628        }
5629        Outline(o) => {
5630            use lightningcss::properties::outline::OutlineStyle as OS;
5631            let out = outline_mut(r);
5632            match &o.style {
5633                OS::Auto => out.style = gpui::BorderStyle::Solid,
5634                OS::LineStyle(LineStyle::None) | OS::LineStyle(LineStyle::Hidden) => {
5635                    out.width = px(0.0)
5636                }
5637                OS::LineStyle(ls) => {
5638                    out.style = if matches!(ls, LineStyle::Dashed | LineStyle::Dotted) {
5639                        gpui::BorderStyle::Dashed
5640                    } else {
5641                        gpui::BorderStyle::Solid
5642                    }
5643                }
5644            }
5645            let style = out.style;
5646            // `outline: none` is the whole declaration: there is no width to read and no colour to
5647            // resolve (the shorthand's is the initial `currentColor`, which would advise for
5648            // nothing).
5649            if matches!(&o.style, OS::LineStyle(LineStyle::None | LineStyle::Hidden)) {
5650                x.outline.hidden = Some(true);
5651            } else {
5652                x.outline.hidden = Some(false);
5653                x.outline.style = Some(style);
5654                if let Some(w) = border_width_px(&o.width) {
5655                    r.vn_outline.as_mut().unwrap().width = px(w);
5656                    x.outline.width = Some(w);
5657                }
5658                match &o.color {
5659                    CssColor::CurrentColor => {
5660                        x.current_color.0 |= CurrentColorTargets::OUTLINE;
5661                        x.outline.color = Some(None);
5662                    }
5663                    c => match color(c) {
5664                        Some(c) => {
5665                            r.vn_outline.as_mut().unwrap().color = c;
5666                            x.outline.color = Some(Some(c));
5667                        }
5668                        None => unresolved_color(diagnostics, "outline-color"),
5669                    },
5670                }
5671            }
5672        }
5673        OutlineWidth(w) => {
5674            if let Some(v) = border_width_px(w) {
5675                outline_mut(r).width = px(v);
5676                x.outline.width = Some(v);
5677            }
5678        }
5679        OutlineColor(CssColor::CurrentColor) => {
5680            outline_mut(r);
5681            x.current_color.0 |= CurrentColorTargets::OUTLINE;
5682            x.outline.color = Some(None);
5683        }
5684        OutlineColor(c) => match color(c) {
5685            Some(v) => {
5686                outline_mut(r).color = v;
5687                x.outline.color = Some(Some(v));
5688            }
5689            None => unresolved_color(diagnostics, "outline-color"),
5690        },
5691        OutlineStyle(s) => {
5692            use lightningcss::properties::outline::OutlineStyle as OS;
5693            let out = outline_mut(r);
5694            match s {
5695                OS::LineStyle(LineStyle::None) | OS::LineStyle(LineStyle::Hidden) => {
5696                    out.width = px(0.0);
5697                    x.outline.hidden = Some(true);
5698                }
5699                other => {
5700                    out.style = if matches!(
5701                        other,
5702                        OS::LineStyle(LineStyle::Dashed) | OS::LineStyle(LineStyle::Dotted)
5703                    ) {
5704                        gpui::BorderStyle::Dashed
5705                    } else {
5706                        gpui::BorderStyle::Solid
5707                    };
5708                    x.outline.hidden = Some(false);
5709                    x.outline.style = Some(out.style);
5710                    if out.width == px(0.0) {
5711                        out.width = px(3.0);
5712                    }
5713                }
5714            }
5715        }
5716        BoxShadow(shadows, _) => {
5717            let mut out = Vec::new();
5718            for s in shadows.iter() {
5719                let (Some(c), Some(x), Some(y)) = (
5720                    color(&s.color),
5721                    css_length_px(&s.x_offset),
5722                    css_length_px(&s.y_offset),
5723                ) else {
5724                    // One unresolvable shadow drops ITSELF, not the list — but it does not drop in
5725                    // silence, because a missing ring in a stack of three is invisible to read
5726                    // back.
5727                    unresolved_color(diagnostics, "box-shadow");
5728                    continue;
5729                };
5730                out.push(gpui::BoxShadow {
5731                    color: c,
5732                    offset: gpui::point(px(x), px(y)),
5733                    blur_radius: px(css_length_px(&s.blur).unwrap_or(0.0)),
5734                    spread_radius: px(css_length_px(&s.spread).unwrap_or(0.0)),
5735                    inset: s.inset,
5736                });
5737            }
5738            r.box_shadow = Some(out);
5739        }
5740        TextShadow(shadows) => {
5741            if let Some(shadows) = text_shadows(shadows, diagnostics) {
5742                r.text.text_shadow = Some(shadows);
5743            }
5744        }
5745        FontFamily(families) => {
5746            x.web_font = waiting_web_font(families);
5747            if let Some(family) = first_available_family(families) {
5748                r.text.font_family = Some(gpui::SharedString::from(family));
5749            }
5750            if let Some((family, fallbacks)) = composed_font_stack(families) {
5751                r.text.font_family = Some(gpui::SharedString::from(family));
5752                r.text.font_fallbacks = Some(fallbacks);
5753            }
5754        }
5755        FontSize(v) => {
5756            use lightningcss::properties::font::{FontSize as FS, RelativeFontSize as R};
5757            let size = match v {
5758                FS::Length(DimensionPercentage::Percentage(p)) => Some(p.0 * em_basis()),
5759                FS::Length(DimensionPercentage::Calc(c)) => match calc_px(c, &lp_leaf_px) {
5760                    Some(p) => Some(p),
5761                    None => calc_linear(c).map(|(fraction, pixels)| fraction * em_basis() + pixels),
5762                },
5763                FS::Length(lp) => lp_absolute(lp).map(font_size_px),
5764                FS::Absolute(k) => Some(absolute_font_size_px(k)),
5765                FS::Relative(R::Smaller) => Some(em_basis() / 1.2),
5766                FS::Relative(R::Larger) => Some(em_basis() * 1.2),
5767            };
5768            if let Some(size) = size {
5769                r.text.font_size = Some(px(size.max(0.0)).into());
5770            }
5771        }
5772        FontWeight(w) => {
5773            let n = match w {
5774                CssFontWeight::Absolute(AbsoluteFontWeight::Weight(n)) => Some(*n),
5775                CssFontWeight::Absolute(AbsoluteFontWeight::Normal) => Some(400.0),
5776                CssFontWeight::Absolute(AbsoluteFontWeight::Bold) => Some(700.0),
5777                _ => None,
5778            };
5779            match n {
5780                Some(n) => r.text.font_weight = Some(gpui::FontWeight(n)),
5781                None => {
5782                    r.text.font_weight = Some(match w {
5783                        CssFontWeight::Bolder => gpui::FontWeight(700.0),
5784                        _ => gpui::FontWeight(100.0),
5785                    })
5786                }
5787            }
5788        }
5789        LineHeight(v) => {
5790            r.text.line_height = match v {
5791                // A number inherits as the number: gpui's fraction is taken of each element's own
5792                // font size at paint.
5793                CssLineHeight::Number(n) => Some(relative(*n)),
5794                CssLineHeight::Length(DimensionPercentage::Percentage(p)) => {
5795                    Some(px(p.0 * em_basis()).into())
5796                }
5797                CssLineHeight::Length(lp) => lp_definite(lp),
5798                CssLineHeight::Normal => Some(relative(1.2)),
5799            };
5800        }
5801        FontStyle(v) => {
5802            use lightningcss::properties::font::FontStyle as FS;
5803            r.text.font_style = Some(match v {
5804                FS::Normal => gpui::FontStyle::Normal,
5805                FS::Italic => gpui::FontStyle::Italic,
5806                FS::Oblique(_) => {
5807                    unsupported(diagnostics, "font-style: oblique <angle> (angle ignored)");
5808                    gpui::FontStyle::Oblique
5809                }
5810            });
5811        }
5812        TextAlign(v) => {
5813            use gpui::TextAlign as G;
5814            let mapped = match v {
5815                CssTextAlign::Left | CssTextAlign::Start => Some(G::Left),
5816                CssTextAlign::Center => Some(G::Center),
5817                CssTextAlign::Right | CssTextAlign::End => Some(G::Right),
5818                _ => None,
5819            };
5820            match mapped {
5821                Some(m) => r.text.text_align = Some(m),
5822                None => unsupported(diagnostics, "text-align"),
5823            }
5824        }
5825        WhiteSpace(v) => {
5826            use lightningcss::properties::text::WhiteSpace as WS;
5827            let mode = match v {
5828                WS::Normal => WhiteSpaceMode::Normal,
5829                WS::NoWrap => WhiteSpaceMode::Nowrap,
5830                WS::Pre => WhiteSpaceMode::Pre,
5831                WS::PreWrap => WhiteSpaceMode::PreWrap,
5832                WS::PreLine => WhiteSpaceMode::PreLine,
5833                WS::BreakSpaces => WhiteSpaceMode::BreakSpaces,
5834            };
5835            x.white_space = Some(mode);
5836            r.text.white_space = Some(match mode {
5837                // `break-spaces` differs from `pre-wrap` only inside a run of spaces, which gpui's
5838                // breaker does not expose.
5839                WhiteSpaceMode::Nowrap | WhiteSpaceMode::Pre => gpui::WhiteSpace::Nowrap,
5840                _ => gpui::WhiteSpace::Normal,
5841            });
5842        }
5843        TextOverflow(v, _) => {
5844            use lightningcss::properties::overflow::TextOverflow as TO;
5845            match v {
5846                TO::Ellipsis => {
5847                    r.text.text_overflow = Some(gpui::TextOverflow::Truncate("…".into()))
5848                }
5849                // A refinement cannot express "clear", so `text-clip` after an `text-ellipsis` is a
5850                // no-op rather than a reset.
5851                TO::Clip => unsupported(
5852                    diagnostics,
5853                    "text-overflow: clip — cannot undo an earlier ellipsis",
5854                ),
5855            }
5856        }
5857        TextDecorationLine(v, _) => {
5858            use lightningcss::properties::text::TextDecorationLine as TDL;
5859            if v.contains(TDL::Underline) {
5860                r.text.underline = Some(underline_line());
5861            }
5862            if v.contains(TDL::LineThrough) {
5863                r.text.strikethrough = Some(strike_line());
5864            }
5865            if v.intersects(TDL::Overline | TDL::Blink) {
5866                unsupported(diagnostics, "text-decoration-line: overline/blink");
5867            }
5868            if v.is_empty() {
5869                // `text-decoration-line: none` must undo an earlier line but a refinement cannot
5870                // clear a field, so it is a decoration that paints nothing: zero thickness AND
5871                // transparent, since gpui snaps a hairline up to a device pixel.
5872                r.text.underline = Some(gpui::UnderlineStyle {
5873                    thickness: px(0.0),
5874                    color: Some(gpui::transparent_black()),
5875                    wavy: false,
5876                    offset: px(0.0),
5877                });
5878                r.text.strikethrough = Some(gpui::StrikethroughStyle {
5879                    thickness: px(0.0),
5880                    color: Some(gpui::transparent_black()),
5881                });
5882            }
5883        }
5884        Cursor(c) => {
5885            use gpui::CursorStyle as C;
5886            use lightningcss::properties::ui::CursorKeyword as K;
5887            let mapped = match c.keyword {
5888                K::Pointer => C::PointingHand,
5889                K::Default | K::Auto => C::Arrow,
5890                K::Text => C::IBeam,
5891                K::VerticalText => C::IBeamCursorForVerticalLayout,
5892                K::Crosshair => C::Crosshair,
5893                K::Cell => C::Cell,
5894                K::Grab => C::OpenHand,
5895                K::Move => C::Move,
5896                K::AllScroll => C::AllScroll,
5897                K::Grabbing => C::ClosedHand,
5898                K::EResize => C::ResizeRight,
5899                K::WResize => C::ResizeLeft,
5900                K::NResize => C::ResizeUp,
5901                K::SResize => C::ResizeDown,
5902                K::EwResize => C::ResizeLeftRight,
5903                K::NsResize => C::ResizeUpDown,
5904                // Use the actual platform shapes; the GPUI enum's CSS doc comments accidentally
5905                // reverse these two diagonals.
5906                K::NwResize | K::SeResize | K::NwseResize => C::ResizeUpLeftDownRight,
5907                K::NeResize | K::SwResize | K::NeswResize => C::ResizeUpRightDownLeft,
5908                K::ColResize => C::ResizeColumn,
5909                K::RowResize => C::ResizeRow,
5910                K::NotAllowed => C::OperationNotAllowed,
5911                K::NoDrop => C::NoDrop,
5912                K::Alias => C::DragLink,
5913                K::Copy => C::DragCopy,
5914                K::ContextMenu => C::ContextualMenu,
5915                K::Help => C::Help,
5916                K::Progress => C::Progress,
5917                K::Wait => C::Wait,
5918                K::ZoomIn => C::ZoomIn,
5919                K::ZoomOut => C::ZoomOut,
5920                K::None => C::Hidden,
5921            };
5922            r.mouse_cursor = Some(mapped);
5923        }
5924        Filter(list, _) => apply_filter(list, x, diagnostics),
5925        BackdropFilter(list, _) => apply_backdrop_filter(list, r, diagnostics),
5926        Custom(c) => match &c.name {
5927            // `--shading` is the ONE custom property Skathi interprets: a GPU effect has no web
5928            // equivalent, so it needs a spelling a browser parses, stores and ignores rather than
5929            // one a browser DROPS.
5930            lightningcss::properties::custom::CustomPropertyName::Custom(name)
5931                if name.0.as_ref() == effect::SHADING =>
5932            {
5933                if let Some(spec) = effect::parse(&c.value, diagnostics) {
5934                    r.vn_effect = Some(spec);
5935                }
5936            }
5937            lightningcss::properties::custom::CustomPropertyName::Custom(name)
5938                if name.0.as_ref() == WINDOW_CONTROL =>
5939            {
5940                if let Some(c) = window_control(&c.value, diagnostics) {
5941                    x.window_control = Some(c);
5942                }
5943            }
5944            lightningcss::properties::custom::CustomPropertyName::Custom(_) => {}
5945            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5946                if name.0.as_ref() == "object-fit" =>
5947            {
5948                if let Some(fit) = object_fit(&c.value, diagnostics) {
5949                    x.object_fit = Some(fit);
5950                }
5951            }
5952            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5953                if name.0.as_ref() == "object-position" =>
5954            {
5955                if let Some(position) = object_position(p, diagnostics) {
5956                    r.vn_object_position = Some(position);
5957                }
5958            }
5959            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5960                if crate::corner_shape::is_property(name.0.as_ref()) =>
5961            {
5962                apply_corner_shape(name.0.as_ref(), p, r, x, diagnostics);
5963            }
5964            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5965                if matches!(
5966                    name.0.as_ref(),
5967                    "window-drag" | "app-region" | "-webkit-app-region"
5968                ) =>
5969            {
5970                if let Some(d) = window_drag(name.0.as_ref(), &c.value, diagnostics) {
5971                    x.window_drag = Some(d);
5972                }
5973            }
5974            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5975                if name.0.as_ref() == "pointer-events" =>
5976            {
5977                match single_ident(&c.value, "pointer-events", diagnostics) {
5978                    Some("none") => x.pointer_events_none = Some(true),
5979                    Some("auto") => x.pointer_events_none = Some(false),
5980                    other => once(
5981                        diagnostics,
5982                        format!(
5983                            "unsupported value for pointer-events: {} — only `none` and `auto` \
5984                             are modelled (SVG-only values have nothing to apply to)",
5985                            other.unwrap_or("<not a keyword>")
5986                        ),
5987                    ),
5988                }
5989            }
5990            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
5991                if name.0.as_ref() == "content" =>
5992            {
5993                match content_string(&c.value) {
5994                    ContentValue::Text(t) => {
5995                        x.content = Some(t);
5996                        x.content_none = false;
5997                    }
5998                    ContentValue::None => {
5999                        x.content = None;
6000                        x.content_none = true;
6001                    }
6002                    ContentValue::Unsupported(what) => once(
6003                        diagnostics,
6004                        format!(
6005                            "`content: {what}` does not generate a box (v1) — only a literal \
6006                             string does. Counters, `attr()`, `url()` and the `open-quote` \
6007                             family have no model here; render the value as a real element"
6008                        ),
6009                    ),
6010                }
6011            }
6012            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6013                if name.0.as_ref() == "outline-offset" =>
6014            {
6015                match single_length_px(&c.value) {
6016                    Some(v) => {
6017                        outline_mut(r).offset = px(v);
6018                        x.outline.offset = Some(v);
6019                    }
6020                    None => unsupported(diagnostics, "outline-offset (a <length> is expected)"),
6021                }
6022            }
6023            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6024                if name.0.as_ref() == "-webkit-line-clamp" || name.0.as_ref() == "line-clamp" =>
6025            {
6026                match single_number(&c.value) {
6027                    Some(n) if n >= 1.0 => r.text.line_clamp = Some(n as usize),
6028                    _ => unsupported(
6029                        diagnostics,
6030                        "line-clamp: none — cannot undo an earlier clamp",
6031                    ),
6032                }
6033            }
6034            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6035                if name
6036                    .0
6037                    .as_ref()
6038                    .eq_ignore_ascii_case("-webkit-text-fill-color") =>
6039            {
6040                use lightningcss::properties::custom::{Token, TokenOrValue};
6041                let mut tokens = c
6042                    .value
6043                    .0
6044                    .iter()
6045                    .filter(|t| !matches!(t, TokenOrValue::Token(Token::WhiteSpace(_))));
6046                let fill = match (tokens.next(), tokens.next()) {
6047                    (Some(TokenOrValue::Color(cc)), None) => color(cc).map(TextFill::Color),
6048                    (Some(TokenOrValue::Token(Token::Ident(id))), None)
6049                        if id.as_ref().eq_ignore_ascii_case("currentcolor") =>
6050                    {
6051                        Some(TextFill::CurrentColor)
6052                    }
6053                    (Some(TokenOrValue::Token(Token::Ident(id))), None) => {
6054                        named_color(id.as_ref()).map(TextFill::Color)
6055                    }
6056                    _ => None,
6057                };
6058                match fill {
6059                    Some(f) => x.text_fill_color = Some(f),
6060                    None if is_css_wide_keyword(&c.value) => {}
6061                    None => unsupported(
6062                        diagnostics,
6063                        "-webkit-text-fill-color (a <color> is expected)",
6064                    ),
6065                }
6066            }
6067            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6068                if name.0.as_ref() == "text-underline-offset" =>
6069            {
6070                if single_ident_is(&c.value, "auto") || is_css_wide_keyword(&c.value) {
6071                } else if let Some(offset) = single_length_px(&c.value) {
6072                    x.underline_offset = Some(offset);
6073                    if let Some(u) = r.text.underline.as_mut() {
6074                        u.offset = px(offset);
6075                    }
6076                } else {
6077                    unsupported(
6078                        diagnostics,
6079                        "text-underline-offset (a <length> is expected)",
6080                    );
6081                }
6082            }
6083            // `text-decoration-skip-ink` decides whether an underline BREAKS around descenders.
6084            // gpui draws one unbroken rule, and the property has no other effect.
6085            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6086                if name.0.as_ref() == "text-decoration-skip-ink" =>
6087            {
6088                if !single_ident_is(&c.value, "none") && !is_css_wide_keyword(&c.value) {
6089                    warn_once(
6090                        diagnostics,
6091                        "`text-decoration-skip-ink: auto` is not applied (v1) — gpui draws one \
6092                         unbroken underline and does not lift it around descenders. `none` (draw \
6093                         it straight through) is what it already does",
6094                    );
6095                }
6096            }
6097            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6098                if matches!(
6099                    name.0.as_ref(),
6100                    "font-feature-settings"
6101                        | "font-variant-numeric"
6102                        | "font-variant-ligatures"
6103                        | "font-kerning"
6104                ) =>
6105            {
6106                match font_features(&c.value, name.0.as_ref()) {
6107                    Some(features) if features.0.is_empty() => {}
6108                    Some(features) => {
6109                        let mut pairs = r
6110                            .text
6111                            .font_features
6112                            .take()
6113                            .map(|f| (*f.0).clone())
6114                            .unwrap_or_default();
6115                        for (tag, v) in features.0.iter() {
6116                            match pairs.iter_mut().find(|(t, _)| t == tag) {
6117                                Some(slot) => slot.1 = *v,
6118                                None => pairs.push((tag.clone(), *v)),
6119                            }
6120                        }
6121                        r.text.font_features = Some(gpui::FontFeatures(std::sync::Arc::new(pairs)));
6122                    }
6123                    None => warn_once(
6124                        diagnostics,
6125                        "an OpenType FEATURE value was not understood (v1) — \
6126                         `font-feature-settings` takes `\"tag\" <number|on|off>` pairs, \
6127                         `font-variant-numeric` / `font-variant-ligatures` their keyword sets and \
6128                         `font-kerning` `auto | normal | none`; all reach the shaper when they \
6129                         parse",
6130                    ),
6131                }
6132            }
6133            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6134                if name.0.as_ref() == "font-optical-sizing" =>
6135            {
6136                if !single_ident_is(&c.value, "auto") && !is_css_wide_keyword(&c.value) {
6137                    warn_once(
6138                        diagnostics,
6139                        "`font-optical-sizing: none` is not applied (v1) — a variable font's \
6140                         `opsz` axis is driven from the font size here, which is what `auto` (the \
6141                         initial value, and what every browser does) asks for. There is no way to \
6142                         switch it off",
6143                    );
6144                }
6145            }
6146            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6147                if name.0.as_ref() == "font-variation-settings" =>
6148            {
6149                if single_ident_is(&c.value, "normal") || is_css_wide_keyword(&c.value) {
6150                    return;
6151                }
6152                warn_once(
6153                    diagnostics,
6154                    "`font-variation-settings` is not applied (v1) — a face is selected through \
6155                     the weight/width/slope model, not by axis value, so an arbitrary axis \
6156                     (`wdth`, `slnt`, a custom one) cannot be instantiated. `font-weight` and \
6157                     `font-style` do reach the axis the WWS model covers, and `opsz` is driven \
6158                     from the font size",
6159                )
6160            }
6161            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6162                if matches!(name.0.as_ref(), "touch-action" | "will-change") => {}
6163            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6164                if name.0.as_ref() == "scroll-behavior" =>
6165            {
6166                match single_ident(&c.value, "scroll-behavior", diagnostics) {
6167                    Some("auto") => x.scroll_smooth = Some(false),
6168                    Some("smooth") => x.scroll_smooth = Some(true),
6169                    _ => unsupported(diagnostics, "scroll-behavior"),
6170                }
6171            }
6172            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6173                if matches!(
6174                    name.0.as_ref(),
6175                    "scroll-snap-type" | "scroll-snap-align" | "scroll-snap-stop"
6176                ) =>
6177            {
6178                crate::snap::apply_keywords(name.0.as_ref(), &c.value, &mut x.snap, diagnostics);
6179            }
6180            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6181                if matches!(name.0.as_ref(), "interpolate-size" | "dynamic-range-limit") =>
6182            {
6183                let value = value_text(p).unwrap_or_default();
6184                let keyword = value.trim().to_ascii_lowercase();
6185                let inherited = matches!(
6186                    keyword.as_str(),
6187                    "inherit" | "unset" | "revert" | "revert-layer"
6188                );
6189                if name.0.as_ref() == "interpolate-size" {
6190                    match keyword.as_str() {
6191                        _ if inherited => {}
6192                        "allow-keywords" => x.interpolate_size = Some(true),
6193                        "numeric-only" | "initial" => x.interpolate_size = Some(false),
6194                        _ => unsupported(
6195                            diagnostics,
6196                            "interpolate-size (`numeric-only` or `allow-keywords`)",
6197                        ),
6198                    }
6199                } else if !inherited {
6200                    let parsed = if keyword == "initial" {
6201                        Ok(crate::DynamicRangeLimit::NO_LIMIT)
6202                    } else {
6203                        crate::DynamicRangeLimit::parse(&value)
6204                    };
6205                    match parsed {
6206                        Ok(limit) => x.dynamic_range_limit = Some(limit),
6207                        Err(why) => once(
6208                            diagnostics,
6209                            format!("`dynamic-range-limit` was dropped: {why}"),
6210                        ),
6211                    }
6212                }
6213            }
6214            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6215                if name.0.as_ref() == "contain" =>
6216            {
6217                if let Some((paint, size)) = contain(&c.value, diagnostics) {
6218                    x.contain_paint = Some(paint);
6219                    x.contain_size = Some(size);
6220                }
6221            }
6222            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6223                if name.0.as_ref() == "scrollbar-width" =>
6224            {
6225                if let Some(w) = scrollbar_width(&c.value, diagnostics) {
6226                    x.scrollbar_width = Some(w);
6227                }
6228            }
6229            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6230                if name.0.as_ref() == "scrollbar-color" =>
6231            {
6232                if let Some(pair) = scrollbar_color(&c.value, diagnostics) {
6233                    x.scrollbar_color = Some(pair);
6234                }
6235            }
6236            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6237                if matches!(
6238                    name.0.as_ref(),
6239                    "overscroll-behavior"
6240                        | "overscroll-behavior-x"
6241                        | "overscroll-behavior-y"
6242                        | "overscroll-behavior-inline"
6243                        | "overscroll-behavior-block"
6244                ) =>
6245            {
6246                let property = name.0.as_ref();
6247                if let Some(b) = overscroll(property, &c.value, diagnostics) {
6248                    match property {
6249                        "overscroll-behavior-x" | "overscroll-behavior-inline" => {
6250                            x.overscroll_x = Some(b)
6251                        }
6252                        "overscroll-behavior-y" | "overscroll-behavior-block" => {
6253                            x.overscroll_y = Some(b)
6254                        }
6255                        _ => {
6256                            x.overscroll_x = Some(b);
6257                            x.overscroll_y = Some(b);
6258                        }
6259                    }
6260                }
6261            }
6262            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6263                if name.0.as_ref() == "isolation" =>
6264            {
6265                if single_ident_is(&c.value, "isolate") {
6266                    x.isolate = Some(true);
6267                } else if single_ident_is(&c.value, "auto") {
6268                    x.isolate = Some(false);
6269                } else if !is_css_wide_keyword(&c.value) {
6270                    unsupported(diagnostics, "isolation (expected `auto` or `isolate`)");
6271                }
6272            }
6273            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6274                if matches!(
6275                    name.0.as_ref(),
6276                    "border-collapse"
6277                        | "border-spacing"
6278                        | "caption-side"
6279                        | "table-layout"
6280                        | "empty-cells"
6281                ) =>
6282            {
6283                warn_once(
6284                    diagnostics,
6285                    "the table properties are not applied (v1) — `<table>` and friends lay out as \
6286                     plain blocks; build tables out of flex rows or a grid track list, which both \
6287                     render",
6288                )
6289            }
6290            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6291                if name.0.as_ref() == "clip" =>
6292            {
6293                // A non-degenerate rect would need a per-element content mask in the paint path.
6294                if clip_rect_is_empty(&c.value) {
6295                    r.visibility = Some(gpui::Visibility::Hidden);
6296                } else {
6297                    warn_once(
6298                        diagnostics,
6299                        "a non-empty legacy `clip: rect()` is not applied (v1) — it is deprecated \
6300                         in CSS too, and clipping a box to an arbitrary sub-rectangle needs a \
6301                         content mask the paint path does not carry. `clip: rect(0,0,0,0)` (the \
6302                         visually-hidden idiom) IS honoured, and `overflow: hidden` on a sized \
6303                         box clips for real",
6304                    );
6305                }
6306            }
6307            // lightningcss has a `-webkit-mask-composite` property, but its name lookup strips the
6308            // prefix first, finds the unprefixed `mask-composite` (which takes no prefix), and
6309            // gives up.
6310            lightningcss::properties::custom::CustomPropertyName::Unknown(name)
6311                if name
6312                    .0
6313                    .as_ref()
6314                    .eq_ignore_ascii_case("-webkit-mask-composite") =>
6315            {
6316                use lightningcss::properties::custom::{Token, TokenOrValue};
6317                let first = c.value.0.iter().find_map(|t| match t {
6318                    TokenOrValue::Token(Token::Ident(id)) => Some(id.as_ref()),
6319                    _ => None,
6320                });
6321                x.mask_composite = Some(webkit_mask_compositing(first.unwrap_or("source-over")));
6322                advise_mask(x, diagnostics);
6323            }
6324            lightningcss::properties::custom::CustomPropertyName::Unknown(name) => {
6325                once(
6326                    diagnostics,
6327                    format!("property not mapped (v1): {}", name.0.as_ref()),
6328                );
6329            }
6330        },
6331        LetterSpacing(v) => {
6332            if let Some(px) = spacing_px(v) {
6333                r.text.letter_spacing = Some(gpui::px(px));
6334            }
6335        }
6336        WordSpacing(v) => {
6337            if let Some(px) = spacing_px(v) {
6338                r.text.word_spacing = Some(gpui::px(px));
6339            }
6340        }
6341        VerticalAlign(v) => {
6342            use lightningcss::properties::font::VerticalAlign as VA;
6343            use lightningcss::properties::font::VerticalAlignKeyword as VK;
6344            // `vertical-align` applies only to inline-level boxes and table cells, so it is inert
6345            // on a block; Tailwind's preflight pairs `display: block` with `vertical-align: middle`
6346            // on that basis.
6347            let block_level = matches!(
6348                r.display,
6349                Some(gpui::Display::Block | gpui::Display::Flex | gpui::Display::Grid)
6350            ) && x.inline_level != Some(true);
6351            if !matches!(v, VA::Keyword(VK::Baseline)) && !block_level {
6352                warn_once(
6353                    diagnostics,
6354                    "`vertical-align` is not applied (v1) — it aligns boxes inside a LINE box, \
6355                     and taffy has no inline formatting context. `align-items` / `align-self` on \
6356                     the flex parent is the equivalent that works",
6357                );
6358            }
6359        }
6360        TextIndent(v) => {
6361            if lp_definite(&v.value).is_none_or(|l| l != gpui::px(0.0).into()) {
6362                warn_once(
6363                    diagnostics,
6364                    "`text-indent` is not applied (v1) — there is no first-line concept in the                      shaper. `padding-left` indents the whole block",
6365                );
6366            }
6367        }
6368        ListStyle(v) => {
6369            use lightningcss::properties::list::ListStylePosition as P;
6370            match list_marker(&v.list_style_type) {
6371                Some(marker) => x.list_marker = Some(marker),
6372                None => advise_list_marker(diagnostics),
6373            }
6374            x.list_marker_inside = Some(matches!(v.position, P::Inside));
6375        }
6376        ListStyleType(v) => match list_marker(v) {
6377            Some(marker) => x.list_marker = Some(marker),
6378            None => advise_list_marker(diagnostics),
6379        },
6380        // A marker IMAGE would be a raster in the marker box, which is the one shape of marker
6381        // there is no box to put.
6382        ListStyleImage(v) => {
6383            if !matches!(v, lightningcss::values::image::Image::None) {
6384                advise_list_marker(diagnostics);
6385            }
6386        }
6387        ListStylePosition(v) => {
6388            use lightningcss::properties::list::ListStylePosition as P;
6389            x.list_marker_inside = Some(matches!(v, P::Inside));
6390        }
6391        Resize(v) => {
6392            use lightningcss::properties::ui::Resize as R;
6393            // `resize: none` is the initial value and already true of every box here; the others
6394            // ask for a UA drag affordance that gpui has no equivalent of.
6395            if !matches!(v, R::None) {
6396                warn_once(
6397                    diagnostics,
6398                    "`resize` is not applied (v1) — there is no user-resize affordance on a gpui                      box. A drag handle has to be a real element with a pointer handler",
6399                );
6400            }
6401        }
6402        UserSelect(v, _) => {
6403            use crate::mapper::UserSelect as S;
6404            use lightningcss::properties::ui::UserSelect as U;
6405            x.user_select = Some(match v {
6406                U::Auto => S::Auto,
6407                U::None => S::None,
6408                U::Text => S::Text,
6409                U::All => S::All,
6410                U::Contain => {
6411                    warn_once(
6412                        diagnostics,
6413                        "`user-select: contain` selects like `text` here: a selection that starts \
6414                         inside the element is not kept inside it",
6415                    );
6416                    S::Text
6417                }
6418            });
6419        }
6420        AccentColor(c) => {
6421            use lightningcss::properties::ui::ColorOrAuto;
6422            x.accent_color = Some(match c {
6423                ColorOrAuto::Auto => None,
6424                ColorOrAuto::Color(c) => color(c),
6425            });
6426        }
6427        Appearance(a, _) => {
6428            x.appearance_none = Some(matches!(a, lightningcss::properties::ui::Appearance::None))
6429        }
6430        // Whitespace is always collapsed here, so a tab is one space and `tab-size` could not
6431        // change the result.
6432        TabSize(..) => {}
6433        // `text-size-adjust` exists to stop MOBILE BROWSERS inflating text.
6434        TextSizeAdjust(..) => {}
6435        // The screen-reader-only idiom, `inset(50%)`, encloses nothing and so paints nothing, while
6436        // the layout box and the CSS `visibility` stay.
6437        ClipPath(v, _) => {
6438            if let Some(clip) = clip_path(v, diagnostics) {
6439                r.vn_clip_path = Some(clip);
6440            }
6441        }
6442        WordWrap(v) | OverflowWrap(v) => {
6443            use lightningcss::properties::text::OverflowWrap as OW;
6444            r.text.overflow_wrap = Some(match v {
6445                OW::Normal => gpui::OverflowWrap::Normal,
6446                OW::BreakWord => gpui::OverflowWrap::BreakWord,
6447                OW::Anywhere => gpui::OverflowWrap::Anywhere,
6448            });
6449        }
6450        WordBreak(v) => {
6451            use lightningcss::properties::text::WordBreak as WB;
6452            r.text.word_break = Some(match v {
6453                WB::Normal => gpui::WordBreak::Normal,
6454                WB::BreakAll => gpui::WordBreak::BreakAll,
6455                WB::KeepAll => gpui::WordBreak::KeepAll,
6456                WB::BreakWord => gpui::WordBreak::BreakWord,
6457            });
6458        }
6459        Hyphens(v, _) => {
6460            use lightningcss::properties::text::Hyphens as H;
6461            r.text.hyphens = Some(match v {
6462                H::None => gpui::Hyphens::None,
6463                H::Manual => gpui::Hyphens::Manual,
6464                H::Auto => {
6465                    warn_once(
6466                        diagnostics,
6467                        "`hyphens: auto` hyphenates only at soft hyphens (`&shy;`), as `manual` \
6468                         does (v1) — there is no hyphenation dictionary",
6469                    );
6470                    gpui::Hyphens::Manual
6471                }
6472            });
6473        }
6474        ScrollMarginTop(_)
6475        | ScrollMarginBottom(_)
6476        | ScrollMarginLeft(_)
6477        | ScrollMarginRight(_)
6478        | ScrollMargin(_)
6479        | ScrollMarginBlock(_)
6480        | ScrollMarginInline(_)
6481        | ScrollMarginBlockStart(_)
6482        | ScrollMarginBlockEnd(_)
6483        | ScrollMarginInlineStart(_)
6484        | ScrollMarginInlineEnd(_)
6485        | ScrollPaddingTop(_)
6486        | ScrollPaddingBottom(_)
6487        | ScrollPaddingLeft(_)
6488        | ScrollPaddingRight(_)
6489        | ScrollPadding(_)
6490        | ScrollPaddingBlock(_)
6491        | ScrollPaddingInline(_)
6492        | ScrollPaddingBlockStart(_)
6493        | ScrollPaddingBlockEnd(_)
6494        | ScrollPaddingInlineStart(_)
6495        | ScrollPaddingInlineEnd(_) => {
6496            crate::snap::apply_box(p, &mut x.snap, diagnostics);
6497        }
6498        TextTransform(t) => {
6499            use crate::mapper::TextTransform as TT;
6500            use lightningcss::properties::text::TextTransformCase as C;
6501            x.text_transform = Some(match t.case {
6502                C::None => TT::None,
6503                C::Uppercase => TT::Uppercase,
6504                C::Lowercase => TT::Lowercase,
6505                C::Capitalize => TT::Capitalize,
6506            });
6507        }
6508        // Reaching here means the value stayed unparsed after substitution (unbalanced `var(` or an
6509        // invalid token stream): a defensive advisory.
6510        Unparsed(u) => {
6511            if !apply_unparsed(u, r, x, diagnostics) {
6512                once(
6513                    diagnostics,
6514                    format!(
6515                        "`{}` value is still unresolved after var()/env() substitution (v1)",
6516                        u.property_id.name()
6517                    ),
6518                );
6519            }
6520        }
6521        Property::ViewTransitionName(name) => {
6522            use lightningcss::properties::transition::ViewTransitionName as N;
6523            x.view_transition_name = Some(match name {
6524                N::None => None,
6525                N::Auto => Some("auto".into()),
6526                N::Custom(ident) => Some(ident.0.as_ref().into()),
6527            });
6528        }
6529        Property::ViewTransitionClass(list) => {
6530            use lightningcss::values::ident::NoneOrCustomIdentList as L;
6531            x.view_transition_class = Some(match list {
6532                L::None => Rc::from([]),
6533                L::Idents(idents) => idents.iter().map(|i| Rc::from(i.0.as_ref())).collect(),
6534            });
6535        }
6536        Property::MixBlendMode(mode) => {
6537            use lightningcss::properties::effects::BlendMode;
6538            match mode {
6539                BlendMode::Normal => x.plus_lighter = Some(false),
6540                BlendMode::PlusLighter => x.plus_lighter = Some(true),
6541                _ => unsupported(
6542                    diagnostics,
6543                    "mix-blend-mode (only `normal`, and `plus-lighter` on view transition images)",
6544                ),
6545            }
6546        }
6547        other => {
6548            once(
6549                diagnostics,
6550                format!("property not mapped (v1): {}", prop_name(other)),
6551            );
6552        }
6553    }
6554}
6555
6556/// A sizing property set to a `calc-size()`; `None` when it is not one.
6557fn apply_calc_size(
6558    u: &lightningcss::properties::custom::UnparsedProperty,
6559    r: &mut StyleRefinement,
6560    diagnostics: &mut Vec<String>,
6561) -> Option<bool> {
6562    use lightningcss::properties::custom::TokenOrValue;
6563    let slot = match u.property_id {
6564        PropertyId::Width | PropertyId::InlineSize => &mut r.size.width,
6565        PropertyId::Height | PropertyId::BlockSize => &mut r.size.height,
6566        PropertyId::MinWidth | PropertyId::MinInlineSize => &mut r.min_size.width,
6567        PropertyId::MinHeight | PropertyId::MinBlockSize => &mut r.min_size.height,
6568        PropertyId::MaxWidth | PropertyId::MaxInlineSize => &mut r.max_size.width,
6569        PropertyId::MaxHeight | PropertyId::MaxBlockSize => &mut r.max_size.height,
6570        PropertyId::FlexBasis(_) => &mut r.flex_basis,
6571        _ => return None,
6572    };
6573    let calls_it = u.value.0.iter().any(
6574        |t| matches!(t, TokenOrValue::Function(f) if f.name.0.eq_ignore_ascii_case("calc-size")),
6575    );
6576    if !calls_it {
6577        return None;
6578    }
6579    let name = u.property_id.name();
6580    let text = value_text(&Property::Unparsed(u.clone()))?;
6581    let max = name.starts_with("max-");
6582    match crate::calc_size::parse(&text, max, name == "flex-basis") {
6583        Ok(length) => *slot = Some(length),
6584        Err(why) => once(diagnostics, format!("`{name}: {text}` was dropped: {why}")),
6585    }
6586    Some(true)
6587}
6588
6589/// A value lightningcss left as tokens without a substitution in it; false when it is not one the
6590/// mapper knows, which is to say invalid.
6591fn apply_unparsed(
6592    u: &lightningcss::properties::custom::UnparsedProperty,
6593    r: &mut StyleRefinement,
6594    x: &mut Extras,
6595    diagnostics: &mut Vec<String>,
6596) -> bool {
6597    if let Some(done) = apply_calc_size(u, r, diagnostics) {
6598        return done;
6599    }
6600    let reset = initial_inset_sides(u.property_id.name(), &u.value);
6601    if reset != 0 {
6602        if reset & 0b0001 != 0 {
6603            r.inset.top = Some(Length::Auto);
6604        }
6605        if reset & 0b0010 != 0 {
6606            r.inset.right = Some(Length::Auto);
6607        }
6608        if reset & 0b0100 != 0 {
6609            r.inset.bottom = Some(Length::Auto);
6610        }
6611        if reset & 0b1000 != 0 {
6612            r.inset.left = Some(Length::Auto);
6613        }
6614        return true;
6615    }
6616    // lightningcss has no typed `none` for a list property, so `box-shadow: none`
6617    // (Tailwind's `shadow-none`) always lands here; it means an empty list, which lets it
6618    // cancel an earlier shadow.
6619    if matches!(u.property_id, PropertyId::BoxShadow(_))
6620        && matches!(single_ident_raw(&u.value), Some("none"))
6621    {
6622        r.box_shadow = Some(Vec::new());
6623        return true;
6624    }
6625    if matches!(u.property_id, PropertyId::TextShadow)
6626        && matches!(single_ident_raw(&u.value), Some("none" | "initial"))
6627    {
6628        r.text.text_shadow = Some(Vec::new());
6629        return true;
6630    }
6631    // `x: inherit` parses as Unparsed for every property but `all`; not writing the field
6632    // is "take the parent's value", so it is honoured by ignoring it. `border-radius` is
6633    // the exception (it does not inherit): it is recorded and filled after the cascade
6634    // (`RadiusInherit`).
6635    if matches!(u.property_id, PropertyId::ClipPath(_)) && !has_substitution(&u.value) {
6636        use lightningcss::properties::custom::{Token, TokenOrValue};
6637        match clip_path_path(&u.value) {
6638            Some(Ok(clip)) => {
6639                r.vn_clip_path = Some(clip);
6640                return true;
6641            }
6642            Some(Err(why)) => {
6643                once(
6644                    diagnostics,
6645                    format!(
6646                        "`clip-path: path()` was dropped as invalid, as Chromium drops it: {why}"
6647                    ),
6648                );
6649                return true;
6650            }
6651            None => {}
6652        }
6653        let what = u.value.0.iter().find_map(|t| match t {
6654            TokenOrValue::Function(f) => Some(format!("{}()", f.name.0.as_ref())),
6655            TokenOrValue::Token(Token::Function(name)) => Some(format!("{}()", name.as_ref())),
6656            _ => None,
6657        });
6658        clip_path_unsupported(diagnostics, what.as_deref().unwrap_or("this value"));
6659        return true;
6660    }
6661    if matches!(single_ident_raw(&u.value), Some("inherit")) {
6662        let corners = match u.property_id {
6663            PropertyId::BorderRadius(_) => RadiusInherit::ALL,
6664            PropertyId::BorderTopLeftRadius(_) => RadiusInherit::TOP_LEFT,
6665            PropertyId::BorderTopRightRadius(_) => RadiusInherit::TOP_RIGHT,
6666            PropertyId::BorderBottomRightRadius(_) => RadiusInherit::BOTTOM_RIGHT,
6667            PropertyId::BorderBottomLeftRadius(_) => RadiusInherit::BOTTOM_LEFT,
6668            _ => 0,
6669        };
6670        x.radius_inherit.write(corners, true);
6671        return true;
6672    }
6673    false
6674}
6675
6676fn apply_corner_shape(
6677    name: &str,
6678    p: &Property,
6679    r: &mut StyleRefinement,
6680    x: &mut Extras,
6681    diagnostics: &mut Vec<String>,
6682) {
6683    use crate::corner_shape::{inherit_bit, parse, Declared};
6684    match parse(name, &value_text(p).unwrap_or_default()) {
6685        Ok(Declared::Inherit(bits)) => x.radius_inherit.write(bits, true),
6686        Ok(Declared::Shapes(shapes)) => {
6687            let s = &mut r.vn_corner_shapes;
6688            let slots = [
6689                &mut s.top_left,
6690                &mut s.top_right,
6691                &mut s.bottom_right,
6692                &mut s.bottom_left,
6693            ];
6694            for (i, (slot, shape)) in slots.into_iter().zip(shapes).enumerate() {
6695                if let Some(shape) = shape {
6696                    *slot = Some(shape);
6697                    x.radius_inherit.write(inherit_bit(i), false);
6698                }
6699            }
6700        }
6701        Err(why) => once(diagnostics, format!("`{name}` was dropped: {why}")),
6702    }
6703}
6704
6705fn presentation_name(p: &Property) -> Option<&'static str> {
6706    use Property::*;
6707    Some(match p {
6708        FillOpacity(_) => "fill-opacity",
6709        FillRule(_) => "fill-rule",
6710        StrokeOpacity(_) => "stroke-opacity",
6711        StrokeWidth(_) => "stroke-width",
6712        StrokeLinecap(_) => "stroke-linecap",
6713        StrokeLinejoin(_) => "stroke-linejoin",
6714        StrokeMiterlimit(_) => "stroke-miterlimit",
6715        StrokeDasharray(_) => "stroke-dasharray",
6716        StrokeDashoffset(_) => "stroke-dashoffset",
6717        ShapeRendering(_) => "shape-rendering",
6718        _ => return None,
6719    })
6720}
6721
6722/// CSS keywords are case-insensitive and lightningcss prints them lowercase; an attribute's are
6723/// not, and resvg ignores `shape-rendering="crispedges"` (the line is anti-aliased again).
6724fn presentation_value(name: &str, value: String) -> String {
6725    if name != "shape-rendering" {
6726        return value;
6727    }
6728    match value.to_ascii_lowercase().as_str() {
6729        "optimizespeed" => "optimizeSpeed".into(),
6730        "crispedges" => "crispEdges".into(),
6731        "geometricprecision" => "geometricPrecision".into(),
6732        _ => value,
6733    }
6734}
6735
6736fn set_presentation(list: &mut Vec<(&'static str, Rc<str>)>, name: &'static str, value: Rc<str>) {
6737    match list.iter_mut().find(|(n, _)| *n == name) {
6738        Some(slot) => slot.1 = value,
6739        None => list.push((name, value)),
6740    }
6741}
6742
6743fn svg_paint(
6744    p: &lightningcss::properties::svg::SVGPaint<'_>,
6745    what: &str,
6746    diagnostics: &mut Vec<String>,
6747) -> SvgPaint {
6748    use lightningcss::properties::svg::SVGPaint as P;
6749    match p {
6750        P::None => SvgPaint::None,
6751        P::Color(c) if is_current_color(c) => SvgPaint::Current,
6752        P::Color(c) => match color(c) {
6753            Some(c) => SvgPaint::Color(c),
6754            None => {
6755                unresolved_color(diagnostics, what);
6756                SvgPaint::Server
6757            }
6758        },
6759        // `context-fill`/`context-stroke` only mean anything inside a `<use>` of a marker; treated
6760        // as "painted", which is what they degrade to.
6761        P::Url { .. } | P::ContextFill | P::ContextStroke => SvgPaint::Server,
6762    }
6763}
6764
6765fn is_current_color(c: &lightningcss::values::color::CssColor) -> bool {
6766    matches!(c, lightningcss::values::color::CssColor::CurrentColor)
6767}
6768
6769fn apply_transform(
6770    list: &lightningcss::properties::transform::TransformList,
6771    r: &mut StyleRefinement,
6772    diagnostics: &mut Vec<String>,
6773) {
6774    use lightningcss::properties::transform::Transform as T;
6775    use lightningcss::values::percentage::NumberOrPercentage;
6776    const UNIT: [[f64; 2]; 2] = [[1.0, 0.0], [0.0, 1.0]];
6777    const ZERO: [[f64; 3]; 2] = [[0.0; 3]; 2];
6778    fn len(v: &LengthPercentage, axis: usize) -> Option<[f64; 3]> {
6779        match v {
6780            DimensionPercentage::Dimension(l) => {
6781                length_value_px(l).map(|p| [f64::from(p), 0.0, 0.0])
6782            }
6783            DimensionPercentage::Percentage(p) => {
6784                let mut row = [0.0; 3];
6785                row[axis + 1] = f64::from(p.0);
6786                Some(row)
6787            }
6788            DimensionPercentage::Calc(_) => {
6789                calc_dropped();
6790                None
6791            }
6792        }
6793    }
6794    fn factor(v: &NumberOrPercentage) -> f64 {
6795        f64::from(match v {
6796            NumberOrPercentage::Number(n) => *n,
6797            NumberOrPercentage::Percentage(p) => p.0,
6798        })
6799    }
6800    fn append(
6801        linear: &mut [[f64; 2]; 2],
6802        offset: &mut [[f64; 3]; 2],
6803        m: [[f64; 2]; 2],
6804        t: [[f64; 3]; 2],
6805    ) {
6806        let old = *linear;
6807        for row in 0..2 {
6808            for term in 0..3 {
6809                offset[row][term] += old[row][0] * t[0][term] + old[row][1] * t[1][term];
6810            }
6811            for column in 0..2 {
6812                linear[row][column] = old[row][0] * m[0][column] + old[row][1] * m[1][column];
6813            }
6814        }
6815    }
6816    fn slot(row: [f32; 3], axis: usize) -> Option<TransformLength> {
6817        let own = row[axis + 1];
6818        let cross = row[2 - axis];
6819        if cross != 0.0 || (row[0] != 0.0 && own != 0.0) {
6820            None
6821        } else if own != 0.0 {
6822            Some(TransformLength::Fraction(own))
6823        } else {
6824            Some(TransformLength::Pixels(row[0]))
6825        }
6826    }
6827    let mut linear = UNIT;
6828    let mut offset = ZERO;
6829    let mut authored_rotate = 0.0f64;
6830    let mut authored_scale = (1.0f64, 1.0f64);
6831    let mut affine = false;
6832    let mut dropped: Vec<&str> = Vec::new();
6833    for transform in &list.0 {
6834        let mut m = UNIT;
6835        let mut t = ZERO;
6836        match transform {
6837            T::Translate(a, b) | T::Translate3d(a, b, _) => {
6838                let (Some(x), Some(y)) = (len(a, 0), len(b, 1)) else {
6839                    dropped.push("translate() with a calc() length");
6840                    continue;
6841                };
6842                t = [x, y];
6843                if let T::Translate3d(_, _, z) = transform {
6844                    if !matches!(css_length_px(z), Some(0.0)) {
6845                        dropped.push("the Z axis of a 3D translate");
6846                    }
6847                }
6848            }
6849            T::TranslateX(v) => {
6850                let Some(value) = len(v, 0) else {
6851                    dropped.push("translateX() with a calc() length");
6852                    continue;
6853                };
6854                t[0] = value;
6855            }
6856            T::TranslateY(v) => {
6857                let Some(value) = len(v, 1) else {
6858                    dropped.push("translateY() with a calc() length");
6859                    continue;
6860                };
6861                t[1] = value;
6862            }
6863            T::Rotate(a) | T::RotateZ(a) => {
6864                let angle = f64::from(a.to_radians());
6865                let (sin, cos) = angle.sin_cos();
6866                m = [[cos, -sin], [sin, cos]];
6867                authored_rotate += angle;
6868            }
6869            T::RotateX(a) | T::RotateY(a) if a.to_degrees() == 0.0 => {}
6870            T::RotateX(_) | T::RotateY(_) | T::Rotate3d(..) => {
6871                dropped.push("rotate3d()/rotateX()/rotateY()");
6872                continue;
6873            }
6874            T::Scale(a, b) | T::Scale3d(a, b, _) => {
6875                let (x, y) = (factor(a), factor(b));
6876                m = [[x, 0.0], [0.0, y]];
6877                authored_scale = (authored_scale.0 * x, authored_scale.1 * y);
6878            }
6879            T::ScaleX(value) => {
6880                let x = factor(value);
6881                m[0][0] = x;
6882                authored_scale.0 *= x;
6883            }
6884            T::ScaleY(value) => {
6885                let y = factor(value);
6886                m[1][1] = y;
6887                authored_scale.1 *= y;
6888            }
6889            T::ScaleZ(_) => {}
6890            T::Skew(a, b) => {
6891                m = [
6892                    [1.0, f64::from(a.to_radians()).tan()],
6893                    [f64::from(b.to_radians()).tan(), 1.0],
6894                ];
6895                affine |= a.to_degrees() != 0.0 || b.to_degrees() != 0.0;
6896            }
6897            T::SkewX(a) => {
6898                m[0][1] = f64::from(a.to_radians()).tan();
6899                affine |= a.to_degrees() != 0.0;
6900            }
6901            T::SkewY(a) => {
6902                m[1][0] = f64::from(a.to_radians()).tan();
6903                affine |= a.to_degrees() != 0.0;
6904            }
6905            T::Matrix(value) => {
6906                m = [
6907                    [f64::from(value.a), f64::from(value.c)],
6908                    [f64::from(value.b), f64::from(value.d)],
6909                ];
6910                t[0][0] = f64::from(value.e);
6911                t[1][0] = f64::from(value.f);
6912                affine = true;
6913            }
6914            T::Matrix3d(_) => {
6915                dropped.push("matrix3d()");
6916                continue;
6917            }
6918            T::Perspective(_) => {
6919                dropped.push("perspective()");
6920                continue;
6921            }
6922            T::TranslateZ(_) => {
6923                dropped.push("the Z axis of a 3D translate");
6924                continue;
6925            }
6926        }
6927        if m.iter()
6928            .flatten()
6929            .chain(t.iter().flatten())
6930            .any(|v| !v.is_finite())
6931        {
6932            dropped.push("a non-finite 2D transform");
6933            continue;
6934        }
6935        append(&mut linear, &mut offset, m, t);
6936    }
6937    let (sin, cos) = authored_rotate.sin_cos();
6938    let expected = [
6939        [cos * authored_scale.0, -sin * authored_scale.1],
6940        [sin * authored_scale.0, cos * authored_scale.1],
6941    ];
6942    affine |= linear
6943        .iter()
6944        .flatten()
6945        .zip(expected.iter().flatten())
6946        .any(|(a, b)| (a - b).abs() > 1e-6 * a.abs().max(b.abs()).max(1.0));
6947    let (mut rotate, mut scale, mut shear) = (
6948        authored_rotate as f32,
6949        (authored_scale.0 as f32, authored_scale.1 as f32),
6950        0.0f32,
6951    );
6952    if affine {
6953        let [[a, c], [b, d]] = linear;
6954        let sx = a.hypot(b);
6955        if sx != 0.0 {
6956            rotate = b.atan2(a) as f32;
6957            scale = (sx as f32, ((a * d - b * c) / sx) as f32);
6958            shear = ((a * c + b * d) / sx) as f32;
6959        } else {
6960            rotate = (-c).atan2(d) as f32;
6961            scale = (0.0, c.hypot(d) as f32);
6962        }
6963    }
6964    let basis = offset.map(|row| row.map(|value| value as f32));
6965    let (x, y) = (slot(basis[0], 0), slot(basis[1], 1));
6966    let origin = r
6967        .vn_transform
6968        .map(|t| t.origin)
6969        .unwrap_or(TransformSpec::CENTRE_ORIGIN);
6970    let mut spec = TransformSpec {
6971        translate: (
6972            x.unwrap_or(TransformLength::ZERO),
6973            y.unwrap_or(TransformLength::ZERO),
6974        ),
6975        rotate,
6976        scale,
6977        shear,
6978        origin,
6979        translation_basis: (x.is_none() || y.is_none()).then_some(basis),
6980    };
6981    if [rotate, scale.0, scale.1, shear]
6982        .iter()
6983        .chain(basis.iter().flatten())
6984        .any(|v| !v.is_finite())
6985    {
6986        dropped.push("an out-of-range 2D composition");
6987        spec = TransformSpec {
6988            origin,
6989            ..TransformSpec::IDENTITY
6990        };
6991    }
6992    r.vn_transform = Some(spec);
6993    if !dropped.is_empty() {
6994        dropped.sort_unstable();
6995        dropped.dedup();
6996        once(diagnostics, format!("`transform` supports ordered 2D translate(), rotate(), scale(), skew(), matrix() and `transform-origin` at paint time — dropped {}", dropped.join(", ")));
6997    }
6998}
6999pub fn transform_css(spec: TransformSpec) -> String {
7000    if spec.is_identity() {
7001        return "none".into();
7002    }
7003    let mut parts = Vec::new();
7004    let len = |value: TransformLength| match value {
7005        TransformLength::Pixels(value) => format!("{value}px"),
7006        TransformLength::Fraction(value) => format!("{}%", value * 100.0),
7007    };
7008    if let Some([[px, width, cross_x], [py, cross_y, height]]) = spec.translation_basis {
7009        if px != 0.0 || py != 0.0 {
7010            parts.push(format!("translate({px}px, {py}px)"));
7011        }
7012        if width != 0.0 || height != 0.0 {
7013            parts.push(format!(
7014                "translate({}%, {}%)",
7015                width * 100.0,
7016                height * 100.0
7017            ));
7018        }
7019        if cross_x != 0.0 {
7020            parts.push(format!(
7021                "rotate(-90deg) translateY({}%) rotate(90deg)",
7022                cross_x * 100.0
7023            ));
7024        }
7025        if cross_y != 0.0 {
7026            parts.push(format!(
7027                "rotate(90deg) translateX({}%) rotate(-90deg)",
7028                cross_y * 100.0
7029            ));
7030        }
7031    } else if !spec.translate.0.is_zero() || !spec.translate.1.is_zero() {
7032        parts.push(format!(
7033            "translate({}, {})",
7034            len(spec.translate.0),
7035            len(spec.translate.1)
7036        ));
7037    }
7038    if spec.rotate != 0.0 {
7039        parts.push(format!("rotate({}deg)", spec.rotate.to_degrees()));
7040    }
7041    if spec.shear != 0.0 {
7042        parts.push(format!(
7043            "matrix({},0,{},{},0,0)",
7044            spec.scale.0, spec.shear, spec.scale.1
7045        ));
7046    } else if spec.scale != (1.0, 1.0) {
7047        parts.push(format!("scale({}, {})", spec.scale.0, spec.scale.1));
7048    }
7049    parts.join(" ")
7050}
7051fn apply_backdrop_filter(
7052    list: &lightningcss::properties::effects::FilterList,
7053    r: &mut StyleRefinement,
7054    diagnostics: &mut Vec<String>,
7055) {
7056    use lightningcss::properties::effects::{Filter, FilterList};
7057
7058    let filters = match list {
7059        FilterList::None => {
7060            r.backdrop_blur = Some(px(0.0));
7061            return;
7062        }
7063        FilterList::Filters(filters) => filters,
7064    };
7065
7066    let mut blur_radius = None;
7067    let mut others = Vec::new();
7068    for filter in filters.iter() {
7069        match filter {
7070            Filter::Blur(length) => match css_length_px(length) {
7071                Some(radius) if blur_radius.is_none() => blur_radius = Some(radius.max(0.0)),
7072                Some(_) => others.push("a second blur()"),
7073                None => others.push("blur() with a non-absolute length"),
7074            },
7075            Filter::Brightness(_) => others.push("brightness()"),
7076            Filter::Contrast(_) => others.push("contrast()"),
7077            Filter::Grayscale(_) => others.push("grayscale()"),
7078            Filter::HueRotate(_) => others.push("hue-rotate()"),
7079            Filter::Invert(_) => others.push("invert()"),
7080            Filter::Opacity(_) => others.push("opacity()"),
7081            Filter::Saturate(_) => others.push("saturate()"),
7082            Filter::Sepia(_) => others.push("sepia()"),
7083            Filter::DropShadow(_) => others.push("drop-shadow()"),
7084            Filter::Url(_) => others.push("url() SVG filters"),
7085        }
7086    }
7087
7088    if let Some(radius) = blur_radius {
7089        r.backdrop_blur = Some(px(radius));
7090    }
7091    if !others.is_empty() {
7092        once(
7093            diagnostics,
7094            format!(
7095                "backdrop-filter: only blur() is implemented (v1) — dropped {}",
7096                others.join(", ")
7097            ),
7098        );
7099    }
7100}
7101
7102fn apply_filter(
7103    list: &lightningcss::properties::effects::FilterList,
7104    x: &mut Extras,
7105    diagnostics: &mut Vec<String>,
7106) {
7107    use lightningcss::properties::effects::{Filter, FilterList};
7108
7109    let filters = match list {
7110        FilterList::None => {
7111            x.blur = Some(0.0);
7112            x.drop_shadow = None;
7113            x.filter_url = None;
7114            return;
7115        }
7116        FilterList::Filters(filters) => filters,
7117    };
7118
7119    let mut blur_radius = None;
7120    let mut drop_shadow = None;
7121    let mut filter_url = None;
7122    let mut others = Vec::new();
7123    for filter in filters.iter() {
7124        match filter {
7125            Filter::Blur(length) => match css_length_px(length) {
7126                Some(radius) if blur_radius.is_none() => blur_radius = Some(radius.max(0.0)),
7127                Some(_) => others.push("a second blur()"),
7128                None => others.push("blur() with a non-absolute length"),
7129            },
7130            Filter::Brightness(_) => others.push("brightness()"),
7131            Filter::Contrast(_) => others.push("contrast()"),
7132            Filter::Grayscale(_) => others.push("grayscale()"),
7133            Filter::HueRotate(_) => others.push("hue-rotate()"),
7134            Filter::Invert(_) => others.push("invert()"),
7135            Filter::Opacity(_) => others.push("opacity()"),
7136            Filter::Saturate(_) => others.push("saturate()"),
7137            Filter::Sepia(_) => others.push("sepia()"),
7138            Filter::DropShadow(shadow) => match drop_shadow_of(shadow) {
7139                Some(s) if drop_shadow.is_none() => drop_shadow = Some(s),
7140                Some(_) => others.push("a second drop-shadow()"),
7141                None => others.push("drop-shadow() with a non-absolute length"),
7142            },
7143            Filter::Url(url) if filters.len() == 1 && url.url.starts_with('#') => {
7144                filter_url = Some(Rc::from(url.url.as_ref()));
7145            }
7146            Filter::Url(_) => others.push("external or chained url() SVG filters"),
7147        }
7148    }
7149
7150    x.blur = Some(blur_radius.unwrap_or(0.0));
7151    x.drop_shadow = drop_shadow;
7152    x.filter_url = filter_url;
7153
7154    if !others.is_empty() {
7155        once(
7156            diagnostics,
7157            format!(
7158                "`filter`: supported functions are blur(), drop-shadow(), and a single \
7159                 same-document SVG feColorMatrix URL. Blur and drop-shadow require the \
7160                 painted shape described by the render-side advisory — dropped {}",
7161                others.join(", ")
7162            ),
7163        );
7164    }
7165}
7166
7167fn drop_shadow_of(shadow: &lightningcss::properties::effects::DropShadow) -> Option<DropShadow> {
7168    Some(DropShadow {
7169        dx: css_length_px(&shadow.x_offset)?,
7170        dy: css_length_px(&shadow.y_offset)?,
7171        blur: css_length_px(&shadow.blur)?.max(0.0),
7172        // `None` here is `currentColor` — the CSS default for the function's colour argument, and
7173        // the one value `color()` cannot flatten.
7174        color: color(&shadow.color),
7175    })
7176}
7177
7178const SIDE_TOP: u8 = 1;
7179const SIDE_RIGHT: u8 = 2;
7180const SIDE_BOTTOM: u8 = 4;
7181const SIDE_LEFT: u8 = 8;
7182const SIDES_ALL: u8 = SIDE_TOP | SIDE_RIGHT | SIDE_BOTTOM | SIDE_LEFT;
7183
7184fn set_border_style(
7185    r: &mut StyleRefinement,
7186    s: LineStyle,
7187    sides: u8,
7188    diagnostics: &mut Vec<String>,
7189) {
7190    if matches!(s, LineStyle::None | LineStyle::Hidden) {
7191        let zero: AbsoluteLength = px(0.0).into();
7192        if sides & SIDE_TOP != 0 {
7193            r.border_widths.top = Some(zero);
7194        }
7195        if sides & SIDE_RIGHT != 0 {
7196            r.border_widths.right = Some(zero);
7197        }
7198        if sides & SIDE_BOTTOM != 0 {
7199            r.border_widths.bottom = Some(zero);
7200        }
7201        if sides & SIDE_LEFT != 0 {
7202            r.border_widths.left = Some(zero);
7203        }
7204        return;
7205    }
7206    r.border_style = Some(match s {
7207        LineStyle::Dashed => gpui::BorderStyle::Dashed,
7208        LineStyle::Solid => gpui::BorderStyle::Solid,
7209        _ => {
7210            unsupported(
7211                diagnostics,
7212                "border-style (dotted/double/groove/ridge/inset/outset render as solid)",
7213            );
7214            gpui::BorderStyle::Solid
7215        }
7216    });
7217}
7218
7219fn lp_definite_of_lpa(v: &LengthPercentageOrAuto) -> Option<DefiniteLength> {
7220    match v {
7221        LengthPercentageOrAuto::LengthPercentage(lp) => lp_definite(lp),
7222        LengthPercentageOrAuto::Auto => None,
7223    }
7224}
7225
7226fn overflow(k: OverflowKeyword) -> Overflow {
7227    match k {
7228        OverflowKeyword::Hidden | OverflowKeyword::Clip => Overflow::Hidden,
7229        OverflowKeyword::Scroll | OverflowKeyword::Auto => Overflow::Scroll,
7230        OverflowKeyword::Visible => Overflow::Visible,
7231    }
7232}
7233
7234fn overflow_keyword(axis: Option<Overflow>, declared: Option<OverflowKeyword>) -> OverflowKeyword {
7235    use OverflowKeyword as K;
7236    match axis {
7237        None | Some(Overflow::Visible) => K::Visible,
7238        Some(Overflow::Clip) => K::Clip,
7239        Some(Overflow::Hidden) if declared == Some(K::Clip) => K::Clip,
7240        Some(Overflow::Hidden) => K::Hidden,
7241        Some(Overflow::Scroll) if declared == Some(K::Auto) => K::Auto,
7242        Some(Overflow::Scroll) => K::Scroll,
7243    }
7244}
7245
7246pub(crate) fn compute_overflow(r: &mut StyleRefinement, x: &mut Extras) {
7247    use OverflowKeyword as K;
7248    if x.contain_paint == Some(true) {
7249        if overflow_keyword(r.overflow.x, x.overflow_x) == K::Visible {
7250            r.overflow.x = Some(overflow(K::Clip));
7251            x.overflow_x = Some(K::Clip);
7252        }
7253        if overflow_keyword(r.overflow.y, x.overflow_y) == K::Visible {
7254            r.overflow.y = Some(overflow(K::Clip));
7255            x.overflow_y = Some(K::Clip);
7256        }
7257    }
7258    let kx = overflow_keyword(r.overflow.x, x.overflow_x);
7259    let ky = overflow_keyword(r.overflow.y, x.overflow_y);
7260    let plain = |k: K| matches!(k, K::Visible | K::Clip);
7261    if plain(kx) == plain(ky) {
7262        return;
7263    }
7264    let computed = |k: K| match k {
7265        K::Visible => K::Auto,
7266        K::Clip => K::Hidden,
7267        k => k,
7268    };
7269    if plain(kx) {
7270        r.overflow.x = Some(overflow(computed(kx)));
7271        x.overflow_x = Some(computed(kx));
7272    } else {
7273        r.overflow.y = Some(overflow(computed(ky)));
7274        x.overflow_y = Some(computed(ky));
7275    }
7276}
7277
7278impl Extras {
7279    pub const CONTAIN_WIDTH: u8 = 1;
7280    pub const CONTAIN_HEIGHT: u8 = 2;
7281
7282    pub fn overflow_names(&self, base: &StyleRefinement) -> [&'static str; 2] {
7283        let name = |k: OverflowKeyword| match k {
7284            OverflowKeyword::Visible => "visible",
7285            OverflowKeyword::Hidden => "hidden",
7286            OverflowKeyword::Clip => "clip",
7287            OverflowKeyword::Scroll => "scroll",
7288            OverflowKeyword::Auto => "auto",
7289        };
7290        [
7291            name(overflow_keyword(base.overflow.x, self.overflow_x)),
7292            name(overflow_keyword(base.overflow.y, self.overflow_y)),
7293        ]
7294    }
7295}
7296
7297fn border_width_px(w: &lightningcss::properties::border::BorderSideWidth) -> Option<f32> {
7298    use lightningcss::properties::border::BorderSideWidth as W;
7299    match w {
7300        W::Length(l) => css_length_px(l),
7301        W::Thin => Some(1.0),
7302        W::Medium => Some(3.0),
7303        W::Thick => Some(5.0),
7304    }
7305}
7306
7307fn prop_name(p: &Property) -> String {
7308    let d = format!("{p:?}");
7309    d.split(['(', ' ', '{']).next().unwrap_or("?").to_string()
7310}
7311
7312#[cfg(test)]
7313mod tests {
7314    use super::*;
7315
7316    fn map(body: &str) -> (StyleRefinement, Vec<String>) {
7317        let mut diagnostics = Vec::new();
7318        let r = parse_inline(body, &mut diagnostics);
7319        (r, diagnostics)
7320    }
7321
7322    fn map_full(body: &str) -> (StyleRefinement, Extras, Vec<String>) {
7323        let mut diagnostics = Vec::new();
7324        let (refinement, _, extras) = parse_inline_full(body, &mut diagnostics);
7325        (refinement, extras, diagnostics)
7326    }
7327
7328    fn clean(body: &str) -> StyleRefinement {
7329        let (r, d) = map(body);
7330        assert!(d.is_empty(), "{body:?} produced {d:?}");
7331        r
7332    }
7333
7334    #[test]
7335    fn overflow_longhands_set_one_axis_each() {
7336        let r = clean("overflow-x: hidden");
7337        assert_eq!(r.overflow.x, Some(Overflow::Hidden));
7338        assert_eq!(r.overflow.y, None, "overflow-x must not touch the y axis");
7339
7340        let r = clean("overflow-y: scroll");
7341        assert_eq!(r.overflow.y, Some(Overflow::Scroll));
7342        assert_eq!(r.overflow.x, None);
7343
7344        assert_eq!(clean("overflow-y: auto").overflow.y, Some(Overflow::Scroll));
7345        assert_eq!(
7346            clean("overflow-x: visible").overflow.x,
7347            Some(Overflow::Visible)
7348        );
7349    }
7350
7351    #[test]
7352    fn a_longhand_after_the_shorthand_wins_on_its_axis_only() {
7353        let r = clean("overflow: hidden; overflow-y: scroll");
7354        assert_eq!(r.overflow.x, Some(Overflow::Hidden));
7355        assert_eq!(r.overflow.y, Some(Overflow::Scroll));
7356    }
7357
7358    fn computed_overflow(body: &str) -> (StyleRefinement, [&'static str; 2]) {
7359        let (mut r, mut x, d) = map_full(body);
7360        assert!(d.is_empty(), "{body:?} produced {d:?}");
7361        compute_overflow(&mut r, &mut x);
7362        let names = x.overflow_names(&r);
7363        (r, names)
7364    }
7365
7366    #[test]
7367    fn visible_beside_a_scrolling_axis_computes_to_auto() {
7368        let (r, names) = computed_overflow("overflow-y: auto");
7369        assert_eq!(names, ["auto", "auto"]);
7370        assert_eq!(
7371            r.overflow.x,
7372            Some(Overflow::Scroll),
7373            "x scrolls too, it is not just clipped"
7374        );
7375        assert_eq!(r.overflow.y, Some(Overflow::Scroll));
7376
7377        let (r, names) = computed_overflow("overflow-x: hidden");
7378        assert_eq!(names, ["hidden", "auto"]);
7379        assert_eq!(r.overflow.y, Some(Overflow::Scroll));
7380
7381        assert_eq!(
7382            computed_overflow("overflow-x: scroll").1,
7383            ["scroll", "auto"]
7384        );
7385        assert_eq!(computed_overflow("overflow: auto").1, ["auto", "auto"]);
7386        assert_eq!(
7387            computed_overflow("overflow: hidden scroll").1,
7388            ["hidden", "scroll"]
7389        );
7390    }
7391
7392    #[test]
7393    fn clip_beside_a_scrolling_axis_computes_to_hidden_and_beside_visible_stays() {
7394        assert_eq!(
7395            computed_overflow("overflow-x: clip; overflow-y: auto").1,
7396            ["hidden", "auto"]
7397        );
7398        let (r, names) = computed_overflow("overflow-x: clip");
7399        assert_eq!(names, ["clip", "visible"]);
7400        assert_eq!(r.overflow.y, None);
7401        assert_eq!(computed_overflow("overflow: clip").1, ["clip", "clip"]);
7402        assert_eq!(computed_overflow("color: red").1, ["visible", "visible"]);
7403    }
7404
7405    #[test]
7406    fn the_refinement_decides_and_the_keyword_only_qualifies_it() {
7407        let (mut base, mut x, _) = map_full("color: red");
7408        x.refine(&map_full("overflow-y: auto").1);
7409        compute_overflow(&mut base, &mut x);
7410        assert_eq!(x.overflow_names(&base), ["visible", "visible"]);
7411        assert_eq!(base.overflow.x, None);
7412    }
7413
7414    #[test]
7415    fn gap_longhands_map_to_the_matching_axis() {
7416        let r = clean("row-gap: 4px; column-gap: 8px");
7417        assert_eq!(r.gap.height, Some(px(4.0).into()));
7418        assert_eq!(r.gap.width, Some(px(8.0).into()));
7419    }
7420
7421    #[test]
7422    fn border_style_none_computes_the_widths_to_zero() {
7423        let r = clean("border: 3px solid red; border-style: none");
7424        let zero: AbsoluteLength = px(0.0).into();
7425        assert_eq!(r.border_widths.top, Some(zero));
7426        assert_eq!(r.border_widths.right, Some(zero));
7427        assert_eq!(r.border_widths.bottom, Some(zero));
7428        assert_eq!(r.border_widths.left, Some(zero));
7429    }
7430
7431    #[test]
7432    fn border_style_none_on_one_side_leaves_the_others() {
7433        let zero: AbsoluteLength = px(0.0).into();
7434        let one: AbsoluteLength = px(1.0).into();
7435        for body in [
7436            "border: 1px solid red; border-bottom: none",
7437            "border: 1px solid red; border-bottom: 0",
7438            "border: 1px solid red; border-bottom-style: none",
7439            "border: 1px solid red; border-style: solid solid none",
7440        ] {
7441            let r = clean(body);
7442            assert_eq!(r.border_widths.bottom, Some(zero), "{body}");
7443            assert_eq!(r.border_widths.top, Some(one), "{body}");
7444            assert_eq!(r.border_widths.right, Some(one), "{body}");
7445            assert_eq!(r.border_widths.left, Some(one), "{body}");
7446            assert_eq!(r.border_style, Some(gpui::BorderStyle::Solid), "{body}");
7447        }
7448        let r = clean("border-right: none");
7449        assert_eq!(r.border_widths.right, Some(zero));
7450        assert_eq!(r.border_widths.top, None);
7451    }
7452
7453    #[test]
7454    fn border_style_dashed_and_solid_for_the_rest() {
7455        assert_eq!(
7456            clean("border-style: dashed").border_style,
7457            Some(gpui::BorderStyle::Dashed)
7458        );
7459        let (r, _) = map("border-style: dotted");
7460        assert_eq!(r.border_style, Some(gpui::BorderStyle::Solid));
7461    }
7462
7463    #[test]
7464    fn corner_radius_longhands() {
7465        let r = clean("border-top-left-radius: 8px; border-bottom-right-radius: 2px");
7466        assert_eq!(r.corner_radii.top_left, Some(px(8.0).into()));
7467        assert_eq!(r.corner_radii.bottom_right, Some(px(2.0).into()));
7468        assert_eq!(r.corner_radii.top_right, None);
7469        assert_eq!(r.vn_corner_radii.top_left, Some(None));
7470        assert_eq!(r.vn_corner_radii.top_right, None);
7471    }
7472
7473    #[test]
7474    fn relative_and_elliptical_radii_resolve_at_paint() {
7475        let half = gpui::VnCornerRadius {
7476            x: relative(0.5),
7477            y: relative(0.5),
7478        };
7479        let r = clean("border-radius: 50%");
7480        for (length, relative) in [
7481            (r.corner_radii.top_left, r.vn_corner_radii.top_left),
7482            (r.corner_radii.top_right, r.vn_corner_radii.top_right),
7483            (r.corner_radii.bottom_right, r.vn_corner_radii.bottom_right),
7484            (r.corner_radii.bottom_left, r.vn_corner_radii.bottom_left),
7485        ] {
7486            assert_eq!(length, Some(px(0.).into()));
7487            assert_eq!(relative, Some(Some(half)));
7488        }
7489
7490        let r = clean("border-top-left-radius: calc(50% - 2px)");
7491        let calc = DefiniteLength::Calc {
7492            fraction: 0.5,
7493            pixels: px(-2.),
7494        };
7495        assert_eq!(
7496            r.vn_corner_radii.top_left,
7497            Some(Some(gpui::VnCornerRadius { x: calc, y: calc }))
7498        );
7499
7500        let r = clean("border-radius: 10px / 20px");
7501        assert_eq!(
7502            r.vn_corner_radii.bottom_left,
7503            Some(Some(gpui::VnCornerRadius {
7504                x: px(10.).into(),
7505                y: px(20.).into()
7506            }))
7507        );
7508
7509        let r = clean("border-radius: 6px / 6px");
7510        assert_eq!(r.corner_radii.top_right, Some(px(6.).into()));
7511        assert_eq!(r.vn_corner_radii.top_right, Some(None));
7512    }
7513
7514    #[test]
7515    fn flex_shorthand_fills_all_three_fields() {
7516        let r = clean("flex: 1 1 0%");
7517        assert_eq!(r.flex_grow, Some(1.0));
7518        assert_eq!(r.flex_shrink, Some(1.0));
7519        assert_eq!(r.flex_basis, Some(Length::Definite(relative(0.0))));
7520
7521        let r = clean("flex: none");
7522        assert_eq!(r.flex_grow, Some(0.0));
7523        assert_eq!(r.flex_shrink, Some(0.0));
7524        assert_eq!(r.flex_basis, Some(Length::Auto));
7525    }
7526
7527    #[test]
7528    fn order_reaches_the_layout_in_every_spelling() {
7529        assert_eq!(clean("order: -3").vn_order, Some(-3));
7530        assert_eq!(clean("-webkit-order: 2").vn_order, Some(2));
7531        let mut d = Vec::new();
7532        let vars = crate::vars::resolve(
7533            &Rc::new(Vars::default()),
7534            &[&("--o".to_string(), "7".to_string())],
7535            &crate::Env::default(),
7536            &mut d,
7537        );
7538        let mut r = StyleRefinement::default();
7539        apply_dynamic(
7540            "order",
7541            "var(--o)",
7542            &vars,
7543            &crate::Env::default(),
7544            &mut r,
7545            &mut Extras::default(),
7546            &mut d,
7547        );
7548        assert!(d.is_empty(), "{d:?}");
7549        assert_eq!(r.vn_order, Some(7));
7550    }
7551
7552    fn rgb8(c: Option<Hsla>) -> [u8; 4] {
7553        let c = gpui::Rgba::from(c.expect("a concrete colour"));
7554        [c.r, c.g, c.b, c.a].map(|v| (v * 255.0).round() as u8)
7555    }
7556
7557    #[test]
7558    fn css_color_4_and_5_functions_compute_to_srgb() {
7559        let text = |value: &str| rgb8(clean(&format!("color: {value}")).text.color);
7560        assert_eq!(text("oklch(62.8% 0.2577 29.23)"), [255, 0, 0, 255]);
7561        assert_eq!(text("oklab(0.5 0 0)"), [99, 99, 99, 255]);
7562        assert_eq!(text("lab(54.29% 80.82 69.91)"), [255, 0, 0, 255]);
7563        assert_eq!(text("lch(54.29% 106.84 40.85 / 50%)"), [255, 0, 0, 128]);
7564        assert_eq!(text("hwb(120 0% 0%)"), [0, 255, 0, 255]);
7565        assert_eq!(text("color(srgb 0 0.5 1)"), [0, 128, 255, 255]);
7566        assert_eq!(
7567            text("color(srgb-linear 0.2158 0.2158 0.2158)"),
7568            [128, 128, 128, 255]
7569        );
7570        assert_eq!(text("color-mix(in srgb, red, blue)"), [128, 0, 128, 255]);
7571        assert_eq!(
7572            text("color-mix(in srgb, red 25%, transparent)"),
7573            [255, 0, 0, 64]
7574        );
7575        assert_eq!(text("rgb(from #ff0000 r g 255)"), [255, 0, 255, 255]);
7576        assert_eq!(text("oklch(from #00ff00 l c h / 0.5)"), [0, 255, 0, 128]);
7577    }
7578
7579    #[test]
7580    fn a_wide_gamut_colour_is_clipped_into_srgb() {
7581        let [r, g, b, _] = rgb8(clean("color: color(display-p3 1 0 0)").text.color);
7582        assert!(r == 255 && g < 40 && b < 40, "{r} {g} {b}");
7583        let [r, g, b, _] = rgb8(clean("color: oklch(90% 0.4 145)").text.color);
7584        assert!(
7585            g > r && g > b && g > 220,
7586            "a too-vivid green stays green: {r} {g} {b}"
7587        );
7588    }
7589
7590    #[test]
7591    fn every_colour_valued_property_takes_a_css_color_4_value() {
7592        let red = "oklch(62.8% 0.2577 29.23)";
7593        let solid = |r: &StyleRefinement| match &r.background {
7594            Some(gpui::Fill::Color(bg)) => bg.as_solid(),
7595            _ => None,
7596        };
7597        let want = [255, 0, 0, 255];
7598        assert_eq!(
7599            rgb8(solid(&clean(&format!("background-color: {red}")))),
7600            want
7601        );
7602        assert_eq!(
7603            rgb8(clean(&format!("border-color: {red}")).border_color),
7604            want
7605        );
7606        assert_eq!(
7607            rgb8(
7608                clean(&format!("border-left: 1px solid {red}"))
7609                    .vn_border_colors
7610                    .left
7611                    .flatten()
7612            ),
7613            want
7614        );
7615        let outline = clean(&format!("outline: 2px solid {red}"))
7616            .vn_outline
7617            .expect("ring");
7618        assert_eq!(rgb8(Some(outline.color)), want);
7619        let shadow = clean(&format!("box-shadow: 0 0 4px {red}"))
7620            .box_shadow
7621            .expect("shadow");
7622        assert_eq!(rgb8(Some(shadow[0].color)), want);
7623        let decoration = clean(&format!("text-decoration: underline {red}"))
7624            .text
7625            .underline
7626            .expect("line");
7627        assert_eq!(rgb8(decoration.color), want);
7628
7629        let (x, d) = extras(&format!(
7630            "accent-color: {red}; fill: {red}; overflow: auto; scrollbar-color: {red} lab(0% 0 0)"
7631        ));
7632        assert!(d.is_empty(), "{d:?}");
7633        assert_eq!(rgb8(x.accent_color.flatten()), want);
7634        let Some(SvgPaint::Color(fill)) = x.fill else {
7635            panic!("{:?}", x.fill)
7636        };
7637        assert_eq!(rgb8(Some(fill)), want);
7638        let (thumb, track) = x.scrollbar_color.expect("pair");
7639        assert_eq!(
7640            (rgb8(Some(thumb)), rgb8(Some(track))),
7641            (want, [0, 0, 0, 255])
7642        );
7643
7644        let (x, d) = extras(&format!(
7645            "background-image: linear-gradient({red}, color-mix(in oklab, {red}, {red}))"
7646        ));
7647        assert!(d.is_empty(), "{d:?}");
7648        assert!(x.background_images.is_some_and(|l| !l.is_empty()));
7649    }
7650
7651    #[test]
7652    fn scroll_behavior_is_carried_for_the_scroller_and_a_later_auto_takes_it_back() {
7653        let (x, d) = extras("scroll-behavior: smooth");
7654        assert_eq!((x.scroll_smooth, d.len()), (Some(true), 0));
7655        let (x, d) = extras("scroll-behavior: smooth; scroll-behavior: auto");
7656        assert_eq!((x.scroll_smooth, d.len()), (Some(false), 0));
7657        let (x, d) = extras("scroll-behavior: slowly");
7658        assert_eq!((x.scroll_smooth, d.len()), (None, 1));
7659    }
7660
7661    #[test]
7662    fn object_position_is_a_fraction_of_the_free_space_plus_an_offset() {
7663        let at = |body: &str| {
7664            let p = clean(body).vn_object_position.expect("mapped");
7665            (
7666                p.x_fraction,
7667                f32::from(p.x_offset),
7668                p.y_fraction,
7669                f32::from(p.y_offset),
7670            )
7671        };
7672        assert_eq!(at("object-position: left"), (0.0, 0.0, 0.5, 0.0));
7673        assert_eq!(at("object-position: 25% 10px"), (0.25, 0.0, 0.0, 10.0));
7674        assert_eq!(
7675            at("object-position: right 10px bottom 20%"),
7676            (1.0, -10.0, 0.8, 0.0)
7677        );
7678        assert_eq!(at("object-position: top right"), (1.0, 0.0, 0.0, 0.0));
7679        assert_eq!(
7680            at("object-position: calc(50% + 4px) center"),
7681            (0.5, 4.0, 0.5, 0.0)
7682        );
7683        let (r, d) = map("object-position: 10px sideways");
7684        assert_eq!(r.vn_object_position, None);
7685        assert_eq!(d.len(), 1, "{d:?}");
7686    }
7687
7688    #[test]
7689    fn grid_cols_maps_tailwinds_repeat_minmax() {
7690        let r = clean("grid-template-columns: repeat(3, minmax(0, 1fr))");
7691        assert_eq!(
7692            r.grid_cols,
7693            Some(gpui::GridTemplate {
7694                repeat: 3,
7695                min_size: gpui::GridTemplateMinSize::Zero,
7696            })
7697        );
7698        let r = clean("grid-template-rows: repeat(2, minmax(0, 1fr))");
7699        assert_eq!(r.grid_rows.map(|t| t.repeat), Some(2));
7700    }
7701
7702    #[test]
7703    fn an_arbitrary_track_list_becomes_an_explicit_track_list() {
7704        use gpui::{GridTrack, GridTrackSize as G};
7705        let r = clean("grid-template-columns: 200px 1fr");
7706        assert_eq!(r.grid_cols, None);
7707        assert_eq!(
7708            r.vn_grid_cols,
7709            Some(vec![GridTrack::fixed(G::Px(200.0)), GridTrack::fr(1.0)])
7710        );
7711        assert_eq!(
7712            clean("grid-template-columns: 1fr auto").vn_grid_cols,
7713            Some(vec![GridTrack::fr(1.0), GridTrack::fixed(G::Auto)])
7714        );
7715        assert_eq!(
7716            clean("grid-template-rows: repeat(2, minmax(min-content, 1fr)) 40px").vn_grid_rows,
7717            Some(vec![
7718                GridTrack {
7719                    min: G::MinContent,
7720                    max: G::Fr(1.0)
7721                },
7722                GridTrack {
7723                    min: G::MinContent,
7724                    max: G::Fr(1.0)
7725                },
7726                GridTrack::fixed(G::Px(40.0)),
7727            ])
7728        );
7729        assert_eq!(
7730            clean("grid-template-columns: 25% 75%").vn_grid_cols,
7731            Some(vec![
7732                GridTrack::fixed(G::Percent(0.25)),
7733                GridTrack::fixed(G::Percent(0.75)),
7734            ])
7735        );
7736    }
7737
7738    #[test]
7739    fn an_auto_repeat_is_counted_by_the_layout() {
7740        use gpui::{GridAutoRepeat, GridTrack, GridTrackSize as G};
7741        let r = clean("grid-template-columns: repeat(auto-fill, minmax(120px, 1fr))");
7742        assert_eq!(r.grid_cols, None);
7743        assert_eq!(
7744            r.vn_grid_cols,
7745            Some(vec![GridTrack {
7746                min: G::Px(120.0),
7747                max: G::Fr(1.0)
7748            }])
7749        );
7750        assert_eq!(
7751            r.vn_grid_cols_auto,
7752            Some(GridAutoRepeat {
7753                fit: false,
7754                start: 0,
7755                len: 1
7756            })
7757        );
7758
7759        let r = clean("grid-template-rows: 40px repeat(auto-fit, 10px 20%) 1rem");
7760        assert_eq!(
7761            r.vn_grid_rows,
7762            Some(vec![
7763                GridTrack::fixed(G::Px(40.0)),
7764                GridTrack::fixed(G::Px(10.0)),
7765                GridTrack::fixed(G::Percent(0.2)),
7766                GridTrack::fixed(G::Px(16.0)),
7767            ])
7768        );
7769        assert_eq!(
7770            r.vn_grid_rows_auto,
7771            Some(GridAutoRepeat {
7772                fit: true,
7773                start: 1,
7774                len: 2
7775            })
7776        );
7777
7778        assert_eq!(
7779            clean("grid-template-columns: 1fr auto").vn_grid_cols_auto,
7780            Some(GridAutoRepeat {
7781                fit: false,
7782                start: 0,
7783                len: 0
7784            })
7785        );
7786    }
7787
7788    #[test]
7789    fn an_unmodelable_track_list_is_dropped_not_a_wrong_grid() {
7790        for body in [
7791            "grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)) 1fr",
7792            "grid-template-columns: repeat(auto-fill, auto)",
7793            "grid-template-columns: fit-content(200px) 1fr",
7794        ] {
7795            let (r, _) = map(body);
7796            assert_eq!(r.grid_cols, None, "{body}");
7797            assert_eq!(r.vn_grid_cols, None, "{body}");
7798        }
7799    }
7800
7801    #[test]
7802    fn grid_placement_maps_lines_and_spans() {
7803        use gpui::GridPlacement as P;
7804        let r = clean("grid-column: 2 / 4");
7805        let loc = r.grid_location.clone().expect("a grid location");
7806        assert_eq!(loc.column, P::Line(2)..P::Line(4));
7807        let r = clean("grid-row: span 2");
7808        let loc = r.grid_location.clone().expect("a grid location");
7809        assert_eq!(loc.row.start, P::Span(2));
7810        let r = clean("grid-column-start: 3");
7811        assert_eq!(r.grid_location.unwrap().column.start, P::Line(3));
7812    }
7813
7814    #[test]
7815    fn implicit_track_lists_map_fractional_and_repeating_patterns() {
7816        use gpui::{GridTrack, GridTrackSize as Track};
7817        assert_eq!(
7818            clean("grid-auto-columns: 1fr").vn_grid_auto_cols,
7819            Some(vec![GridTrack::fr(1.0)])
7820        );
7821        assert_eq!(
7822            clean("grid-auto-rows: 20px 2rem 25% minmax(min-content, 1fr)").vn_grid_auto_rows,
7823            Some(vec![
7824                GridTrack::fixed(Track::Px(20.0)),
7825                GridTrack::fixed(Track::Px(32.0)),
7826                GridTrack::fixed(Track::Percent(0.25)),
7827                GridTrack {
7828                    min: Track::MinContent,
7829                    max: Track::Fr(1.0)
7830                }
7831            ])
7832        );
7833        // lightningcss canonicalizes a sole `auto` to an empty track list. It must remain Some so
7834        // the cascade can reset an earlier pattern.
7835        assert_eq!(
7836            clean("grid-auto-rows: 20px; grid-auto-rows: auto").vn_grid_auto_rows,
7837            Some(Vec::new())
7838        );
7839        let (style, _) = map("grid-auto-columns: 12px fit-content(30px)");
7840        assert!(
7841            style.vn_grid_auto_cols.is_none(),
7842            "unsupported tracks cannot leave a truncated pattern"
7843        );
7844    }
7845
7846    #[test]
7847    fn declared_visibility_is_not_the_paint_switch() {
7848        assert_eq!(extras("visibility: hidden").0.visibility_hidden, Some(true));
7849        assert_eq!(
7850            extras("visibility: collapse").0.visibility_hidden,
7851            Some(true)
7852        );
7853        assert_eq!(
7854            extras("visibility: visible").0.visibility_hidden,
7855            Some(false)
7856        );
7857        assert_eq!(extras("color: red").0.visibility_hidden, None);
7858        for sr_only in ["clip: rect(0, 0, 0, 0)"] {
7859            let mut d = Vec::new();
7860            let inline = parse_inline_style(sr_only, &mut d);
7861            assert_eq!(
7862                inline.refinement.and_then(|r| r.visibility),
7863                Some(gpui::Visibility::Hidden),
7864                "{sr_only}"
7865            );
7866            assert_eq!(inline.extras.visibility_hidden, None, "{sr_only}");
7867        }
7868        let mut d = Vec::new();
7869        let inline = parse_inline_style("clip-path: inset(50%)", &mut d);
7870        assert_eq!(inline.extras.visibility_hidden, None);
7871    }
7872
7873    #[test]
7874    fn custom_properties_travel_their_own_channel() {
7875        let mut d = Vec::new();
7876        let inline = parse_inline_style(
7877            "--tw-shadow: 0 0 #0000; --tw-ring-color: red; --whatever: 3; color: blue",
7878            &mut d,
7879        );
7880        assert!(d.is_empty(), "{d:?}");
7881        assert_eq!(
7882            inline.custom,
7883            vec![
7884                ("--tw-shadow".to_string(), "0 0 #0000".to_string()),
7885                ("--tw-ring-color".to_string(), "red".to_string()),
7886                ("--whatever".to_string(), "3".to_string()),
7887            ]
7888        );
7889        assert!(inline.refinement.is_some_and(|r| r.text.color.is_some()));
7890    }
7891
7892    #[test]
7893    fn a_var_composed_value_is_deferred_to_computed_value_time() {
7894        let mut d = Vec::new();
7895        let inline = parse_inline_style("box-shadow: var(--tw-shadow)", &mut d);
7896        assert!(d.is_empty(), "{d:?}");
7897        assert!(inline.refinement.is_none());
7898        assert_eq!(
7899            inline.dynamic,
7900            vec![("box-shadow".to_string(), "var(--tw-shadow)".to_string())]
7901        );
7902    }
7903
7904    #[test]
7905    fn apply_dynamic_substitutes_then_maps() {
7906        let mut d = Vec::new();
7907        let vars = crate::vars::resolve(
7908            &Rc::new(Vars::default()),
7909            &[&(
7910                "--tw-shadow".to_string(),
7911                "0 1px 2px 0 rgb(0 0 0 / 0.5)".to_string(),
7912            )],
7913            &crate::Env::default(),
7914            &mut d,
7915        );
7916        let mut r = StyleRefinement::default();
7917        let mut x = Extras::default();
7918        apply_dynamic(
7919            "box-shadow",
7920            "var(--tw-shadow)",
7921            &vars,
7922            &crate::Env::default(),
7923            &mut r,
7924            &mut x,
7925            &mut d,
7926        );
7927        assert!(d.is_empty(), "{d:?}");
7928        let shadows = r.box_shadow.expect("box-shadow mapped");
7929        assert_eq!(shadows.len(), 1);
7930        assert_eq!(shadows[0].blur_radius, px(2.0));
7931    }
7932
7933    #[test]
7934    fn currentcolor_is_recorded_for_substitution_after_the_cascade() {
7935        let (r, x, d) = map_full("background-color: currentColor");
7936        assert_eq!(r.background, None, "not resolvable yet");
7937        assert!(x.current_color.has(CurrentColorTargets::BACKGROUND));
7938        assert!(d.is_empty(), "{d:?}");
7939
7940        let (_, x, d) = map_full("border-color: currentColor");
7941        assert!(x.current_color.has(CurrentColorTargets::BORDER));
7942        assert!(d.is_empty(), "{d:?}");
7943
7944        let (r, x, d) = map_full("color: currentColor");
7945        assert_eq!(r.text.color, None);
7946        assert_eq!(x.current_color, CurrentColorTargets::default());
7947        assert!(d.is_empty(), "{d:?}");
7948    }
7949
7950    #[test]
7951    fn calc_that_is_not_a_finite_length_does_not_reach_the_layout() {
7952        let (r, _) = map("width: clamp(2rem, 5px, 1rem)");
7953        assert_eq!(r.size.width, Some(Length::Definite(px(32.0).into())));
7954        let (r, _) = map("width: calc(100px / 0)");
7955        assert_eq!(r.size.width, None);
7956        let (r, _) = map("padding-top: calc(1px * (1 / 0))");
7957        assert_eq!(r.padding.top, None);
7958    }
7959
7960    #[test]
7961    fn calc_sums_and_products_resolve_to_pixels() {
7962        assert_eq!(
7963            clean("border-radius: calc(0.5rem - 2px)")
7964                .corner_radii
7965                .top_left,
7966            Some(px(6.0).into())
7967        );
7968        assert_eq!(
7969            clean("padding-top: calc(1rem + 4px)").padding.top,
7970            Some(px(20.0).into())
7971        );
7972        assert_eq!(
7973            clean("width: calc(2 * 8px)").size.width,
7974            Some(Length::Definite(px(16.0).into()))
7975        );
7976        assert_eq!(
7977            clean("border-top-width: calc(4px + 1px)").border_widths.top,
7978            Some(px(5.0).into())
7979        );
7980        assert_eq!(
7981            clean("width: min(100px, 40px)").size.width,
7982            Some(Length::Definite(px(40.0).into()))
7983        );
7984        assert_eq!(
7985            clean("width: clamp(10px, 4px, 100px)").size.width,
7986            Some(Length::Definite(px(10.0).into()))
7987        );
7988    }
7989
7990    #[test]
7991    fn a_percentage_inside_calc_is_resolved_by_the_layout() {
7992        let calc = |fraction: f32, pixels: f32| {
7993            Some(Length::Definite(DefiniteLength::Calc {
7994                fraction,
7995                pixels: px(pixels),
7996            }))
7997        };
7998        assert_eq!(
7999            clean("left: calc(38.89% + 13.33px)").inset.left,
8000            calc(0.3889, 13.33)
8001        );
8002        assert_eq!(clean("width: calc(100% - 8px)").size.width, calc(1.0, -8.0));
8003        assert_eq!(
8004            clean("max-width: calc((100% - 1rem) * 0.5)").max_size.width,
8005            calc(0.5, -8.0)
8006        );
8007        assert_eq!(
8008            clean("margin-left: calc(-50% + 2px)").margin.left,
8009            calc(-0.5, 2.0)
8010        );
8011        assert_eq!(
8012            clean("padding-top: calc(10% - 1px)").padding.top,
8013            Some(DefiniteLength::Calc {
8014                fraction: 0.1,
8015                pixels: px(-1.0)
8016            })
8017        );
8018        assert_eq!(
8019            clean("width: calc(50% - 50% + 3px)").size.width,
8020            Some(Length::Definite(px(3.0).into()))
8021        );
8022    }
8023
8024    #[test]
8025    fn a_calc_that_cannot_be_laid_out_is_dropped() {
8026        let (r, _) = map("width: min(100%, 10px)");
8027        assert_eq!(r.size.width, None);
8028        let (r, _) = map("left: clamp(0px, 50%, 100px)");
8029        assert_eq!(r.inset.left, None);
8030    }
8031
8032    #[test]
8033    fn a_cursor_image_falls_back_to_its_keyword() {
8034        assert_eq!(
8035            clean("cursor: url(brush.svg) 8 8, crosshair").mouse_cursor,
8036            Some(gpui::CursorStyle::Crosshair)
8037        );
8038    }
8039
8040    #[test]
8041    fn flex_flow_sets_both_longhands() {
8042        let r = clean("flex-flow: column wrap-reverse");
8043        assert_eq!(
8044            (r.flex_direction, r.flex_wrap),
8045            (
8046                Some(gpui::FlexDirection::Column),
8047                Some(gpui::FlexWrap::WrapReverse)
8048            )
8049        );
8050        let r = clean("flex-direction: column; flex-flow: wrap");
8051        assert_eq!(
8052            (r.flex_direction, r.flex_wrap),
8053            (Some(gpui::FlexDirection::Row), Some(gpui::FlexWrap::Wrap)),
8054            "an omitted half resets to its initial value"
8055        );
8056    }
8057
8058    #[test]
8059    fn aspect_ratio_auto_overrides_an_earlier_ratio() {
8060        assert_eq!(clean("aspect-ratio: 16 / 8").aspect_ratio, Some(2.0));
8061        assert_eq!(
8062            clean("aspect-ratio: 2; aspect-ratio: auto").aspect_ratio,
8063            Some(0.0)
8064        );
8065        assert_eq!(clean("aspect-ratio: auto 2 / 1").aspect_ratio, Some(-2.0));
8066        assert_eq!(clean("aspect-ratio: 0 / 1").aspect_ratio, Some(0.0));
8067    }
8068
8069    fn extras(body: &str) -> (Extras, Vec<String>) {
8070        let mut d = Vec::new();
8071        let inline = parse_inline_style(body, &mut d);
8072        (inline.extras, d)
8073    }
8074
8075    fn transform(body: &str) -> (Option<TransformSpec>, Vec<String>) {
8076        let mut d = Vec::new();
8077        let inline = parse_inline_style(body, &mut d);
8078        (inline.refinement.and_then(|r| r.vn_transform), d)
8079    }
8080
8081    #[test]
8082    fn absolute_and_inset_map_straight_through() {
8083        let r = clean("position: absolute; inset: 0; left: 50%; top: 8px");
8084        assert_eq!(r.position, Some(gpui::Position::Absolute));
8085        assert_eq!(r.inset.right, Some(Length::Definite(px(0.0).into())));
8086        assert_eq!(r.inset.left, Some(Length::Definite(relative(0.5))));
8087        assert_eq!(r.inset.top, Some(Length::Definite(px(8.0).into())));
8088    }
8089
8090    #[test]
8091    fn css_wide_inset_resets_clear_offsets_and_keep_literal_source_order() {
8092        for keyword in ["initial", "unset"] {
8093            let r = clean(&format!(
8094                "inset: 9px; bottom: {keyword}; inset-inline-start: {keyword}"
8095            ));
8096            assert_eq!(r.inset.top, Some(px(9.0).into()));
8097            assert_eq!(r.inset.right, Some(px(9.0).into()));
8098            assert_eq!(r.inset.bottom, Some(Length::Auto));
8099            assert_eq!(r.inset.left, Some(Length::Auto));
8100            let r = clean(&format!("inset: {keyword}; bottom: 8px; inset-inline: 2px"));
8101            assert_eq!(r.inset.top, Some(Length::Auto));
8102            assert_eq!(r.inset.bottom, Some(px(8.0).into()));
8103            assert_eq!(r.inset.left, Some(px(2.0).into()));
8104            assert_eq!(r.inset.right, Some(px(2.0).into()));
8105        }
8106    }
8107
8108    #[test]
8109    fn appearance_none_takes_the_select_skin_away() {
8110        for (body, none) in [
8111            ("appearance: none", Some(true)),
8112            ("-webkit-appearance: none", Some(true)),
8113            ("-moz-appearance: none", None),
8114            ("appearance: auto", Some(false)),
8115            ("appearance: menulist-button", Some(false)),
8116            ("color: red", None),
8117        ] {
8118            let (x, d) = extras(body);
8119            assert_eq!(x.appearance_none, none, "{body}");
8120            assert!(d.is_empty(), "{body}: {d:?}");
8121        }
8122        let (mut x, _) = extras("appearance: none");
8123        x.refine(&extras("appearance: auto").0);
8124        assert_eq!(x.appearance_none, Some(false), "a later rule wins");
8125    }
8126
8127    #[test]
8128    fn fixed_is_absolute_plus_a_deferred_layer_and_no_advisory() {
8129        let (x, d) = extras("position: fixed");
8130        assert_eq!(x.fixed, Some(true));
8131        assert!(x.may_defer());
8132        assert!(d.is_empty(), "{d:?}");
8133        let (x, _) = extras("position: fixed; position: relative");
8134        assert_eq!(x.fixed, Some(false));
8135        assert!(!x.may_defer());
8136    }
8137
8138    #[test]
8139    fn z_index_auto_is_not_zero() {
8140        assert_eq!(extras("z-index: auto").0.z_index, Some(None));
8141        assert_eq!(extras("z-index: 0").0.z_index, Some(Some(0)));
8142        assert_eq!(extras("color: red").0.z_index, None);
8143        let mut folded = extras("z-index: 10").0;
8144        folded.refine(&extras("z-index: auto").0);
8145        assert_eq!(folded.z(), None);
8146        folded.refine(&extras("color: red").0);
8147        assert_eq!(
8148            folded.z_index,
8149            Some(None),
8150            "a block that says nothing keeps it"
8151        );
8152    }
8153
8154    #[test]
8155    fn translate_is_kept_in_its_authored_unit() {
8156        let (r, d) = transform("transform: translate(-50%, -50%)");
8157        assert!(d.is_empty(), "{d:?}");
8158        let t = r.expect("declared");
8159        assert_eq!(
8160            t.translate,
8161            (
8162                TransformLength::Fraction(-0.5),
8163                TransformLength::Fraction(-0.5)
8164            )
8165        );
8166        assert_eq!(TransformLength::Fraction(-0.5).resolve(400.0), -200.0);
8167
8168        let t = transform("transform: translateX(1.25rem)")
8169            .0
8170            .expect("declared");
8171        assert_eq!(
8172            t.translate,
8173            (TransformLength::Pixels(20.0), TransformLength::Pixels(0.0))
8174        );
8175    }
8176
8177    #[test]
8178    fn tailwinds_identity_transform_chain_is_silent() {
8179        let (r, d) = transform(
8180            "transform: translate(-50%, -50%) rotate(0) skewX(0) skewY(0) scaleX(1) scaleY(1)",
8181        );
8182        assert!(d.is_empty(), "{d:?}");
8183        let t = r.expect("declared");
8184        assert_eq!(
8185            t.translate,
8186            (
8187                TransformLength::Fraction(-0.5),
8188                TransformLength::Fraction(-0.5)
8189            )
8190        );
8191        assert_eq!(t.rotate, 0.0);
8192        assert_eq!(t.scale, (1.0, 1.0));
8193    }
8194
8195    #[test]
8196    fn transform_none_is_a_value_not_an_absence() {
8197        let (r, d) = transform("transform: rotate(0deg)");
8198        assert!(d.is_empty(), "{d:?}");
8199        assert_eq!(r, Some(TransformSpec::IDENTITY));
8200        assert!(r.unwrap().is_identity());
8201        assert_eq!(transform("color: red").0, None);
8202    }
8203
8204    #[test]
8205    fn rotate_and_scale_reach_the_computed_value() {
8206        let (r, d) = transform("transform: translateY(4px) rotate(45deg) scale(1.5)");
8207        assert!(d.is_empty(), "{d:?}");
8208        let t = r.expect("declared");
8209        assert_eq!(
8210            t.translate,
8211            (TransformLength::Pixels(0.0), TransformLength::Pixels(4.0))
8212        );
8213        assert!(
8214            (t.rotate - std::f32::consts::FRAC_PI_4).abs() < 1e-5,
8215            "{}",
8216            t.rotate
8217        );
8218        assert_eq!(t.scale, (1.5, 1.5));
8219
8220        let spin = transform("transform: rotate(360deg)").0.expect("declared");
8221        assert!(
8222            (spin.rotate - std::f32::consts::TAU).abs() < 1e-4,
8223            "{}",
8224            spin.rotate
8225        );
8226        assert_eq!(
8227            transform("transform: scaleX(-1)")
8228                .0
8229                .expect("declared")
8230                .scale,
8231            (-1.0, 1.0)
8232        );
8233
8234        let (r, _) = transform("transform: rotateY(30deg) skewX(10deg)");
8235        assert_eq!(r.expect("declared").rotate, 0.0);
8236    }
8237
8238    #[test]
8239    fn every_gradient_shape_becomes_a_background_layer() {
8240        let layers = |body: &str| {
8241            let (_, x, d) = map_full(body);
8242            assert!(d.is_empty(), "{body}: {d:?}");
8243            x.resolve_background_layers()
8244        };
8245        let one = |body: &str| {
8246            let list = layers(body);
8247            assert_eq!(list.len(), 1, "{body}");
8248            list[0]
8249        };
8250
8251        let right = one("background-image: linear-gradient(to right, #ff0000, #0000ff)");
8252        let ninety = one("background: linear-gradient(90deg, #ff0000 0%, #0000ff 100%)");
8253        assert_eq!(
8254            format!("{right:?}"),
8255            format!("{ninety:?}"),
8256            "`to right` is 90deg"
8257        );
8258        let down = one("background-image: linear-gradient(#fff, #000)");
8259        let explicit = one("background-image: linear-gradient(180deg, #fff, #000)");
8260        assert_eq!(
8261            format!("{down:?}"),
8262            format!("{explicit:?}"),
8263            "the default is `to bottom`"
8264        );
8265
8266        assert!(
8267            format!("{:?}", one("background-image: radial-gradient(#fff, #000)"))
8268                .starts_with("RadialGradient")
8269        );
8270        assert!(
8271            format!("{:?}", one("background-image: conic-gradient(#fff, #000)"))
8272                .starts_with("ConicGradient")
8273        );
8274
8275        let three = one("background-image: linear-gradient(#f00, #0f0, #00f)");
8276        assert_eq!(three.live_stops().len(), 3);
8277
8278        let repeating = one("background-image: repeating-linear-gradient(#f00 0px, #00f 10px)");
8279        assert_eq!(repeating.live_stops().len(), 2);
8280        assert_ne!(
8281            format!("{repeating:?}"),
8282            format!(
8283                "{:?}",
8284                one("background-image: linear-gradient(#f00 0px, #00f 10px)")
8285            )
8286        );
8287
8288        let stack =
8289            layers("background-image: linear-gradient(#f00, #f00), linear-gradient(#00f, #00f)");
8290        assert_eq!(stack.len(), 2);
8291    }
8292
8293    #[test]
8294    fn background_size_and_position_tile_the_gradient() {
8295        let (_, x, d) = map_full(
8296            "background-image: linear-gradient(rgba(255,255,255,.02) 1px, transparent 1px),              linear-gradient(90deg, rgba(255,255,255,.02) 1px, transparent 1px);              background-size: 64px 64px",
8297        );
8298        assert!(d.is_empty(), "{d:?}");
8299        let layers = x.resolve_background_layers();
8300        assert_eq!(layers.len(), 2);
8301        for layer in &layers {
8302            assert!(layer.is_tiled(), "{layer:?}");
8303            assert_eq!(layer.live_stops()[0].percentage, 1.0);
8304        }
8305        assert!(format!("{:?}", layers[0]).contains("LinearGradient(90"));
8306
8307        let (_, x, _) = map_full("background-image: linear-gradient(#f00, #00f)");
8308        assert!(!x.resolve_background_layers()[0].is_tiled());
8309    }
8310
8311    #[test]
8312    fn a_url_background_is_carried_with_its_geometry() {
8313        let (r, x, d) = map_full(
8314            "background-image: url(atlas.webp); background-size: 6100% 600%; \
8315             background-position: 45% 20%; background-repeat: no-repeat",
8316        );
8317        assert!(d.is_empty(), "{d:?}");
8318        assert_eq!(r.background, None);
8319        assert_eq!(
8320            x.resolve_background_stack(),
8321            Some(vec![PaintLayer::Image {
8322                url: Rc::from("atlas.webp"),
8323                size: BackgroundSize::Explicit(
8324                    Some(TileLength::Fraction(61.0)),
8325                    Some(TileLength::Fraction(6.0))
8326                ),
8327                position: (TileLength::Fraction(0.45), TileLength::Fraction(0.2)),
8328                repeat: (false, false),
8329            }])
8330        );
8331
8332        let (_, x, _) = map_full(
8333            "background-image: url(\"a.png\"); background-size: 1342px 268px; \
8334             background-position: -88px -44px",
8335        );
8336        let stack = x.resolve_background_stack().unwrap();
8337        let [PaintLayer::Image {
8338            size,
8339            position,
8340            repeat,
8341            ..
8342        }] = stack.as_slice()
8343        else {
8344            panic!("one image layer: {stack:?}");
8345        };
8346        assert_eq!(
8347            *size,
8348            BackgroundSize::Explicit(
8349                Some(TileLength::Pixels(1342.0)),
8350                Some(TileLength::Pixels(268.0))
8351            )
8352        );
8353        assert_eq!(
8354            *position,
8355            (TileLength::Pixels(-88.0), TileLength::Pixels(-44.0))
8356        );
8357        assert_eq!(*repeat, (true, true));
8358        let size_of = |body: &str| match map_full(body).1.resolve_background_stack().unwrap()[0] {
8359            PaintLayer::Image { size, .. } => size,
8360            ref other => panic!("{other:?}"),
8361        };
8362        assert_eq!(
8363            size_of("background: url(b.png) center / cover no-repeat"),
8364            BackgroundSize::Cover
8365        );
8366        assert_eq!(
8367            size_of("background-image: url(b.png); background-size: contain"),
8368            BackgroundSize::Contain
8369        );
8370
8371        let (_, x, _) =
8372            map_full("background-image: linear-gradient(#0008, #0008), url(banner.png)");
8373        let stack = x.resolve_background_stack().unwrap();
8374        assert!(matches!(stack[0], PaintLayer::Image { .. }), "{stack:?}");
8375        assert!(matches!(stack[1], PaintLayer::Gradient(_)), "{stack:?}");
8376
8377        let (_, x, _) = map_full("background-image: linear-gradient(#f00, #00f)");
8378        assert_eq!(x.resolve_background_stack(), None);
8379        assert_eq!(
8380            map_full("background-image: url(\"\")")
8381                .1
8382                .resolve_background_stack(),
8383            None
8384        );
8385    }
8386
8387    #[test]
8388    fn a_later_background_image_replaces_an_earlier_url() {
8389        let (_, mut x, _) = map_full("background-image: url(a.png)");
8390        let (_, later, _) = map_full("background-image: linear-gradient(#f00, #00f)");
8391        x.refine(&later);
8392        assert_eq!(x.resolve_background_stack(), None);
8393        assert_eq!(x.resolve_background_layers().len(), 1);
8394    }
8395
8396    #[test]
8397    fn letter_and_word_spacing_reach_the_text_style() {
8398        assert_eq!(
8399            clean("letter-spacing: 6.3px").text.letter_spacing,
8400            Some(px(6.3))
8401        );
8402        assert_eq!(clean("word-spacing: 2px").text.word_spacing, Some(px(2.0)));
8403        assert_eq!(
8404            clean("letter-spacing: normal").text.letter_spacing,
8405            Some(px(0.0))
8406        );
8407        assert_eq!(
8408            clean("letter-spacing: 0.5em").text.letter_spacing,
8409            Some(px(0.5 * crate::rem_basis()))
8410        );
8411    }
8412
8413    #[test]
8414    fn no_underline_cancels_an_earlier_one() {
8415        let r = clean("text-decoration-line: underline; text-decoration-line: none");
8416        let u = r
8417            .text
8418            .underline
8419            .expect("declared, so it wins over the earlier one");
8420        assert_eq!(u.thickness, px(0.0));
8421        assert_eq!(u.color.map(|c| c.a), Some(0.0));
8422        let strike = r.text.strikethrough.expect("cleared too");
8423        assert_eq!(strike.thickness, px(0.0));
8424    }
8425
8426    #[test]
8427    fn a_declared_line_is_thick_enough_to_paint() {
8428        for css in [
8429            "text-decoration: line-through",
8430            "text-decoration-line: line-through",
8431        ] {
8432            let strike = clean(css).text.strikethrough.expect("declared");
8433            assert!(strike.thickness > px(0.0), "{css}: {strike:?}");
8434        }
8435        for css in [
8436            "text-decoration: underline",
8437            "text-decoration-line: underline",
8438        ] {
8439            let underline = clean(css).text.underline.expect("declared");
8440            assert!(underline.thickness > px(0.0), "{css}: {underline:?}");
8441        }
8442        let strike = clean("text-decoration-line: line-through; text-decoration-thickness: 3px")
8443            .text
8444            .strikethrough
8445            .expect("declared");
8446        assert_eq!(strike.thickness, px(3.0));
8447    }
8448
8449    #[test]
8450    fn underline_offset_lands_on_the_decoration() {
8451        let (r, x, d) = map_full("text-decoration-line: underline; text-underline-offset: 4px");
8452        assert!(d.is_empty(), "{d:?}");
8453        assert_eq!(r.text.underline.expect("declared").offset, px(4.0));
8454        assert_eq!(x.underline_offset, Some(4.0));
8455
8456        let (_, x, d) = map_full("text-underline-offset: 4px");
8457        assert!(d.is_empty(), "{d:?}");
8458        assert_eq!(x.underline_offset, Some(4.0));
8459    }
8460
8461    #[test]
8462    fn font_features_reach_the_shaper_and_axes_do_not() {
8463        let features = clean("font-feature-settings: \"ss01\" 1, \"liga\" 0")
8464            .text
8465            .font_features
8466            .expect("declared");
8467        assert_eq!(
8468            &*features.0,
8469            &[("ss01".into(), 1u32), ("liga".into(), 0u32)]
8470        );
8471
8472        let numeric = clean("font-variant-numeric: tabular-nums")
8473            .text
8474            .font_features
8475            .expect("declared");
8476        assert_eq!(&*numeric.0, &[("tnum".into(), 1u32)]);
8477    }
8478
8479    #[test]
8480    fn kerning_and_ligature_keywords_become_features() {
8481        let features = |css: &str| {
8482            clean(css)
8483                .text
8484                .font_features
8485                .map(|f| (*f.0).clone())
8486                .unwrap_or_default()
8487        };
8488        let pairs = |p: &[(&str, u32)]| -> Vec<(String, u32)> {
8489            p.iter().map(|(t, v)| (t.to_string(), *v)).collect()
8490        };
8491        assert_eq!(features("font-kerning: none"), pairs(&[("kern", 0)]));
8492        assert!(features("font-kerning: auto").is_empty());
8493        assert!(features("font-kerning: normal").is_empty());
8494        assert!(features("font-variant-ligatures: normal").is_empty());
8495        assert_eq!(
8496            features("font-variant-ligatures: none"),
8497            pairs(&[
8498                ("liga", 0),
8499                ("clig", 0),
8500                ("dlig", 0),
8501                ("hlig", 0),
8502                ("calt", 0)
8503            ])
8504        );
8505        assert_eq!(
8506            features("font-variant-ligatures: no-common-ligatures discretionary-ligatures"),
8507            pairs(&[("liga", 0), ("clig", 0), ("dlig", 1)])
8508        );
8509        assert_eq!(
8510            features("font-variant-ligatures: no-contextual"),
8511            pairs(&[("calt", 0)])
8512        );
8513        assert_eq!(
8514            features(
8515                "font-variant-numeric: tabular-nums; font-kerning: none; \
8516                 font-variant-ligatures: no-common-ligatures; font-feature-settings: \"liga\" 1"
8517            ),
8518            pairs(&[("tnum", 1), ("kern", 0), ("liga", 1), ("clig", 0)])
8519        );
8520    }
8521
8522    #[test]
8523    fn font_family_takes_the_first_installed_family() {
8524        let family = |css: &str| clean(css).text.font_family.map(|f| f.to_string());
8525        assert_eq!(
8526            family("font-family: Inter, sans-serif").as_deref(),
8527            Some("Inter")
8528        );
8529
8530        set_font_source(|| vec!["Segoe UI".into(), "Consolas".into(), "Arial".into()]);
8531        assert_eq!(
8532            family("font-family: Inter, \"Segoe UI\", sans-serif").as_deref(),
8533            Some("Segoe UI")
8534        );
8535        assert_eq!(
8536            family(
8537                "font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \
8538                 \"Liberation Mono\", \"Courier New\", monospace"
8539            )
8540            .as_deref(),
8541            Some("Consolas")
8542        );
8543        assert_eq!(
8544            family(
8545                "font-family: ui-sans-serif, system-ui, sans-serif, \"Apple Color Emoji\", \
8546                 \"Segoe UI Emoji\""
8547            )
8548            .as_deref(),
8549            Some(".SystemUIFont")
8550        );
8551        assert_eq!(
8552            family("font-family: monospace").as_deref(),
8553            Some("Consolas")
8554        );
8555        assert_eq!(family("font-family: sans-serif").as_deref(), Some("Arial"));
8556        assert_eq!(
8557            family("font-family: serif").as_deref(),
8558            Some(".SystemUIFont")
8559        );
8560        assert_eq!(
8561            family("font-family: Roboto, Helvetica").as_deref(),
8562            Some("Roboto")
8563        );
8564        let misses = take_font_misses();
8565        assert_eq!(
8566            misses,
8567            vec![
8568                ("Inter".to_string(), Some("Segoe UI".to_string())),
8569                ("Roboto".to_string(), None),
8570            ],
8571            "{misses:?}"
8572        );
8573        assert!(take_font_misses().is_empty());
8574    }
8575
8576    #[test]
8577    fn composed_web_families_hand_gpui_the_rest_of_the_list() {
8578        let font = |css: &str| {
8579            let t = clean(css).text;
8580            (
8581                t.font_family.map(|f| f.to_string()),
8582                t.font_fallbacks.map(|f| f.fallback_list().join("|")),
8583            )
8584        };
8585        set_font_source(|| vec!["Arial".into(), "Mix".into(), "Segoe UI".into()]);
8586        assert_eq!(font("font-family: Mix, Arial"), (Some("Mix".into()), None));
8587
8588        set_composed_font_families([("Mix".to_string(), true), ("SK PUA".to_string(), false)]);
8589        let some = |f: &str, rest: &str| (Some(f.to_string()), Some(rest.to_string()));
8590        assert_eq!(
8591            font("font-family: Mix, \"Segoe UI\", sans-serif"),
8592            some("Mix", "Segoe UI|Arial")
8593        );
8594        assert_eq!(
8595            font("font-family: \"SK PUA\", Nowhere, mix, sans-serif"),
8596            some("SK PUA", "mix|Arial")
8597        );
8598        assert_eq!(
8599            font("font-family: Nowhere, \"SK PUA\", Mix"),
8600            some("SK PUA", "Mix")
8601        );
8602        assert!(take_unreached_fonts().is_empty());
8603        assert_eq!(
8604            font("font-family: Arial, Mix, \"SK PUA\""),
8605            some("Arial", "")
8606        );
8607        assert_eq!(
8608            take_unreached_fonts(),
8609            vec![
8610                ("Mix".to_string(), "Arial".to_string()),
8611                ("SK PUA".to_string(), "Arial".to_string())
8612            ]
8613        );
8614        assert_eq!(font("font-family: Arial"), some("Arial", ""));
8615        assert!(take_unreached_fonts().is_empty());
8616        set_composed_font_families([]);
8617        assert_eq!(font("font-family: Mix"), (Some("Mix".into()), None));
8618    }
8619
8620    #[test]
8621    fn waiting_web_fonts_are_recorded_for_the_host() {
8622        let web = |css: &str| extras(css).0.web_font.map(|f| f.join("|"));
8623        set_font_source(|| vec!["Arial".into(), "SK Half".into()]);
8624        assert_eq!(web("font-family: \"SK Web\", Arial"), None);
8625
8626        set_web_font_families([
8627            "SK Web".to_string(),
8628            "sk half".to_string(),
8629            "SK PUA".to_string(),
8630        ]);
8631        assert_eq!(
8632            web("font-family: \"SK Web\", Arial").as_deref(),
8633            Some("SK Web")
8634        );
8635        assert_eq!(
8636            clean("font-family: \"SK Web\", Arial")
8637                .text
8638                .font_family
8639                .as_deref(),
8640            Some("Arial")
8641        );
8642        assert_eq!(
8643            web("font-family: Nowhere, sk web, sans-serif").as_deref(),
8644            Some("sk web")
8645        );
8646        assert_eq!(
8647            web("font-family: \"SK PUA\", \"SK Web\", serif").as_deref(),
8648            Some("SK PUA|SK Web")
8649        );
8650        assert_eq!(web("font-family: Arial, \"SK Web\"").as_deref(), Some(""));
8651        assert_eq!(
8652            web("font-family: sans-serif, \"SK Web\"").as_deref(),
8653            Some("")
8654        );
8655        assert_eq!(
8656            web("font-family: \"SK Half\", \"SK Web\"").as_deref(),
8657            Some("SK Half")
8658        );
8659        assert_eq!(web("color: red"), None);
8660        set_web_font_families(Vec::new());
8661    }
8662
8663    #[test]
8664    fn the_visually_hidden_clip_idiom_hides_the_box() {
8665        assert_eq!(
8666            clean("clip: rect(0, 0, 0, 0)").visibility,
8667            Some(gpui::Visibility::Hidden)
8668        );
8669        assert_eq!(
8670            clean("clip: rect(0 0 0 0)").visibility,
8671            Some(gpui::Visibility::Hidden)
8672        );
8673        let (r, _) = map("clip: rect(0, 20px, 20px, 0)");
8674        assert_eq!(r.visibility, None);
8675    }
8676
8677    #[test]
8678    fn ordered_markers_count_from_one() {
8679        use crate::ListMarker;
8680        assert_eq!(ListMarker::Disc.render(3).as_deref(), Some("\u{2022}"));
8681        assert_eq!(ListMarker::None.render(3), None);
8682        assert_eq!(ListMarker::Decimal.render(1).as_deref(), Some("1."));
8683        assert_eq!(
8684            ListMarker::DecimalLeadingZero.render(7).as_deref(),
8685            Some("07.")
8686        );
8687        assert_eq!(ListMarker::LowerAlpha.render(1).as_deref(), Some("a."));
8688        assert_eq!(ListMarker::LowerAlpha.render(26).as_deref(), Some("z."));
8689        assert_eq!(ListMarker::LowerAlpha.render(27).as_deref(), Some("aa."));
8690        assert_eq!(ListMarker::UpperAlpha.render(28).as_deref(), Some("AB."));
8691        assert_eq!(ListMarker::LowerRoman.render(4).as_deref(), Some("iv."));
8692        assert_eq!(
8693            ListMarker::UpperRoman.render(1994).as_deref(),
8694            Some("MCMXCIV.")
8695        );
8696    }
8697
8698    #[test]
8699    fn outline_folds_the_shorthand_and_the_longhands_into_one_ring() {
8700        let r = clean("outline: 2px solid #ff0000; outline-offset: 3px");
8701        let o = r.vn_outline.expect("an outline");
8702        assert_eq!(o.width, px(2.0));
8703        assert_eq!(o.offset, px(3.0));
8704        assert_eq!(o.style, gpui::BorderStyle::Solid);
8705        assert!((o.color.a - 1.0).abs() < 1e-3, "{o:?}");
8706
8707        let r = clean("outline: 2px solid #ff0000; outline: none");
8708        assert_eq!(r.vn_outline.unwrap().width, px(0.0));
8709
8710        let r = clean("outline: 2px solid transparent; outline-offset: 2px");
8711        let o = r.vn_outline.unwrap();
8712        assert_eq!(o.width, px(2.0));
8713        assert_eq!(o.color.a, 0.0, "transparent paints nothing");
8714
8715        assert_eq!(
8716            clean("outline-color: #ff0000").vn_outline.unwrap().width,
8717            px(0.0)
8718        );
8719        assert_eq!(
8720            clean("outline-style: solid").vn_outline.unwrap().width,
8721            px(3.0)
8722        );
8723        assert_eq!(
8724            clean("outline-style: dashed").vn_outline.unwrap().style,
8725            gpui::BorderStyle::Dashed
8726        );
8727    }
8728
8729    #[test]
8730    fn box_shadow_carries_every_shadow_with_spread_and_inset() {
8731        let r = clean(
8732            "box-shadow: 0 0 0 2px #ffffff, 0 0 0 4px #3b82f6, inset 0 1px 2px 0 rgb(0 0 0 / 0.4)",
8733        );
8734        let shadows = r.box_shadow.expect("shadows");
8735        assert_eq!(shadows.len(), 3);
8736        assert_eq!(shadows[0].spread_radius, px(2.0));
8737        assert_eq!(shadows[1].spread_radius, px(4.0));
8738        assert!(!shadows[0].inset && !shadows[1].inset);
8739        assert!(shadows[2].inset, "the third is an inset shadow");
8740        assert_eq!(shadows[2].blur_radius, px(2.0));
8741        assert_eq!(shadows[2].offset.y, px(1.0));
8742        let mut d = Vec::new();
8743        let mut r = StyleRefinement::default();
8744        r.box_shadow = Some(vec![gpui::BoxShadow {
8745            color: Hsla::default(),
8746            offset: gpui::point(px(0.0), px(1.0)),
8747            blur_radius: px(2.0),
8748            spread_radius: px(0.0),
8749            inset: false,
8750        }]);
8751        apply_dynamic(
8752            "box-shadow",
8753            "none",
8754            &Vars::default(),
8755            &crate::Env::default(),
8756            &mut r,
8757            &mut Extras::default(),
8758            &mut d,
8759        );
8760        assert_eq!(r.box_shadow, Some(Vec::new()), "{d:?}");
8761        assert!(d.is_empty(), "{d:?}");
8762    }
8763
8764    #[test]
8765    fn text_shadow_keeps_order_offsets_blur_and_current_color() {
8766        let shadows = clean("text-shadow: 1px 2px 3px red, -0.5em 0 #00f, 0 0 4px")
8767            .text
8768            .text_shadow
8769            .expect("text-shadow");
8770        assert_eq!(shadows.len(), 3);
8771        assert_eq!(shadows[0].offset, gpui::point(px(1.0), px(2.0)));
8772        assert_eq!(shadows[0].blur_radius, px(3.0));
8773        assert_eq!(shadows[0].color, Some(gpui::red()));
8774        assert_eq!(
8775            shadows[1].offset.x,
8776            px(-8.0),
8777            "em resolves against the font size"
8778        );
8779        assert_eq!(shadows[1].blur_radius, px(0.0));
8780        assert_eq!(shadows[2].color, None, "an omitted color is currentColor");
8781        for none in ["none", "initial"] {
8782            let mut d = Vec::new();
8783            let mut r = clean("text-shadow: 1px 1px red");
8784            apply_dynamic(
8785                "text-shadow",
8786                none,
8787                &Vars::default(),
8788                &crate::Env::default(),
8789                &mut r,
8790                &mut Extras::default(),
8791                &mut d,
8792            );
8793            assert_eq!(r.text.text_shadow, Some(Vec::new()), "{none}");
8794            assert!(d.is_empty(), "{d:?}");
8795        }
8796        assert_eq!(clean("text-shadow: inherit").text.text_shadow, None);
8797    }
8798
8799    #[test]
8800    fn invalid_text_shadows_drop_the_declaration_and_say_why() {
8801        for body in [
8802            "text-shadow: 1px 1px 2px 3px red",
8803            "text-shadow: 1px 1px -2px red",
8804        ] {
8805            let (r, d) = map(&format!("text-shadow: 4px 4px blue; {body}"));
8806            assert_eq!(
8807                r.text.text_shadow.map(|s| s[0].offset.x),
8808                Some(px(4.0)),
8809                "{body} must not replace the earlier value"
8810            );
8811            assert_eq!(d.len(), 1, "{body}: {d:?}");
8812        }
8813    }
8814
8815    #[test]
8816    fn content_keeps_literal_strings_and_drops_the_rest() {
8817        let (x, d) = extras(r#"content: "->""#);
8818        assert_eq!(x.content.as_deref(), Some("->"));
8819        assert!(d.is_empty(), "{d:?}");
8820        assert_eq!(extras(r#"content: """#).0.content.as_deref(), Some(""));
8821        assert_eq!(extras("content: none").0.content, None);
8822        for body in [
8823            "content: counter(x)",
8824            "content: attr(data-x)",
8825            "content: url(a.png)",
8826        ] {
8827            assert_eq!(extras(body).0.content, None, "{body}");
8828        }
8829    }
8830
8831    #[test]
8832    fn text_transform_rewrites_the_text() {
8833        use crate::mapper::TextTransform as TT;
8834        assert_eq!(TT::Uppercase.apply("Sign in").as_deref(), Some("SIGN IN"));
8835        assert_eq!(TT::Lowercase.apply("Sign In").as_deref(), Some("sign in"));
8836        assert_eq!(
8837            TT::Capitalize.apply("sign iN now").as_deref(),
8838            Some("Sign IN Now")
8839        );
8840        assert_eq!(TT::None.apply("Sign in"), None);
8841    }
8842
8843    #[test]
8844    fn referenced_color_filter_is_replaced_by_later_none_in_one_rule_or_cascade() {
8845        let (mut referenced, diagnostics) = extras("filter:url('#color-matrix')");
8846        assert!(diagnostics.is_empty(), "{diagnostics:?}");
8847        assert_eq!(referenced.filter_url.as_deref(), Some("#color-matrix"));
8848        referenced.refine(&extras("filter:none").0);
8849        assert!(referenced.filter_url.is_none());
8850        assert!(extras("filter:url('#color-matrix'); filter:none")
8851            .0
8852            .filter_url
8853            .is_none());
8854        assert!(extras("filter:drop-shadow(1px 2px red); filter:none")
8855            .0
8856            .drop_shadow
8857            .is_none());
8858    }
8859
8860    #[test]
8861    fn a_blur_is_recorded_even_beside_other_filters() {
8862        let (x, d) = extras("filter: blur(64px)");
8863        assert_eq!(x.blur, Some(64.0));
8864        assert!(
8865            d.is_empty(),
8866            "a lone blur() is implemented, not advised: {d:?}"
8867        );
8868
8869        assert_eq!(extras("filter: none").0.blur, Some(0.0));
8870
8871        assert_eq!(extras("filter: blur(8px)  ").0.blur, Some(8.0));
8872
8873        let (x, _) = extras("filter: blur(4px) grayscale(1)");
8874        assert_eq!(x.blur, Some(4.0), "the blur still lands");
8875    }
8876
8877    #[test]
8878    fn nickname_six_color_and_thirteen_stop_travelling_gradients_keep_every_stop() {
8879        let palette = [0xff3355, 0xffaa00, 0x00ff44, 0x0088ff, 0x9933ff, 0xff55bb];
8880        for travelling in [false, true] {
8881            let colors: Vec<_> = if travelling {
8882                palette
8883                    .iter()
8884                    .chain(palette.iter())
8885                    .chain(palette[..1].iter())
8886                    .copied()
8887                    .collect()
8888            } else {
8889                palette.to_vec()
8890            };
8891            let css = format!("background-image:linear-gradient(90deg,{});background-clip:text;color:transparent;background-size:200% 100%;background-position:-100% 0",
8892                colors.iter().map(|color| format!("#{color:06x}")).collect::<Vec<_>>().join(","));
8893            let (extras, diagnostics) = extras(&css);
8894            assert!(diagnostics.is_empty(), "{diagnostics:?}");
8895            let layers = extras
8896                .background_images
8897                .as_ref()
8898                .expect("gradient brush stack");
8899            for (index, color) in colors.iter().enumerate() {
8900                let expected: Hsla = gpui::rgb(*color).into();
8901                let position = index as f32 / (colors.len() - 1) as f32;
8902                assert!(
8903                    layers
8904                        .iter()
8905                        .flat_map(|layer| layer.background.live_stops())
8906                        .any(|stop| stop.color == expected
8907                            && (stop.percentage - position).abs() < 1e-5),
8908                    "stop {index}/{} must survive transparent-band packing",
8909                    colors.len()
8910                );
8911            }
8912            assert!(layers
8913                .iter()
8914                .all(|layer| layer.background.live_stops().len() <= gpui::GRADIENT_STOPS));
8915            assert_eq!(extras.background_clip_text, Some(true));
8916            assert_eq!(
8917                extras.background_position.as_ref().unwrap()[0].0,
8918                TileLength::Fraction(-1.)
8919            );
8920        }
8921    }
8922
8923    #[test]
8924    fn background_clip_text_records_the_clip_and_background_metadata() {
8925        let (x, _) = extras(
8926            "background-image: linear-gradient(to right, #fbbf24, #eab308); \
8927             background-clip: text; color: transparent",
8928        );
8929        assert_eq!(x.background_clip_text, Some(true));
8930        let key = x
8931            .background_key_color
8932            .expect("a gradient contributes a key colour");
8933        assert!(key.s > 0.8 && key.l > 0.4 && key.l < 0.7, "{key:?}");
8934        assert!(
8935            key.h < 0.15,
8936            "an amber ramp must not average to a cold hue: {key:?}"
8937        );
8938
8939        let (x, _) = extras("background-color: #ff0000; -webkit-background-clip: text");
8940        assert_eq!(x.background_clip_text, Some(true));
8941        assert_eq!(x.background_key_color.map(|c| c.h), Some(0.0));
8942    }
8943
8944    #[test]
8945    fn rem_resolves_against_the_root_font_size() {
8946        assert_eq!(rem_basis(), INITIAL_REM_BASIS);
8947        assert_eq!(
8948            clean("width: 32rem").size.width,
8949            Some(Length::Definite(px(512.0).into()))
8950        );
8951
8952        assert!(set_rem_basis(14.0), "a new basis is a change");
8953        assert!(!set_rem_basis(14.0), "the same basis is not");
8954        assert_eq!(
8955            clean("width: 32rem").size.width,
8956            Some(Length::Definite(px(448.0).into()))
8957        );
8958
8959        // A basis that would silently rescale the whole app is refused, and "the root has no
8960        // font-size yet" is a normal state, not a change.
8961        assert!(!set_rem_basis(0.0));
8962        assert!(!set_rem_basis(f32::NAN));
8963        assert_eq!(rem_basis(), 14.0);
8964
8965        set_rem_basis(INITIAL_REM_BASIS);
8966    }
8967
8968    #[test]
8969    fn ch_and_ex_compile_to_half_an_em_of_the_root() {
8970        let w = |body: &str| clean(body).size.width;
8971        assert_eq!(w("width: 1ch"), Some(Length::Definite(px(8.0).into())));
8972        assert_eq!(w("width: 3ex"), Some(Length::Definite(px(24.0).into())));
8973        assert_eq!(w("width: 2rch"), Some(Length::Definite(px(16.0).into())));
8974        assert_eq!(w("width: 2rex"), Some(Length::Definite(px(16.0).into())));
8975        assert_eq!(
8976            w("width: calc(2ch + 1px)"),
8977            Some(Length::Definite(px(17.0).into()))
8978        );
8979
8980        assert!(set_rem_basis(14.0));
8981        assert_eq!(w("width: 1ch"), Some(Length::Definite(px(7.0).into())));
8982        set_rem_basis(INITIAL_REM_BASIS);
8983    }
8984
8985    #[test]
8986    fn the_css_wide_inherit_keyword_is_a_no_op_rather_than_an_advisory() {
8987        for body in [
8988            "letter-spacing: inherit",
8989            "font-weight: inherit",
8990            "color: inherit",
8991            "font-size: inherit",
8992            "line-height: inherit",
8993        ] {
8994            let (_, d) = map(body);
8995            assert!(d.is_empty(), "{body:?} should be silent, said {d:?}");
8996        }
8997    }
8998
8999    #[test]
9000    fn border_radius_inherit_is_recorded_per_corner() {
9001        let inherit = |name: &str| {
9002            let (mut r, mut x, mut d) = (StyleRefinement::default(), Extras::default(), Vec::new());
9003            apply_dynamic(
9004                name,
9005                "inherit",
9006                &Vars::default(),
9007                &crate::Env::default(),
9008                &mut r,
9009                &mut x,
9010                &mut d,
9011            );
9012            assert!(d.is_empty(), "{name}: {d:?}");
9013            (r, x)
9014        };
9015        let (r, x) = inherit("border-radius");
9016        assert_eq!(
9017            x.radius_inherit,
9018            RadiusInherit {
9019                declared: 15,
9020                inherit: 15
9021            }
9022        );
9023        assert_eq!(
9024            r.corner_radii.top_left, None,
9025            "nothing to write until the parent is known"
9026        );
9027        let (_, x) = inherit("border-bottom-left-radius");
9028        let bl = RadiusInherit::BOTTOM_LEFT;
9029        assert_eq!(
9030            x.radius_inherit,
9031            RadiusInherit {
9032                declared: bl,
9033                inherit: bl
9034            }
9035        );
9036        assert_eq!(inherit("color").1.radius_inherit, RadiusInherit::default());
9037
9038        let (_, x, d) = map_full("border-radius: 4px; border-top-left-radius: 50%");
9039        assert!(d.is_empty(), "{d:?}");
9040        assert_eq!(
9041            x.radius_inherit,
9042            RadiusInherit {
9043                declared: 15,
9044                inherit: 0
9045            }
9046        );
9047        let mut folded = inherit("border-radius").1;
9048        folded.refine(&map_full("border-top-right-radius: 2px").1);
9049        assert_eq!(
9050            folded.radius_inherit.inherit,
9051            RadiusInherit::ALL & !RadiusInherit::TOP_RIGHT
9052        );
9053        folded.refine(&inherit("border-top-right-radius").1);
9054        assert_eq!(folded.radius_inherit.inherit, RadiusInherit::ALL);
9055    }
9056
9057    #[test]
9058    fn a_property_with_no_divergence_says_nothing() {
9059        for body in [
9060            "user-select: none",
9061            "user-select: text",
9062            "user-select: auto",
9063            "user-select: all",
9064            "appearance: none",
9065            "appearance: textfield",
9066            "tab-size: 4",
9067            "text-size-adjust: 100%",
9068            "touch-action: none",
9069            "-webkit-font-smoothing: antialiased",
9070            "-webkit-box-orient: vertical",
9071            "vertical-align: baseline",
9072            "text-indent: 0",
9073            "resize: none",
9074            "overflow-wrap: normal",
9075            "word-break: normal",
9076            "overflow-wrap: break-word",
9077            "overflow-wrap: anywhere",
9078            "word-wrap: break-word",
9079            "word-break: break-all",
9080            "word-break: keep-all",
9081            "word-break: break-word",
9082            "hyphens: manual",
9083            "hyphens: none",
9084            "list-style: none",
9085            "list-style-type: none",
9086            "list-style-type: disc",
9087            "list-style: decimal inside",
9088            "list-style-position: inside",
9089            "text-decoration-color: #f00",
9090            "visibility: collapse",
9091            "letter-spacing: 0.05em",
9092            "word-spacing: 2px",
9093            "font-variant-numeric: tabular-nums",
9094            "font-feature-settings: \"ss01\" 1, \"liga\" 0",
9095            "font-feature-settings: normal",
9096            "font-kerning: none",
9097            "font-kerning: auto",
9098            "font-variant-ligatures: no-common-ligatures",
9099            "font-variant-ligatures: normal",
9100            "font-variation-settings: normal",
9101            "font-optical-sizing: auto",
9102            "text-underline-offset: 4px",
9103            "text-decoration-skip-ink: none",
9104            "clip: rect(0, 0, 0, 0)",
9105            "scroll-margin-top: 4rem",
9106            "scroll-padding: 1rem",
9107            "background-size: cover",
9108            "background-image: linear-gradient(#f00, #00f); background-size: 64px 64px",
9109            "background-repeat: no-repeat",
9110            "background-position: center",
9111            "background-image: radial-gradient(circle at 30% 40%, #fff, #000)",
9112            "background-image: conic-gradient(from 45deg, #f00, #0f0, #00f)",
9113            "background-image: repeating-linear-gradient(45deg, #f00 0 10px, #00f 10px 20px)",
9114            "background-image: linear-gradient(to bottom right, #f00, #0f0, #00f, #ff0)",
9115        ] {
9116            let (_, d) = map(body);
9117            assert!(d.is_empty(), "{body:?} should be silent, said {d:?}");
9118        }
9119    }
9120
9121    #[test]
9122    fn per_side_border_colours_are_independent_and_silent() {
9123        let (r, diagnostics) = map("border-top: 1px solid #ff0000; border-left-color: #00ff00");
9124        assert_eq!(r.border_widths.top, Some(px(1.0).into()));
9125        assert_eq!(r.border_widths.bottom, None);
9126        assert_eq!(
9127            r.vn_border_colors.top,
9128            Some(Some(gpui::rgb(0xff0000).into()))
9129        );
9130        assert_eq!(
9131            r.vn_border_colors.left,
9132            Some(Some(gpui::rgb(0x00ff00).into()))
9133        );
9134        assert_eq!(r.vn_border_colors.right, None);
9135        assert!(diagnostics.is_empty(), "{diagnostics:?}");
9136    }
9137
9138    #[test]
9139    fn border_color_shorthand_retains_four_colours_and_resets_side_overrides() {
9140        let (r, diagnostics) = map("border-color: red green blue transparent");
9141        assert_eq!(
9142            r.vn_border_colors.top,
9143            Some(Some(gpui::rgb(0xff0000).into()))
9144        );
9145        assert_eq!(
9146            r.vn_border_colors.right,
9147            Some(Some(gpui::rgb(0x008000).into()))
9148        );
9149        assert_eq!(
9150            r.vn_border_colors.bottom,
9151            Some(Some(gpui::rgb(0x0000ff).into()))
9152        );
9153        assert!(r
9154            .vn_border_colors
9155            .left
9156            .flatten()
9157            .is_some_and(|c| c.is_transparent()));
9158        assert!(diagnostics.is_empty(), "{diagnostics:?}");
9159        let (r, diagnostics) = map("border-left-color: blue; border-color: red");
9160        assert_eq!(
9161            r.vn_border_colors.left,
9162            Some(Some(gpui::rgb(0xff0000).into()))
9163        );
9164        assert!(diagnostics.is_empty(), "{diagnostics:?}");
9165    }
9166
9167    #[test]
9168    fn scrollbar_color_accepts_functional_colours() {
9169        for body in [
9170            "scrollbar-color: hsl(240 5% 64% / 0.35) transparent",
9171            "scrollbar-color: rgba(128, 24, 255, 0.5) #0000",
9172            "scrollbar-color: hsl(0 0% 10%) transparent",
9173        ] {
9174            let (_, extras, diagnostics) = map_full(body);
9175            assert!(extras.scrollbar_color.is_some(), "{body}: {diagnostics:?}");
9176            assert!(diagnostics.is_empty(), "{body}: {diagnostics:?}");
9177        }
9178    }
9179
9180    #[test]
9181    fn transform_origin_survives_beside_the_transform() {
9182        let spec = transform("transform-origin: left top; transform: rotate(45deg)")
9183            .0
9184            .expect("declared");
9185        assert_eq!(
9186            spec.origin,
9187            (
9188                TransformLength::Fraction(0.0),
9189                TransformLength::Fraction(0.0)
9190            )
9191        );
9192        let spec = transform("transform: rotate(45deg); transform-origin: 100% 0")
9193            .0
9194            .expect("declared");
9195        assert_eq!(
9196            spec.origin,
9197            (TransformLength::Fraction(1.0), TransformLength::Pixels(0.0))
9198        );
9199        assert_eq!(
9200            transform("transform: scale(2)").0.unwrap().origin,
9201            TransformSpec::CENTRE_ORIGIN
9202        );
9203        let alone = transform("transform-origin: left top").0.expect("declared");
9204        assert!(alone.is_identity(), "an origin alone transforms nothing");
9205    }
9206
9207    #[test]
9208    fn a_corner_transform_origin_pins_that_corner() {
9209        use gpui::{Bounds, Point, Size};
9210        let bounds = Bounds {
9211            origin: Point {
9212                x: px(100.0),
9213                y: px(50.0),
9214            },
9215            size: Size {
9216                width: px(200.0),
9217                height: px(100.0),
9218            },
9219        };
9220        let spec = transform("transform-origin: left top; transform: scale(2)")
9221            .0
9222            .expect("declared");
9223        let m = spec.to_matrix(bounds, 1.0);
9224        let pinned = m.apply(bounds.origin);
9225        assert!((f32::from(pinned.x) - 100.0).abs() < 1e-3, "{pinned:?}");
9226        assert!((f32::from(pinned.y) - 50.0).abs() < 1e-3, "{pinned:?}");
9227        let far = m.apply(Point {
9228            x: px(300.0),
9229            y: px(150.0),
9230        });
9231        assert!((f32::from(far.x) - 500.0).abs() < 1e-3, "{far:?}");
9232        assert!((f32::from(far.y) - 250.0).abs() < 1e-3, "{far:?}");
9233    }
9234
9235    #[test]
9236    fn a_matrix_decomposes_into_translate_rotate_scale() {
9237        let spec = transform("transform: matrix(2, 0, 0, 2, 10, 20)")
9238            .0
9239            .expect("declared");
9240        assert_eq!(
9241            spec.translate,
9242            (TransformLength::Pixels(10.0), TransformLength::Pixels(20.0))
9243        );
9244        assert!((spec.scale.0 - 2.0).abs() < 1e-4, "{spec:?}");
9245        assert!((spec.scale.1 - 2.0).abs() < 1e-4, "{spec:?}");
9246        assert!(spec.rotate.abs() < 1e-4, "{spec:?}");
9247        let spec = transform("transform: matrix(0, 1, -1, 0, 0, 0)")
9248            .0
9249            .expect("declared");
9250        assert!(
9251            (spec.rotate - std::f32::consts::FRAC_PI_2).abs() < 1e-4,
9252            "{spec:?}"
9253        );
9254        assert!((spec.scale.0 - 1.0).abs() < 1e-4 && (spec.scale.1 - 1.0).abs() < 1e-4);
9255        let (_, d) = map("transform: matrix(1, 0, 0.5, 1, 0, 0)");
9256        assert!(d.is_empty(), "{d:?}");
9257    }
9258
9259    #[test]
9260    fn finite_affine_matrices_keep_every_coefficient_including_singular_ones() {
9261        use gpui::{Bounds, Point, Size};
9262        let bounds = Bounds {
9263            origin: Point::new(px(100.0), px(50.0)),
9264            size: Size::new(px(200.0), px(100.0)),
9265        };
9266        for [a, b, c, d, e, f] in [
9267            [1.0, 0.25, 0.5, 1.0, 10.0, 20.0],
9268            [-2.0, 0.0, 0.5, 3.0, -10.0, 4.0],
9269            [0.0, 0.0, 2.0, 3.0, 0.0, 0.0],
9270            [1.0, 2.0, 2.0, 4.0, 0.0, 0.0],
9271            [0.0; 6],
9272        ] {
9273            let (spec, diagnostics) = transform(&format!(
9274                "transform-origin:0 0; transform:matrix({a},{b},{c},{d},{e},{f})"
9275            ));
9276            assert!(diagnostics.is_empty(), "{diagnostics:?}");
9277            let matrix = spec.unwrap().to_matrix(bounds, 1.0);
9278            for (x, y) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (30.0, -17.0)] {
9279                let point = matrix.apply(Point::new(px(100.0 + x), px(50.0 + y)));
9280                assert!(
9281                    (f32::from(point.x) - (100.0 + a * x + c * y + e)).abs() < 0.001,
9282                    "{matrix:?} {point:?}"
9283                );
9284                assert!(
9285                    (f32::from(point.y) - (50.0 + b * x + d * y + f)).abs() < 0.001,
9286                    "{matrix:?} {point:?}"
9287                );
9288            }
9289        }
9290    }
9291
9292    #[test]
9293    fn projected_editor_matrix_preserves_centring_and_post_rotation_scale() {
9294        use gpui::{Bounds, Point, Size};
9295        let bounds = Bounds {
9296            origin: Point::new(px(0.0), px(0.0)),
9297            size: Size::new(px(200.0), px(100.0)),
9298        };
9299        let (spec, diagnostics) = transform(
9300            "transform:translate(-50%,-50%) matrix(1,.25,.5,1,0,0) rotate(90deg) scale(2,3)",
9301        );
9302        assert!(diagnostics.is_empty(), "{diagnostics:?}");
9303        let spec = spec.unwrap();
9304        assert!(spec.translation_basis.is_none());
9305        let matrix = spec.to_matrix(bounds, 1.0);
9306        for (x, y, ex, ey) in [
9307            (100.0, 50.0, 0.0, 0.0),
9308            (101.0, 50.0, 1.0, 2.0),
9309            (100.0, 51.0, -3.0, -0.75),
9310        ] {
9311            let point = matrix.apply(Point::new(px(x), px(y)));
9312            assert!(
9313                (f32::from(point.x) - ex).abs() < 0.001 && (f32::from(point.y) - ey).abs() < 0.001,
9314                "{point:?} vs {ex},{ey}"
9315            );
9316        }
9317    }
9318
9319    #[test]
9320    fn ordered_translation_can_mix_pixels_and_both_box_axes_at_any_dpi() {
9321        use gpui::{Bounds, Point, Size};
9322        let bounds = Bounds {
9323            origin: Point::new(px(0.0), px(0.0)),
9324            size: Size::new(px(200.0), px(100.0)),
9325        };
9326        for (css, x, y) in [
9327            ("rotate(90deg) translate(50%,25%)", -25.0, 100.0),
9328            ("translate(-50%,25%) matrix(1,0,0,1,10,-4)", -90.0, 21.0),
9329            ("matrix(1,.25,.5,1,10,20) translate(8px,4px)", 20.0, 26.0),
9330        ] {
9331            let (spec, diagnostics) = transform(&format!("transform-origin:0 0; transform:{css}"));
9332            assert!(diagnostics.is_empty(), "{diagnostics:?}");
9333            for dpi in [1.0, 2.0] {
9334                let point = spec
9335                    .unwrap()
9336                    .to_matrix(bounds, dpi)
9337                    .apply(Point::new(px(0.0), px(0.0)));
9338                assert!(
9339                    (f32::from(point.x) - x * dpi).abs() < 0.001
9340                        && (f32::from(point.y) - y * dpi).abs() < 0.001,
9341                    "{css}: {point:?}"
9342                );
9343            }
9344        }
9345    }
9346
9347    #[test]
9348    fn shear_and_mixed_translation_survive_cssom_and_waapi_serialization() {
9349        use gpui::{Bounds, Point, Size};
9350        let bounds = Bounds {
9351            origin: Point::new(px(0.0), px(0.0)),
9352            size: Size::new(px(200.0), px(100.0)),
9353        };
9354        for css in [
9355            "matrix(1,.25,.5,1,10,20)",
9356            "rotate(90deg) translate(50%,25%) skewX(20deg)",
9357            "translate(-50%,25%) matrix(1,0,.5,1,10,-4)",
9358        ] {
9359            let original = transform(&format!("transform:{css}")).0.unwrap();
9360            let text = transform_css(original);
9361            let replayed = transform(&format!("transform:{text}")).0.unwrap();
9362            for (x, y) in [(0.0, 0.0), (20.0, 30.0), (200.0, 100.0)] {
9363                let p = Point::new(px(x), px(y));
9364                let a = original.to_matrix(bounds, 1.0).apply(p);
9365                let b = replayed.to_matrix(bounds, 1.0).apply(p);
9366                assert!(
9367                    (f32::from(a.x) - f32::from(b.x)).abs() < 0.001
9368                        && (f32::from(a.y) - f32::from(b.y)).abs() < 0.001,
9369                    "{css} -> {text}: {a:?} vs {b:?}"
9370                );
9371            }
9372        }
9373        let spin = transform("transform:rotate(360deg) skew(0deg,0deg)")
9374            .0
9375            .unwrap();
9376        assert!(
9377            (TransformSpec::IDENTITY.interpolate(spin, 0.5).rotate - std::f32::consts::PI).abs()
9378                < 0.0001
9379        );
9380        let shear = transform("transform:matrix(1,0,1,1,0,0)").0.unwrap();
9381        assert!((TransformSpec::IDENTITY.interpolate(shear, 0.5).shear - 0.5).abs() < 0.0001);
9382    }
9383
9384    #[test]
9385    fn the_matrix_turns_about_the_box_centre() {
9386        use gpui::{Bounds, Point, Size};
9387        let bounds = Bounds {
9388            origin: Point {
9389                x: px(100.0),
9390                y: px(50.0),
9391            },
9392            size: Size {
9393                width: px(200.0),
9394                height: px(100.0),
9395            },
9396        };
9397        let quarter = transform("transform: rotate(90deg)").0.expect("declared");
9398        let m = quarter.to_matrix(bounds, 1.0);
9399        let centre = m.apply(bounds.center());
9400        assert!((f32::from(centre.x) - 200.0).abs() < 1e-3, "{centre:?}");
9401        assert!((f32::from(centre.y) - 100.0).abs() < 1e-3, "{centre:?}");
9402        let corner = m.apply(bounds.origin);
9403        assert!((f32::from(corner.x) - 250.0).abs() < 1e-3, "{corner:?}");
9404        assert!(f32::from(corner.y).abs() < 1e-3, "{corner:?}");
9405
9406        let half = transform("transform: translate(-50%, -50%)")
9407            .0
9408            .expect("declared");
9409        let m = half.to_matrix(bounds, 1.0);
9410        let moved = m.apply(bounds.origin);
9411        assert!((f32::from(moved.x) - 0.0).abs() < 1e-3, "{moved:?}");
9412        assert!((f32::from(moved.y) - 0.0).abs() < 1e-3, "{moved:?}");
9413    }
9414
9415    #[test]
9416    fn svg_paint_keeps_the_concrete_colour() {
9417        assert_eq!(extras("fill: none").0.fill, Some(SvgPaint::None));
9418        assert_eq!(extras("fill: currentColor").0.fill, Some(SvgPaint::Current));
9419        let red = extras("fill: #ff0000").0.fill;
9420        assert!(matches!(red, Some(SvgPaint::Color(_))), "{red:?}");
9421        assert_eq!(red.unwrap().as_attr(), "rgb(255,0,0)");
9422        let faint = extras("stroke: rgba(219, 232, 255, 0.17)")
9423            .0
9424            .stroke
9425            .expect("declared");
9426        assert_eq!(faint.as_attr(), "rgba(219,232,255,0.169)");
9427        assert_eq!(
9428            extras("stroke: currentColor").0.stroke,
9429            Some(SvgPaint::Current)
9430        );
9431        assert_eq!(SvgPaint::None.as_attr(), "none");
9432        assert_eq!(extras("fill: url(#g)").0.fill, Some(SvgPaint::Server));
9433        assert_eq!(SvgPaint::Server.as_attr(), "currentColor");
9434        assert_eq!(extras("color: red").0.fill, None);
9435    }
9436
9437    #[test]
9438    fn svg_presentation_properties_travel_as_text_and_merge_per_name() {
9439        let (x, d) = extras(
9440            "fill: none; stroke: currentColor; stroke-opacity: 0.28; stroke-width: 1; \
9441             shape-rendering: crispEdges",
9442        );
9443        assert!(d.is_empty(), "{d:?}");
9444        let list = x.svg_presentation.clone().expect("carried");
9445        let get = |l: &[(&'static str, Rc<str>)], n: &str| {
9446            l.iter().find(|(k, _)| *k == n).map(|(_, v)| v.to_string())
9447        };
9448        assert_eq!(get(&list, "stroke-opacity").as_deref(), Some(".28")); // lightningcss's minified text, a valid SVG <number>
9449        assert_eq!(get(&list, "stroke-width").as_deref(), Some("1px"));
9450        assert_eq!(get(&list, "shape-rendering").as_deref(), Some("crispEdges"));
9451        let (dash, d) = extras("stroke-dasharray: 5 5; stroke-dashoffset: 10px");
9452        assert!(d.is_empty(), "{d:?}");
9453        assert_eq!(dash.svg_presentation.as_ref().map(|l| l.len()), Some(2));
9454        let mut merged = x.clone();
9455        merged.refine(&extras("stroke-width: 2").0);
9456        let list = merged.svg_presentation.expect("merged");
9457        assert_eq!(get(&list, "stroke-width").as_deref(), Some("2px"));
9458        assert_eq!(get(&list, "stroke-opacity").as_deref(), Some(".28"));
9459    }
9460
9461    #[test]
9462    fn logical_margin_padding_and_inset_are_their_physical_sides() {
9463        let r = clean(
9464            "margin-inline: auto; margin-block: 2px 4px; padding-inline: 6px 8px; \
9465             padding-block-start: 10px; padding-block-end: 12px; inset-inline: 0 -22px; \
9466             inset-block-start: 3px; inset-block-end: 5%",
9467        );
9468        assert_eq!(r.margin.left, Some(Length::Auto));
9469        assert_eq!(r.margin.right, Some(Length::Auto));
9470        assert_eq!(r.margin.top, Some(px(2.0).into()));
9471        assert_eq!(r.margin.bottom, Some(px(4.0).into()));
9472        assert_eq!(r.padding.left, Some(px(6.0).into()));
9473        assert_eq!(r.padding.right, Some(px(8.0).into()));
9474        assert_eq!(r.padding.top, Some(px(10.0).into()));
9475        assert_eq!(r.padding.bottom, Some(px(12.0).into()));
9476        assert_eq!(r.inset.left, Some(px(0.0).into()));
9477        assert_eq!(r.inset.right, Some(px(-22.0).into()));
9478        assert_eq!(r.inset.top, Some(px(3.0).into()));
9479        assert_eq!(r.inset.bottom, Some(gpui::relative(0.05).into()));
9480
9481        let later = |body: &str| clean(body).margin.left;
9482        assert_eq!(
9483            later("margin-left: 3px; margin-inline-start: 5px"),
9484            Some(px(5.0).into())
9485        );
9486        assert_eq!(
9487            later("margin-inline-start: 5px; margin-left: 3px"),
9488            Some(px(3.0).into())
9489        );
9490        assert_eq!(
9491            clean("margin: 1px; margin-inline-end: 9px").margin.right,
9492            Some(px(9.0).into())
9493        );
9494    }
9495
9496    #[test]
9497    fn the_demo_cards_utilities_all_render() {
9498        let r = clean(
9499            "display: flex; flex-direction: column; gap: 0.5rem; padding: 1rem; \
9500             border-radius: 0.75rem; background-color: rgb(255 255 255 / 0.1); \
9501             font-size: 0.875rem; line-height: 1.25rem; font-weight: 600",
9502        );
9503        assert_eq!(r.display, Some(gpui::Display::Flex));
9504        assert_eq!(r.flex_direction, Some(gpui::FlexDirection::Column));
9505        assert_eq!(r.gap.width, Some(px(8.0).into()));
9506        assert_eq!(r.gap.height, Some(px(8.0).into()));
9507        assert_eq!(r.padding.top, Some(px(16.0).into()));
9508        assert_eq!(r.corner_radii.top_left, Some(px(12.0).into()));
9509        assert_eq!(r.text.font_size, Some(px(14.0).into()));
9510        assert_eq!(r.text.font_weight, Some(gpui::FontWeight(600.0)));
9511        assert!(matches!(r.background, Some(gpui::Fill::Color(_))));
9512    }
9513
9514    #[test]
9515    fn drop_shadow_parses_into_extras_and_says_nothing() {
9516        let (_, x, d) = map_full("filter: drop-shadow(2px 4px 6px rgb(0 0 0 / 0.5))");
9517        assert!(
9518            d.is_empty(),
9519            "the shape gpui can draw exactly must not advise: {d:?}"
9520        );
9521        let s = x.drop_shadow.expect("drop-shadow() reached Extras");
9522        assert_eq!((s.dx, s.dy, s.blur), (2.0, 4.0, 6.0));
9523        assert!(s.color.is_some(), "an explicit colour is flattened here");
9524
9525        // No colour argument is `currentColor`, which only the renderer can resolve — so the mapper
9526        // records `None` rather than guessing black.
9527        let (_, x, d) = map_full("filter: drop-shadow(1px 2px 3px)");
9528        assert!(d.is_empty(), "{d:?}");
9529        assert_eq!(x.drop_shadow.map(|s| s.color), Some(None));
9530
9531        let (_, x, _) =
9532            map_full("filter: drop-shadow(1px 1px 1px red) drop-shadow(2px 2px 2px blue)");
9533        assert!(x.drop_shadow.is_some(), "the first one is still honoured");
9534    }
9535
9536    #[test]
9537    fn the_gradient_border_mask_is_a_ring_and_others_are_not() {
9538        let ring = "-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
9539                    mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
9540                    -webkit-mask-composite: xor;
9541                    mask-composite: exclude";
9542        let (_, x, d) = map_full(ring);
9543        assert!(d.is_empty(), "{d:?}");
9544        assert!(x.mask_ring());
9545        for composite in [
9546            "-webkit-mask-composite: xor",
9547            "-webkit-mask-composite: destination-out",
9548        ] {
9549            let (_, x, d) = map_full(&format!(
9550                "mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); {composite}"
9551            ));
9552            assert!(d.is_empty() && x.mask_ring(), "{composite}: {d:?}");
9553        }
9554        let (_, x, d) =
9555            map_full("mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)");
9556        assert!(d.is_empty(), "{d:?}");
9557        assert!(!x.mask_ring());
9558        let (_, x, d) = map_full(
9559            "mask-image: linear-gradient(red, blue), linear-gradient(#fff 0 0);
9560             mask-clip: content-box, border-box; mask-composite: exclude",
9561        );
9562        assert!(d.is_empty() && x.mask_ring(), "{d:?}");
9563        // A shorthand AFTER the composite resets it to `add`.
9564        let (_, x, _) = map_full(&format!(
9565            "{ring}; mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)"
9566        ));
9567        assert!(!x.mask_ring());
9568
9569        for other in [
9570            "mask-image: linear-gradient(to right, black 90%, transparent)",
9571            "mask-image: url(icon.svg)",
9572            "mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); mask-composite: intersect",
9573        ] {
9574            assert!(!map_full(other).1.mask_ring(), "{other}");
9575        }
9576        let (_, x, d) = map_full("mask: none");
9577        assert!(d.is_empty() && !x.mask_ring(), "{d:?}");
9578    }
9579
9580    #[test]
9581    fn a_mask_resolves_to_layers_with_their_size_position_and_repeat() {
9582        use TileLength::{Fraction as F, Pixels as P};
9583        let (_, x, d) = map_full(
9584            "mask-image: url(icons/check.svg); mask-size: contain; mask-repeat: no-repeat;
9585             mask-position: center",
9586        );
9587        assert!(d.is_empty(), "{d:?}");
9588        let stack = x.resolve_mask_stack().expect("a mask");
9589        assert!(!stack.luminance);
9590        assert_eq!(
9591            stack.layers,
9592            vec![PaintLayer::Image {
9593                url: "icons/check.svg".into(),
9594                size: BackgroundSize::Contain,
9595                position: (F(0.5), F(0.5)),
9596                repeat: (false, false),
9597            }]
9598        );
9599
9600        // The shorthand, two layers, the first on top; a gradient with a size is tiled.
9601        let (_, x, d) = map_full(
9602            "mask: url(a.png) 4px 0 / 10px 20px repeat-x, \
9603             linear-gradient(to bottom, #000 80%, transparent) luminance",
9604        );
9605        assert!(d.iter().any(|d| d.contains("mask-mode")), "{d:?}");
9606        let stack = x.resolve_mask_stack().expect("a mask");
9607        let [PaintLayer::Gradient(_), PaintLayer::Image {
9608            size,
9609            position,
9610            repeat,
9611            ..
9612        }] = stack.layers.as_slice()
9613        else {
9614            panic!("{:?}", stack.layers)
9615        };
9616        assert_eq!(*size, BackgroundSize::Explicit(Some(P(10.)), Some(P(20.))));
9617        assert_eq!(*position, (P(4.), P(0.)));
9618        assert_eq!(*repeat, (true, false));
9619
9620        let (_, x, _) = map_full("mask-image: url(a.svg); mask-image: none");
9621        assert_eq!(x.resolve_mask_stack(), None);
9622        let (_, x, _) =
9623            map_full("mask-image: linear-gradient(#000, transparent); mask-mode: luminance");
9624        assert!(x.resolve_mask_stack().expect("a mask").luminance);
9625    }
9626
9627    #[test]
9628    fn a_webkit_mask_is_ignored_and_the_ring_still_cuts() {
9629        for prefixed in [
9630            "-webkit-mask-image: url(icon.svg)",
9631            "-webkit-mask: url(icon.svg) center / contain no-repeat",
9632        ] {
9633            let (_, x, d) = map_full(prefixed);
9634            assert_eq!(x.resolve_mask_stack(), None, "{prefixed}");
9635            assert_eq!(d.len(), 1, "{prefixed}: {d:?}");
9636        }
9637        let (_, x, _) =
9638            map_full("mask-image: url(icon.svg); -webkit-mask-position: 0 0; mask-position: right");
9639        let stack = x.resolve_mask_stack().expect("a mask");
9640        assert!(
9641            matches!(stack.layers[0], PaintLayer::Image { position: (TileLength::Fraction(f), _), .. } if f == 1.0),
9642            "{stack:?}"
9643        );
9644        let ring = "-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
9645                    -webkit-mask-composite: xor";
9646        let (_, x, d) = map_full(ring);
9647        assert!(d.is_empty() && x.mask_ring(), "{d:?}");
9648        assert_eq!(x.resolve_mask_stack(), None);
9649    }
9650
9651    #[test]
9652    fn clip_path_is_a_rounded_mask_and_the_other_shapes_are_dropped() {
9653        use gpui::{VnClipBox as B, VnClipPath as C, VnCornerRadius, VnShapeRadius as R};
9654        let at = |x: f32, y: f32| VnCornerRadius {
9655            x: px(x).into(),
9656            y: px(y).into(),
9657        };
9658        let half = relative(0.5);
9659        for sr_only in ["clip-path: inset(50%)", "clip-path: inset(50% 50% 50% 50%)"] {
9660            let r = clean(sr_only);
9661            assert_eq!(r.visibility, None, "{sr_only}");
9662            assert_eq!(
9663                r.vn_clip_path,
9664                Some(C::Inset {
9665                    reference: B::Border,
9666                    insets: [half; 4],
9667                    radii: [at(0., 0.); 4]
9668                }),
9669                "{sr_only}"
9670            );
9671        }
9672        assert_eq!(
9673            clean("clip-path: inset(10px 20% round 8px 8px 8px 4px / 8px 8px 8px 6px) padding-box")
9674                .vn_clip_path,
9675            Some(C::Inset {
9676                reference: B::Padding,
9677                insets: [px(10.).into(), relative(0.2), px(10.).into(), relative(0.2)],
9678                radii: [at(8., 8.), at(8., 8.), at(8., 8.), at(4., 6.)],
9679            })
9680        );
9681        assert_eq!(
9682            clean("clip-path: circle(40%)").vn_clip_path,
9683            Some(C::Ellipse {
9684                reference: B::Border,
9685                center: [half, half],
9686                radius: [R::Length(relative(0.4)); 2],
9687                circle: true,
9688            })
9689        );
9690        assert_eq!(
9691            clean("clip-path: circle(at right 10px top) content-box").vn_clip_path,
9692            Some(C::Ellipse {
9693                reference: B::Content,
9694                center: [
9695                    DefiniteLength::Calc {
9696                        fraction: 1.0,
9697                        pixels: px(-10.)
9698                    },
9699                    relative(0.)
9700                ],
9701                radius: [R::ClosestSide; 2],
9702                circle: true,
9703            })
9704        );
9705        assert_eq!(
9706            clean("clip-path: ellipse(30% farthest-side at 25% 75%)").vn_clip_path,
9707            Some(C::Ellipse {
9708                reference: B::Border,
9709                center: [relative(0.25), relative(0.75)],
9710                radius: [R::Length(relative(0.3)), R::FarthestSide],
9711                circle: false,
9712            })
9713        );
9714        assert!(clean("clip-path: ellipse(20px 20px)")
9715            .vn_clip_path
9716            .is_some());
9717        assert_eq!(
9718            clean("clip-path: margin-box").vn_clip_path,
9719            Some(C::Box(B::Margin))
9720        );
9721        assert_eq!(
9722            clean("clip-path: fill-box").vn_clip_path,
9723            Some(C::Box(B::Content))
9724        );
9725        assert_eq!(
9726            clean("clip-path: stroke-box").vn_clip_path,
9727            Some(C::Box(B::Border))
9728        );
9729        for other in [
9730            "url(#c)",
9731            "rect(0 10px 10px 0)",
9732            "xywh(0 0 10px 10px)",
9733            "shape(from 0 0, line to 10px 10px)",
9734        ] {
9735            let (r, _) = map(&format!("clip-path: {other}"));
9736            assert_eq!(r.vn_clip_path, None, "{other}");
9737        }
9738        let r = clean("clip-path: none");
9739        assert_eq!((r.vn_clip_path, r.visibility), (Some(C::None), None));
9740    }
9741
9742    #[test]
9743    fn clip_path_polygon_and_path_are_shapes() {
9744        use gpui::{VnClipBox as B, VnClipPath as C, VnFillRule as F, VnPathVerb::*};
9745        let polygon = |r: &StyleRefinement| match &r.vn_clip_path {
9746            Some(C::Polygon {
9747                reference,
9748                fill_rule,
9749                points,
9750            }) => (*reference, *fill_rule, points.to_vec()),
9751            other => panic!("{other:?}"),
9752        };
9753        assert_eq!(
9754            polygon(&clean("clip-path: polygon(50% 0, 100% 100%, 0 100%)")),
9755            (
9756                B::Border,
9757                F::NonZero,
9758                vec![
9759                    [relative(0.5), px(0.).into()],
9760                    [relative(1.), relative(1.)],
9761                    [px(0.).into(), relative(1.)]
9762                ]
9763            )
9764        );
9765        let (rb, rule, points) = polygon(&clean(
9766            "clip-path: polygon(evenodd, calc(100% - 8px) 0, 8px 100%) content-box",
9767        ));
9768        assert_eq!((rb, rule), (B::Content, F::EvenOdd));
9769        assert_eq!(
9770            points[0],
9771            [
9772                DefiniteLength::Calc {
9773                    fraction: 1.,
9774                    pixels: px(-8.)
9775                },
9776                px(0.).into()
9777            ]
9778        );
9779        assert_eq!(points[1], [px(8.).into(), relative(1.)]);
9780
9781        let path = |r: &StyleRefinement| match &r.vn_clip_path {
9782            Some(C::Path {
9783                reference,
9784                fill_rule,
9785                verbs,
9786            }) => (*reference, *fill_rule, verbs.to_vec()),
9787            other => panic!("{other:?}"),
9788        };
9789        let notch = "clip-path: path('M0 0 C12.1506 0 22 9.8494 22 22 V42 Q22 64 44 64 H420 Q442 64 442 42 V22 C442 9.8494 451.8494 0 464 0 Z')";
9790        let (rb, rule, verbs) = path(&clean(notch));
9791        assert_eq!((rb, rule, verbs.len()), (B::Border, F::NonZero, 9));
9792        assert_eq!(verbs[3], QuadTo([22., 64.], [44., 64.]));
9793        let mut d = Vec::new();
9794        let inline = parse_inline_style(notch, &mut d);
9795        assert!(d.is_empty(), "{d:?}");
9796        assert!(format!("{inline:?}").contains("Path"), "{inline:?}");
9797        let (rb, rule, verbs) = path(&clean(
9798            r#"clip-path: path(evenodd, "M0 0 h10 v10 h-10 z M2 2 h6 v6 h-6 z") padding-box"#,
9799        ));
9800        assert_eq!((rb, rule, verbs.len()), (B::Padding, F::EvenOdd, 10));
9801        assert_eq!(verbs[5], MoveTo([2., 2.]));
9802        assert_eq!(path(&clean("clip-path: path('')")).2, vec![]);
9803        for bad in [
9804            "path('M0 0 L')",
9805            "path('L10 10')",
9806            "path(round, 'M0 0')",
9807            "path(evenodd)",
9808            "path('M0 0') blue",
9809        ] {
9810            let (r, _) = map(&format!("clip-path: {bad}"));
9811            assert_eq!(r.vn_clip_path, None, "{bad}");
9812        }
9813    }
9814}
9815
9816#[cfg(test)]
9817mod scrollbar_tests {
9818    use super::*;
9819
9820    fn extras_of(body: &str) -> Extras {
9821        let mut d = Vec::new();
9822        parse_inline_style(body, &mut d).extras
9823    }
9824
9825    #[test]
9826    fn scrollbar_color_takes_two_colours_thumb_first() {
9827        let x = extras_of("scrollbar-color: #ff0000 #0000ff");
9828        let (thumb, track) = x.scrollbar_color.expect("a pair");
9829        assert!(
9830            thumb.h < 0.02,
9831            "thumb is the first colour (red), got {thumb:?}"
9832        );
9833        assert!(
9834            (track.h - 0.6667).abs() < 0.02,
9835            "track is the second (blue), got {track:?}"
9836        );
9837        assert_eq!(extras_of("scrollbar-color: auto").scrollbar_color, None);
9838        assert_eq!(
9839            extras_of("scrollbar-color: red").scrollbar_color,
9840            None,
9841            "one colour is not a pair"
9842        );
9843        let named = extras_of("scrollbar-color: red blue");
9844        let (thumb, track) = named.scrollbar_color.expect("a pair of named colours");
9845        assert!(thumb.h < 0.02, "thumb is red, got {thumb:?}");
9846        assert!(
9847            (track.h - 0.6667).abs() < 0.02,
9848            "track is blue, got {track:?}"
9849        );
9850    }
9851
9852    #[test]
9853    fn overscroll_behavior_sets_both_axes_or_one() {
9854        let both = extras_of("overscroll-behavior: contain");
9855        assert_eq!(both.overscroll_x, Some(OverscrollBehavior::Contain));
9856        assert_eq!(both.overscroll_y, Some(OverscrollBehavior::Contain));
9857        let y = extras_of("overscroll-behavior-y: none");
9858        assert_eq!(y.overscroll_x, None);
9859        assert_eq!(y.overscroll_y, Some(OverscrollBehavior::None));
9860    }
9861
9862    #[test]
9863    fn a_malformed_inline_declaration_is_skipped_and_the_rest_applies() {
9864        let mut d = Vec::new();
9865        let inline = parse_inline_style("0: d; display: flex; }; gap: 4px", &mut d);
9866        let r = inline
9867            .refinement
9868            .expect("the valid declarations still apply");
9869        assert_eq!(r.display, Some(gpui::Display::Flex));
9870        assert!(
9871            r.gap.width.is_some(),
9872            "gap after the bad declarations applies too"
9873        );
9874    }
9875
9876    #[test]
9877    fn accepts_declaration_is_what_the_engine_applies() {
9878        assert!(accepts_declaration("display", "flex"));
9879        assert!(accepts_declaration("width", "10px"));
9880        assert!(accepts_declaration("width", "var(--w)"));
9881        assert!(accepts_declaration("color", "inherit"));
9882        assert!(accepts_declaration("--anything", "at all"));
9883        // Not a value of the property, so not a declaration a browser keeps.
9884        assert!(!accepts_declaration("width", "abc"));
9885        assert!(!accepts_declaration("width", "10qq"));
9886        assert!(!accepts_declaration("color", "notacolor"));
9887        assert!(!accepts_declaration("display", ""));
9888        // One declaration only: a `;` cannot smuggle a second one in.
9889        assert!(!accepts_declaration("display", "flex; color: red"));
9890        // A property the mapper does not fold is not applied, so not accepted.
9891        assert!(!accepts_declaration("-ms-flex-pack", "center"));
9892        // A prefix Chromium ignores is not accepted, a `var()` value included; the `-webkit-` alias
9893        // it honours is.
9894        assert!(!accepts_declaration("-moz-appearance", "none"));
9895        assert!(!accepts_declaration("-moz-transition", "var(--t)"));
9896        assert!(accepts_declaration("-webkit-user-select", "none"));
9897    }
9898}
9899
9900#[cfg(test)]
9901mod prefix_tests {
9902    use super::*;
9903
9904    fn extras(body: &str) -> (Extras, Vec<String>) {
9905        let mut d = Vec::new();
9906        let inline = parse_inline_style(body, &mut d);
9907        (inline.extras, d)
9908    }
9909
9910    #[test]
9911    fn a_prefixed_declaration_the_engine_does_not_apply_is_dropped_without_a_word() {
9912        for body in [
9913            "-moz-osx-font-smoothing: grayscale",
9914            "-webkit-font-smoothing: antialiased",
9915            "-webkit-touch-callout: none",
9916            "-webkit-tap-highlight-color: transparent",
9917            "-webkit-overflow-scrolling: touch",
9918            "-ms-overflow-style: none",
9919            "-moz-tab-size: 4",
9920            "-moz-user-select: none",
9921            "-moz-appearance: none",
9922            "-ms-flex: 1",
9923            "-o-transition: opacity 1s",
9924            "-webkit-text-decoration: underline dotted",
9925            "-moz-transition: var(--t)",
9926            "-WEBKIT-TOUCH-CALLOUT: none",
9927        ] {
9928            let mut d = Vec::new();
9929            let inline = parse_inline_style(body, &mut d);
9930            assert!(d.is_empty(), "{body:?} said {d:?}");
9931            assert!(inline.is_empty(), "{body:?} applied something");
9932        }
9933    }
9934
9935    #[test]
9936    fn a_dropped_prefix_never_reaches_a_rule_and_an_honoured_one_does() {
9937        assert_eq!(extras("-moz-user-select: none").0.user_select, None);
9938        assert_eq!(
9939            extras("-webkit-user-select: none").0.user_select,
9940            Some(UserSelect::None)
9941        );
9942        fn block(body: &str) -> DeclarationBlock<'_> {
9943            DeclarationBlock::parse_string(body, ParserOptions::default()).expect("parses")
9944        }
9945        let c = convert_block(&block(
9946            "-moz-transition: opacity 1s; -ms-transform: scale(2); -webkit-touch-callout: none",
9947        ));
9948        assert!(c.normal.is_none() && c.normal_transitions.is_none());
9949        assert!(c.diagnostics.is_none(), "{:?}", c.diagnostics);
9950        let c = convert_block(&block(
9951            "-webkit-transition: opacity 1s; -webkit-transform: scale(2)",
9952        ));
9953        assert!(c.normal.is_some() && c.normal_transitions.is_some());
9954        assert!(c.diagnostics.is_none(), "{:?}", c.diagnostics);
9955    }
9956
9957    #[test]
9958    fn webkit_text_fill_color_is_a_glyph_colour() {
9959        let is_red = |f: Option<TextFill>| match f {
9960            Some(TextFill::Color(c)) => {
9961                c.h.abs() < 1e-3 && (c.s - 1.0).abs() < 1e-3 && (c.l - 0.5).abs() < 1e-3
9962            }
9963            _ => false,
9964        };
9965        assert!(is_red(
9966            extras("-webkit-text-fill-color: #ff0000").0.text_fill_color
9967        ));
9968        assert!(is_red(
9969            extras("-webkit-text-fill-color: red").0.text_fill_color
9970        ));
9971        assert_eq!(
9972            extras("-webkit-text-fill-color: currentColor")
9973                .0
9974                .text_fill_color,
9975            Some(TextFill::CurrentColor)
9976        );
9977        match extras("-webkit-text-fill-color: transparent")
9978            .0
9979            .text_fill_color
9980        {
9981            Some(TextFill::Color(c)) => assert_eq!(c.a, 0.0),
9982            other => panic!("{other:?}"),
9983        }
9984        let (x, d) = extras(
9985            "background-image: linear-gradient(90deg, #f00, #00f); -webkit-background-clip: text; \
9986             background-clip: text; -webkit-text-fill-color: transparent",
9987        );
9988        assert_eq!(x.background_clip_text, Some(true));
9989        assert!(x.text_fill_color.is_some());
9990        assert!(d.is_empty(), "{d:?}");
9991        assert_eq!(
9992            extras("-webkit-text-fill-color: 3px").0.text_fill_color,
9993            None
9994        );
9995    }
9996}