Skip to main content

nsh_core/element/
style.rs

1//! Typed styles of Rust components ([`Styled`]): chained methods
2//! (`.px_4()`, `.rounded_xl()`, `.bg(color)`) recording declarations that
3//! lower into the same rules Tailwind classes compile to, without strings
4//! to parse. Values follow Tailwind's default scales (4pt spacing steps),
5//! independent of the app's Tailwind theme, so a component looks the same
6//! in every app.
7//!
8//! Some changes are native, as with classes: theme colors carry a light
9//! and a dark value ([`AdaptiveColor`]), `.active(|s| …)`, `.hover(…)` and
10//! `.focus(…)` follow the view's interaction states. Others are bindings: a
11//! method given a signal or a closure (`.w(move || px(width.get()))`),
12//! `.style_when(signal, …)`, `.style_with(…)`. What is known when the view
13//! is made (a variant) is plain Rust: `.when(cond, …)`.
14
15use std::{
16    fmt,
17    hash::{Hash, Hasher},
18    rc::Rc,
19    sync::{Arc, LazyLock},
20};
21
22use super::{IntoReactive, Reactive, SharedString};
23use crate::{
24    BlendMode, BoxShadow, ClipInset, Cursor, FontVariant, ObjectPosition, TransformOrigin,
25    TransitionProps,
26    color::{Hsla, Rgba, transparent_black},
27    effects::{
28        ColorStop, Filter, Gradient, GradientKind, GradientSize, KeyframeAnimation, Keyframes,
29    },
30    geometry::{
31        AbsoluteLength, DefiniteLength, Length, Percentage, Points, REM_SIZE, Radians, Rems, deg,
32        percentage, px, relative,
33    },
34    style::{Color, LineHeight, PositionAxis, PropertyValue, StyleKey},
35    tailwind::{self, ClassList, Decl, Part, PropDecl, Rank, Rule, rank, state},
36    transform::TransformKind,
37};
38
39/// An absolute length in points (a rem at [`REM_SIZE`]).
40fn points(length: AbsoluteLength) -> f32 {
41    length.to_points(REM_SIZE).0
42}
43
44/// A font weight (100–900).
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub struct FontWeight(pub u16);
47
48impl FontWeight {
49    /// 100.
50    pub const THIN: Self = Self(100);
51    /// 200.
52    pub const EXTRA_LIGHT: Self = Self(200);
53    /// 300.
54    pub const LIGHT: Self = Self(300);
55    /// 400.
56    pub const NORMAL: Self = Self(400);
57    /// 500.
58    pub const MEDIUM: Self = Self(500);
59    /// 600.
60    pub const SEMIBOLD: Self = Self(600);
61    /// 700.
62    pub const BOLD: Self = Self(700);
63    /// 800.
64    pub const EXTRA_BOLD: Self = Self(800);
65    /// 900.
66    pub const BLACK: Self = Self(900);
67}
68
69/// A color for each appearance: the platform switches between them
70/// with nothing running. Theme colors are adaptive; an [`Hsla`] (or anything
71/// that converts to one) is the same in both.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
73pub struct AdaptiveColor {
74    /// In light appearance.
75    pub light: Hsla,
76    /// In dark appearance.
77    pub dark: Hsla,
78}
79
80impl AdaptiveColor {
81    /// Transparent in both.
82    pub const TRANSPARENT: Self = Self {
83        light: transparent_black(),
84        dark: transparent_black(),
85    };
86
87    /// `light` and `dark`.
88    pub fn new(light: impl Into<Hsla>, dark: impl Into<Hsla>) -> Self {
89        Self {
90            light: light.into(),
91            dark: dark.into(),
92        }
93    }
94
95    /// `0xRRGGBB` in light appearance and in dark, opaque (`const`s:
96    /// `AdaptiveColor::rgb(0xffffff, 0x101113)`).
97    pub const fn rgb(light: u32, dark: u32) -> Self {
98        Self {
99            light: crate::color::rgb(light).to_hsla(),
100            dark: crate::color::rgb(dark).to_hsla(),
101        }
102    }
103
104    /// Both with their alpha multiplied by `opacity`.
105    pub fn opacity(self, opacity: f32) -> Self {
106        self.map(|c| c.opacity(opacity))
107    }
108
109    /// Both through `f` (`theme.primary.map(|c| c.darken(0.1))`).
110    pub fn map(self, f: impl Fn(Hsla) -> Hsla) -> Self {
111        Self {
112            light: f(self.light),
113            dark: f(self.dark),
114        }
115    }
116}
117
118impl From<Hsla> for AdaptiveColor {
119    fn from(c: Hsla) -> Self {
120        Self { light: c, dark: c }
121    }
122}
123
124impl From<Rgba> for AdaptiveColor {
125    fn from(c: Rgba) -> Self {
126        Hsla::from(c).into()
127    }
128}
129
130impl From<Color> for AdaptiveColor {
131    fn from(c: Color) -> Self {
132        Hsla::from(c).into()
133    }
134}
135
136/// An `f32` compared and hashed by its bits (styles are cache keys).
137#[derive(Debug, Clone, Copy)]
138pub(crate) struct Bits(f32);
139
140impl PartialEq for Bits {
141    fn eq(&self, other: &Self) -> bool {
142        self.0.to_bits() == other.0.to_bits()
143    }
144}
145
146impl Eq for Bits {}
147
148impl Hash for Bits {
149    fn hash<H: Hasher>(&self, state: &mut H) {
150        self.0.to_bits().hash(state)
151    }
152}
153
154/// When a declaration applies: always, or while the element (or an
155/// ancestor group) is in some states, or in dark appearance. Nested
156/// variants (`.dark(|s| s.group_active(..))`) all have to hold. Small:
157/// every declaration has one (a named group's name is in its
158/// [`StyleRefinement`]).
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
160pub(crate) struct Variant {
161    /// [`state`] bits of the element itself.
162    states: u16,
163    /// [`state`] bits of the nearest ancestor group (none: no group
164    /// condition).
165    group_states: u16,
166    /// That group's name: 0 unnamed, else 1 + its index in
167    /// [`StyleRefinement::names`].
168    group: u8,
169    dark: bool,
170}
171
172impl Variant {
173    /// While hovered.
174    pub(crate) const HOVER: Self = Self::states(state::HOVERED);
175    /// While focused.
176    pub(crate) const FOCUS: Self = Self::states(state::FOCUSED);
177    /// While focused and showing it (the keyboard moved the focus).
178    pub(crate) const FOCUS_VISIBLE: Self = Self::states(state::FOCUS_VISIBLE);
179    /// While it or a view inside it is focused.
180    pub(crate) const FOCUS_WITHIN: Self = Self::states(state::FOCUS_WITHIN);
181    /// While pressed.
182    pub(crate) const ACTIVE: Self = Self::states(state::PRESSED);
183    /// While disabled.
184    pub(crate) const DISABLED: Self = Self::states(state::DISABLED);
185    /// While selected (set by the core from the accessibility state).
186    pub(crate) const SELECTED: Self = Self::states(state::SELECTED);
187    /// While checked (set by the core from the accessibility state).
188    pub(crate) const CHECKED: Self = Self::states(state::CHECKED);
189    /// While indeterminate (set by the core from the accessibility state).
190    pub(crate) const INDETERMINATE: Self = Self::states(state::INDETERMINATE);
191    /// While expanded (set by the core from the accessibility state).
192    pub(crate) const EXPANDED: Self = Self::states(state::EXPANDED);
193    /// While a toggle button is on (set by the core from the
194    /// accessibility state).
195    pub(crate) const ARIA_PRESSED: Self = Self::states(state::ARIA_PRESSED);
196    /// In dark appearance.
197    const DARK: Self = Self {
198        states: 0,
199        group_states: 0,
200        group: 0,
201        dark: true,
202    };
203
204    const fn states(states: u16) -> Self {
205        Self {
206            states,
207            group_states: 0,
208            group: 0,
209            dark: false,
210        }
211    }
212
213    /// `self` inside `outer`: both must hold.
214    fn within(self, outer: Variant) -> Variant {
215        let (group, group_states) = match (outer.group_states, self.group_states) {
216            (0, _) => (self.group, self.group_states),
217            (o, i) if i != 0 && outer.group == self.group => (outer.group, o | i),
218            (o, _) => (outer.group, o),
219        };
220        Variant {
221            states: self.states | outer.states,
222            group_states,
223            group,
224            dark: self.dark || outer.dark,
225        }
226    }
227
228    /// Its place in Tailwind's variant order: every part's, group
229    /// `group` (`""`: unnamed).
230    fn rank(self, group: &str) -> Rank {
231        let mut r = Rank::default();
232        let keys = [
233            (state::HOVERED, rank::HOVER),
234            (state::FOCUSED, rank::FOCUS),
235            (state::FOCUS_VISIBLE, rank::FOCUS_VISIBLE),
236            (state::FOCUS_WITHIN, rank::FOCUS_WITHIN),
237            (state::PRESSED, rank::ACTIVE),
238            (state::DISABLED, rank::DISABLED),
239            (state::SELECTED, rank::SELECTED),
240            (state::CHECKED, rank::CHECKED),
241            (state::INDETERMINATE, rank::INDETERMINATE),
242            (state::EXPANDED, rank::EXPANDED),
243            (state::ARIA_PRESSED, rank::ARIA_PRESSED),
244            (state::BUSY, rank::ARIA_BUSY),
245        ];
246        for (bit, key) in keys {
247            if self.group_states & bit != 0 {
248                r.add_group(&key, group);
249            }
250            if self.states & bit != 0 {
251                r.add(key);
252            }
253        }
254        if self.dark {
255            r.add(rank::DARK);
256        }
257        r
258    }
259}
260
261/// A color of a property several declarations build (a shadow's, a
262/// ring's, a gradient stop's).
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
264pub(crate) enum ColorPart {
265    Shadow,
266    InsetShadow,
267    TextShadow,
268    Ring,
269    RingOffset,
270    InsetRing,
271    From,
272    Via,
273    To,
274}
275
276impl ColorPart {
277    fn part(self, c: Hsla) -> Part {
278        let c = Color::from(c);
279        // The color replaces the layers', alpha too (as Tailwind's
280        // `shadow-red-500`).
281        match self {
282            ColorPart::Shadow => Part::ShadowColor(c),
283            ColorPart::InsetShadow => Part::InsetShadowColor(c),
284            ColorPart::TextShadow => Part::TextShadowColor(c),
285            ColorPart::Ring => Part::RingColor(c),
286            ColorPart::RingOffset => Part::RingOffsetColor(c),
287            ColorPart::InsetRing => Part::InsetRingColor(c),
288            // Theme and palette colors, which Tailwind writes in OKLCH.
289            ColorPart::From => Part::From(c, false),
290            ColorPart::Via => Part::Via(c, false),
291            ColorPart::To => Part::To(c, false),
292        }
293    }
294}
295
296/// A gradient's geometry.
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
298pub(crate) enum GradientShape {
299    /// Along a line at an angle (radians, 0 up, a quarter turn right).
300    Linear(Bits),
301    /// Towards a corner.
302    Corner { right: bool, bottom: bool },
303    /// An ellipse from the center to the farthest corner.
304    Radial,
305    /// Around the center, from an angle (radians, 0 up).
306    Conic(Bits),
307}
308
309/// A filter function (`Opacity` only of backdrops: a view's own opacity
310/// is [`Styled::opacity`]).
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
312pub(crate) enum FilterFn {
313    Blur,
314    Brightness,
315    Contrast,
316    Grayscale,
317    HueRotate,
318    Invert,
319    Opacity,
320    Saturate,
321    Sepia,
322}
323
324impl FilterFn {
325    /// Its slot in the composed list (CSS's order, as Tailwind's
326    /// utilities), and the filter.
327    fn part(self, backdrop: bool, amount: f32) -> Part {
328        let (slot, filter) = match self {
329            FilterFn::Blur => (0, Filter::Blur(crate::geometry::px(amount))),
330            FilterFn::Brightness => (1, Filter::Brightness(amount)),
331            FilterFn::Contrast => (2, Filter::Contrast(amount)),
332            FilterFn::Grayscale => (3, Filter::Grayscale(amount)),
333            FilterFn::HueRotate => (4, Filter::HueRotate(crate::geometry::deg(amount))),
334            FilterFn::Invert => (5, Filter::Invert(amount)),
335            FilterFn::Opacity => (6, Filter::Opacity(amount)),
336            FilterFn::Saturate => (6 + u8::from(backdrop), Filter::Saturate(amount)),
337            FilterFn::Sepia => (7 + u8::from(backdrop), Filter::Sepia(amount)),
338        };
339        Part::Filter {
340            backdrop,
341            slot,
342            filter: Some(filter),
343        }
344    }
345}
346
347/// Layers of [`BoxShadow`]s, compared and hashed by their bits.
348#[derive(Debug, Clone)]
349pub(crate) struct Layers(Arc<[BoxShadow]>);
350
351impl Layers {
352    fn bits(&self) -> impl Iterator<Item = (u32, u32, u32, u32, u32, bool)> + '_ {
353        self.0.iter().map(|l| {
354            (
355                l.offset_x.0.to_bits(),
356                l.offset_y.0.to_bits(),
357                l.blur.0.to_bits(),
358                l.spread.0.to_bits(),
359                l.color.0,
360                l.inset,
361            )
362        })
363    }
364}
365
366impl PartialEq for Layers {
367    fn eq(&self, other: &Self) -> bool {
368        self.0.len() == other.0.len() && self.bits().eq(other.bits())
369    }
370}
371
372impl Eq for Layers {}
373
374impl Hash for Layers {
375    fn hash<H: Hasher>(&self, state: &mut H) {
376        for l in self.bits() {
377            l.hash(state);
378        }
379    }
380}
381
382/// Layers of [`TextShadow`](crate::TextShadow)s, compared and hashed by
383/// their bits.
384#[derive(Debug, Clone)]
385pub(crate) struct TextLayers(Arc<[crate::TextShadow]>);
386
387impl TextLayers {
388    fn bits(&self) -> impl Iterator<Item = (u32, u32, u32, u32)> + '_ {
389        self.0.iter().map(|l| {
390            (
391                l.offset_x.0.to_bits(),
392                l.offset_y.0.to_bits(),
393                l.radius.0.to_bits(),
394                l.color.0,
395            )
396        })
397    }
398}
399
400impl PartialEq for TextLayers {
401    fn eq(&self, other: &Self) -> bool {
402        self.0.len() == other.0.len() && self.bits().eq(other.bits())
403    }
404}
405
406impl Eq for TextLayers {}
407
408impl Hash for TextLayers {
409    fn hash<H: Hasher>(&self, state: &mut H) {
410        for l in self.bits() {
411            l.hash(state);
412        }
413    }
414}
415
416/// `underline` in [`Declaration::Decoration`].
417const UNDERLINE: u8 = 1;
418/// `line-through` in [`Declaration::Decoration`].
419const LINE_THROUGH: u8 = 2;
420
421/// One typed declaration.
422#[derive(Debug, Clone, PartialEq, Eq, Hash)]
423pub(crate) enum Declaration {
424    /// A property's value.
425    Value(StyleKey, PropertyValue),
426    /// What a declaration implies for another property, which any
427    /// declaration of that property overrides wherever it is (an outline
428    /// width's solid style).
429    Default(StyleKey, PropertyValue),
430    Color(StyleKey, AdaptiveColor),
431    /// Tailwind's `text-*` size and line height.
432    TextPreset(&'static str),
433    /// Tailwind's `shadow-*` (`"none"` removes it).
434    Shadow(&'static str),
435    /// Tailwind's `inset-shadow-*` (`"none"` removes it).
436    InsetShadow(&'static str),
437    /// Tailwind's `text-shadow-*` (`"none"` removes it).
438    TextShadow(&'static str),
439    /// Box shadows of the element's own.
440    Shadows(Layers),
441    PartColor(ColorPart, AdaptiveColor),
442    Ring(Bits),
443    RingOffset(Bits),
444    RingInset,
445    InsetRing(Bits),
446    /// Text shadows of the element's own.
447    TextShadows(TextLayers),
448    /// One step of the transform the styles compose (CSS's order:
449    /// translate, rotate, scale, then the 3D rotations and skews).
450    Transform(TransformKind, Bits),
451    /// `transform: none` (the 3D rotations and the skews).
452    TransformNone,
453    /// `translate: none`, `scale: none`, `rotate: none`.
454    TranslateNone,
455    ScaleNone,
456    RotateNone,
457    /// `transformOrigin` at points or fractions (`true`) of the size.
458    Origin([(bool, Bits); 2]),
459    Gradient(GradientShape),
460    GradientNone,
461    /// The position of the gradient's `from` (0), `via` (1) or `to` (2)
462    /// color, a fraction of its length.
463    StopPosition(u8, Bits),
464    Filter(bool, FilterFn, Bits),
465    FilterNone(bool),
466    FontVariant {
467        set: u8,
468        clear: u8,
469    },
470    /// [`UNDERLINE`] and [`LINE_THROUGH`] add up; 0 removes both.
471    Decoration(u8),
472    /// Lines never wrap (`true`, `whitespace-nowrap`) or wrap
473    /// (`whitespace-normal`): inherited, as the classes'.
474    NoWrap(bool),
475    /// Lines wrap without a lone last word (`text-pretty`).
476    Pretty,
477    /// [`TransitionProps`] bits.
478    Transition(u8),
479    TransitionNone,
480    Duration(Bits),
481    Delay(Bits),
482    Ease([Bits; 4]),
483    /// A spring's stiffness, damping and mass (`ease-spring-[…]`).
484    EaseSpring([Bits; 3]),
485    /// Tailwind's `ease-*`.
486    EasePreset(&'static str),
487    /// A keyframe animation (`None`: none).
488    Animate(Option<u8>),
489    /// A keyframe animation with its own timing: the keyframes' index,
490    /// duration, delay, easing, iterations (`None`: forever) and the
491    /// highest frame rate it needs (`None`: the screen's highest).
492    Animation(u8, Bits, Bits, [Bits; 4], Option<u32>, Option<Bits>),
493    /// `repeat(n, minmax(0, 1fr))` tracks.
494    Tracks(StyleKey, u16),
495    /// `span n / span n`.
496    Span(StyleKey, u16),
497    /// The element is a group (`""`: unnamed): `group_*` styles inside
498    /// follow its states.
499    Group(&'static str),
500}
501
502/// Tailwind's default theme: the presets typed styles name.
503static PRESETS: LazyLock<tailwind::Theme> = LazyLock::new(tailwind::Theme::default);
504
505/// A color enters styles packed (`crate::color`'s rounding).
506fn color_value(key: StyleKey, c: Hsla) -> PropertyValue {
507    let c = Color::from(c);
508    match key {
509        // SVG's paint: a color is one of its kinds.
510        StyleKey::Fill | StyleKey::Stroke => PropertyValue::Paint(Some(crate::SvgPaint::Color(c))),
511        _ => PropertyValue::Color(Some(c)),
512    }
513}
514
515/// A transform origin at fractions of the size.
516fn origin(x: f32, y: f32) -> TransformOrigin {
517    TransformOrigin {
518        x: DefiniteLength::Fraction(Percentage(x)),
519        y: DefiniteLength::Fraction(Percentage(y)),
520        z: Points::ZERO,
521    }
522}
523
524/// `1 / -1`: from the first line to the last.
525fn full_line() -> taffy::Line<taffy::GridPlacement<String>> {
526    taffy::Line {
527        start: crate::grid::line_number(1),
528        end: crate::grid::line_number(-1),
529    }
530}
531
532fn shadow_preset(layers: Option<&Vec<BoxShadow>>) -> Arc<[BoxShadow]> {
533    layers.map_or_else(|| Arc::from([]), |l| Arc::from(l.as_slice()))
534}
535
536/// The keyframes of [`Declaration::Animate`].
537const KEYFRAMES: [Keyframes; 4] = [
538    Keyframes::Spin,
539    Keyframes::Ping,
540    Keyframes::Pulse,
541    Keyframes::Bounce,
542];
543
544impl Declaration {
545    fn lower(&self, out: &mut Vec<Decl>) {
546        let part = |out: &mut Vec<Decl>, p: Part| out.push(Decl::Part(p));
547        match self {
548            Declaration::Value(key, value) => {
549                out.push(Decl::Set(*key, value.clone()));
550                // As the classes': a width's color is `currentColor` unless
551                // a color method sets one.
552                match key {
553                    StyleKey::BorderWidth
554                    | StyleKey::BorderTopWidth
555                    | StyleKey::BorderRightWidth
556                    | StyleKey::BorderBottomWidth
557                    | StyleKey::BorderLeftWidth
558                    | StyleKey::BorderStartWidth
559                    | StyleKey::BorderEndWidth => {
560                        out.push(Decl::CurrentColor(StyleKey::BorderColor))
561                    }
562                    StyleKey::OutlineWidth => out.push(Decl::CurrentColor(StyleKey::OutlineColor)),
563                    _ => {}
564                }
565            }
566            Declaration::Default(key, value) => {
567                out.push(Decl::Default(*key, value.clone()));
568                if *key == StyleKey::OutlineWidth {
569                    out.push(Decl::CurrentColor(StyleKey::OutlineColor));
570                }
571            }
572            Declaration::Color(key, c) => out.push(if c.light == c.dark {
573                Decl::Set(*key, color_value(*key, c.light))
574            } else {
575                Decl::Adaptive(
576                    *key,
577                    [color_value(*key, c.light), color_value(*key, c.dark)],
578                )
579            }),
580            Declaration::TextPreset(name) => {
581                if let Some(&(size, line)) = PRESETS.text.get(*name) {
582                    out.push(Decl::Set(
583                        StyleKey::FontSize,
584                        PropertyValue::FontSize(Some(px(size)), None),
585                    ));
586                    // As `text-lg`'s: a line height set anywhere wins.
587                    if let Some(m) = line {
588                        out.push(Decl::Default(
589                            StyleKey::LineHeight,
590                            PropertyValue::LineHeight(LineHeight::Multiple(m)),
591                        ));
592                    }
593                }
594            }
595            Declaration::Shadow(name) => {
596                part(out, Part::Shadow(shadow_preset(PRESETS.shadows.get(*name))))
597            }
598            Declaration::InsetShadow(name) => part(
599                out,
600                Part::InsetShadow(shadow_preset(PRESETS.inset_shadows.get(*name))),
601            ),
602            Declaration::TextShadow(name) => {
603                let layers = PRESETS.text_shadows.get(*name);
604                part(
605                    out,
606                    Part::TextShadow(
607                        layers.map_or_else(|| Arc::from([]), |l| Arc::from(l.as_slice())),
608                    ),
609                )
610            }
611            Declaration::Shadows(layers) => part(out, Part::Shadow(layers.0.clone())),
612            Declaration::PartColor(which, c) => out.push(if c.light == c.dark {
613                Decl::Part(which.part(c.light))
614            } else {
615                Decl::AdaptivePart(Box::new([which.part(c.light), which.part(c.dark)]))
616            }),
617            Declaration::Ring(w) => part(out, Part::Ring(w.0)),
618            Declaration::RingOffset(w) => part(out, Part::RingOffset(w.0)),
619            Declaration::RingInset => part(out, Part::RingInset),
620            Declaration::InsetRing(w) => part(out, Part::InsetRing(w.0)),
621            Declaration::TextShadows(layers) => part(out, Part::TextShadow(layers.0.clone())),
622            Declaration::Transform(kind, v) => {
623                let v = v.0;
624                let parts: &[Part] = match kind {
625                    TransformKind::Scale => &[Part::ScaleX(v), Part::ScaleY(v)],
626                    TransformKind::ScaleX => &[Part::ScaleX(v)],
627                    TransformKind::ScaleY => &[Part::ScaleY(v)],
628                    TransformKind::TranslateX => &[Part::TranslateX(tailwind::Len::Points(v))],
629                    TransformKind::TranslateY => &[Part::TranslateY(tailwind::Len::Points(v))],
630                    TransformKind::TranslateXFraction => {
631                        &[Part::TranslateX(tailwind::Len::Fraction(v))]
632                    }
633                    TransformKind::TranslateYFraction => {
634                        &[Part::TranslateY(tailwind::Len::Fraction(v))]
635                    }
636                    TransformKind::Rotate => &[Part::Rotate(v)],
637                    TransformKind::RotateX => &[Part::RotateX(v)],
638                    TransformKind::RotateY => &[Part::RotateY(v)],
639                    TransformKind::SkewX => &[Part::SkewX(v)],
640                    TransformKind::SkewY => &[Part::SkewY(v)],
641                    TransformKind::Perspective => &[Part::Perspective(Some(v))],
642                };
643                out.extend(parts.iter().cloned().map(Decl::Part));
644            }
645            Declaration::TransformNone => part(out, Part::TransformNone),
646            Declaration::TranslateNone => part(out, Part::TranslateNone),
647            Declaration::ScaleNone => part(out, Part::ScaleNone),
648            Declaration::RotateNone => part(out, Part::RotateNone),
649            Declaration::Origin(axes) => {
650                let [x, y] = axes.map(|(fraction, v)| {
651                    if fraction {
652                        DefiniteLength::Fraction(Percentage(v.0))
653                    } else {
654                        DefiniteLength::Absolute(AbsoluteLength::Points(px(v.0)))
655                    }
656                });
657                out.push(Decl::Set(
658                    StyleKey::TransformOrigin,
659                    PropertyValue::TransformOrigin(TransformOrigin {
660                        x,
661                        y,
662                        z: Points::ZERO,
663                    }),
664                ));
665            }
666            Declaration::Gradient(shape) => part(
667                out,
668                Part::Gradient(match *shape {
669                    GradientShape::Linear(angle) => GradientKind::Linear {
670                        angle: Radians(angle.0),
671                    },
672                    GradientShape::Corner { right, bottom } => {
673                        GradientKind::LinearCorner { right, bottom }
674                    }
675                    GradientShape::Radial => GradientKind::Radial {
676                        circle: false,
677                        size: GradientSize::FarthestCorner,
678                        x: percentage(0.5),
679                        y: percentage(0.5),
680                    },
681                    GradientShape::Conic(from) => GradientKind::Conic {
682                        from: Radians(from.0),
683                        x: percentage(0.5),
684                        y: percentage(0.5),
685                    },
686                }),
687            ),
688            Declaration::GradientNone => part(out, Part::GradientNone),
689            Declaration::StopPosition(i, at) => part(
690                out,
691                match i {
692                    0 => Part::FromPos(at.0),
693                    1 => Part::ViaPos(at.0),
694                    _ => Part::ToPos(at.0),
695                },
696            ),
697            Declaration::Filter(backdrop, f, amount) => part(out, f.part(*backdrop, amount.0)),
698            Declaration::FilterNone(backdrop) => part(
699                out,
700                Part::FilterNone {
701                    backdrop: *backdrop,
702                },
703            ),
704            Declaration::FontVariant { set, clear } => part(
705                out,
706                Part::FontVariant {
707                    set: *set,
708                    clear: *clear,
709                },
710            ),
711            Declaration::Decoration(bits) => out.push(Decl::Set(
712                StyleKey::TextDecorationLine,
713                PropertyValue::TextDecoration(Some(crate::TextDecoration {
714                    underline: bits & UNDERLINE != 0,
715                    line_through: bits & LINE_THROUGH != 0,
716                })),
717            )),
718            Declaration::NoWrap(no_wrap) => out.push(Decl::Prop(PropDecl::NoWrap(*no_wrap))),
719            Declaration::Pretty => out.push(Decl::Prop(PropDecl::Pretty)),
720            Declaration::Transition(props) => part(out, Part::TransitionProps(*props)),
721            Declaration::TransitionNone => part(out, Part::TransitionNone),
722            Declaration::Duration(ms) => part(out, Part::Duration(ms.0)),
723            Declaration::Delay(ms) => part(out, Part::Delay(ms.0)),
724            Declaration::Ease(curve) => part(out, Part::Ease(curve.map(|b| b.0))),
725            Declaration::EaseSpring(physics) => {
726                let [stiffness, damping, mass] = physics.map(|b| b.0);
727                if let Some(spring) = crate::style::spring_of((stiffness, damping, mass)) {
728                    part(out, Part::Spring(spring));
729                }
730            }
731            Declaration::EasePreset(name) => {
732                if let Some(curve) = PRESETS.ease.get(*name) {
733                    part(out, Part::Ease(*curve));
734                }
735            }
736            Declaration::Animate(k) => part(out, Part::Animate(k.map(|i| KEYFRAMES[i as usize]))),
737            Declaration::Animation(k, duration, delay, easing, iterations, frame_rate) => part(
738                out,
739                Part::Animation(KeyframeAnimation {
740                    keyframes: KEYFRAMES[*k as usize],
741                    duration: duration.0,
742                    delay: delay.0,
743                    easing: easing.map(|b| b.0),
744                    iterations: *iterations,
745                    frame_rate: frame_rate.map(|b| b.0),
746                }),
747            ),
748            Declaration::Tracks(key, n) => out.push(Decl::Set(
749                *key,
750                PropertyValue::grid_template(crate::grid::equal_tracks(*n)),
751            )),
752            Declaration::Span(key, n) => out.push(Decl::Set(
753                *key,
754                PropertyValue::GridLine(crate::grid::span(*n)),
755            )),
756            // A property of the class list, not a declaration.
757            Declaration::Group(_) => {}
758        }
759    }
760}
761
762/// The static declarations of a [`StyleRefinement`], in order. Shared by
763/// its copies, which a page keeps several of per element (what a view
764/// applied, and the record its bindings patch against), and copied on the
765/// first change to a shared one.
766#[derive(Clone, Default)]
767struct Entries(Option<Rc<Vec<(Variant, Declaration)>>>);
768
769impl Entries {
770    fn with_capacity(capacity: usize) -> Self {
771        Self(Some(Rc::new(Vec::with_capacity(capacity))))
772    }
773
774    fn as_slice(&self) -> &[(Variant, Declaration)] {
775        self.0.as_deref().map_or(&[], Vec::as_slice)
776    }
777
778    fn capacity(&self) -> usize {
779        self.0.as_ref().map_or(0, |v| v.capacity())
780    }
781
782    fn reserve(&mut self, additional: usize) {
783        self.vec().reserve(additional);
784    }
785
786    fn push(&mut self, entry: (Variant, Declaration)) {
787        self.vec().push(entry);
788    }
789
790    fn extend_from_slice(&mut self, entries: &[(Variant, Declaration)]) {
791        self.vec().extend_from_slice(entries);
792    }
793
794    fn vec(&mut self) -> &mut Vec<(Variant, Declaration)> {
795        Rc::make_mut(self.0.get_or_insert_default())
796    }
797
798    fn into_vec(self) -> Vec<(Variant, Declaration)> {
799        self.0.map(Rc::unwrap_or_clone).unwrap_or_default()
800    }
801}
802
803impl std::ops::Deref for Entries {
804    type Target = [(Variant, Declaration)];
805
806    fn deref(&self) -> &Self::Target {
807        self.as_slice()
808    }
809}
810
811impl PartialEq for Entries {
812    fn eq(&self, other: &Self) -> bool {
813        match (&self.0, &other.0) {
814            (Some(a), Some(b)) if Rc::ptr_eq(a, b) => true,
815            _ => self.as_slice() == other.as_slice(),
816        }
817    }
818}
819
820impl Eq for Entries {}
821
822impl Hash for Entries {
823    fn hash<H: Hasher>(&self, state: &mut H) {
824        self.as_slice().hash(state);
825    }
826}
827
828impl fmt::Debug for Entries {
829    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
830        self.as_slice().fmt(f)
831    }
832}
833
834crate::static_reactive!(AdaptiveColor: AdaptiveColor, Hsla, Rgba, Color);
835
836// Static colors keep the same ergonomics where the native default is also
837// a value. Optional signals and closures use IntoReactive's existing path.
838macro_rules! optional_reactive_colors {
839    ($($source:ty),*) => {$(
840        impl IntoReactive<Option<AdaptiveColor>> for $source {
841            fn into_reactive(self) -> Reactive<Option<AdaptiveColor>> {
842                Reactive::Static(Some(self.into()))
843            }
844        }
845    )*};
846}
847
848optional_reactive_colors!(AdaptiveColor, Hsla, Rgba, Color);
849
850crate::static_reactive!(Length: Length, Points, Rems, AbsoluteLength, DefiniteLength, Percentage);
851crate::static_reactive!(DefiniteLength: Points, Rems, AbsoluteLength, DefiniteLength, Percentage);
852crate::static_reactive!(AbsoluteLength: Points, Rems, AbsoluteLength);
853crate::static_reactive!(Points: Points);
854crate::static_reactive!(LineHeight: LineHeight, Points, Rems, AbsoluteLength);
855crate::static_reactive!(Radians: Radians);
856crate::static_reactive!(Percentage: Percentage);
857crate::static_reactive!(u16: u16);
858crate::static_reactive!(i16: i16);
859crate::static_reactive!(ClipInset: ClipInset);
860
861/// A bound part of a style: it adds its declarations to a style, reading
862/// the signals it binds (run again when they change).
863pub(crate) type BoundStyle = Rc<dyn Fn(&mut StyleRefinement)>;
864
865/// An element's styles, in order (later declarations win). Built by the
866/// [`Styled`] methods; `.active(|s| …)` and the like hand a fresh one to
867/// their closure. Values given as signals or closures are bound parts,
868/// added after the static declarations ([`StyleRefinement::resolved`]).
869#[derive(Clone, Default)]
870pub struct StyleRefinement {
871    entries: Entries,
872    /// The names of the groups its variants follow ([`Variant::group`]).
873    names: Vec<&'static str>,
874    bound: Vec<BoundStyle>,
875}
876
877impl fmt::Debug for StyleRefinement {
878    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
879        f.debug_struct("StyleRefinement")
880            .field("entries", &self.entries)
881            .field("names", &self.names)
882            .field("bound", &self.bound.len())
883            .finish()
884    }
885}
886
887/// Equal static declarations and the same bound parts.
888impl PartialEq for StyleRefinement {
889    fn eq(&self, other: &Self) -> bool {
890        self.entries == other.entries
891            && self.names == other.names
892            && self.bound.len() == other.bound.len()
893            && self
894                .bound
895                .iter()
896                .zip(&other.bound)
897                .all(|(a, b)| Rc::ptr_eq(a, b))
898    }
899}
900
901impl Eq for StyleRefinement {}
902
903/// The static declarations (a resolved style, [`StyleRefinement::resolved`],
904/// has no bound parts).
905impl Hash for StyleRefinement {
906    fn hash<H: Hasher>(&self, state: &mut H) {
907        self.entries.hash(state);
908        self.names.hash(state);
909    }
910}
911
912impl StyleRefinement {
913    /// The color of an input's placeholder (`placeholderColor`, Tailwind's
914    /// `placeholder:text-*`), for the style of a component's part that edits
915    /// text ([`super::InputPartStyle`], such as `number_input`'s
916    /// `input_style`). Inherent rather than [`super::Styled`]'s: on an element it
917    /// is the input's own prop (`input().placeholder_color(..)`).
918    pub fn placeholder_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
919        self.bind_value(color, |s, color: AdaptiveColor| {
920            s.color(&[StyleKey::PlaceholderColor], color);
921        });
922        self
923    }
924
925    /// The color of an input's caret (`caretColor`, Tailwind's `caret-*`),
926    /// for a part that edits text ([`super::InputPartStyle`]); on iOS it
927    /// also tints the selection highlight, as UIKit has one tint for both.
928    pub fn caret_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
929        self.bind_value(color, |s, color: AdaptiveColor| {
930            s.color(&[StyleKey::CaretColor], color);
931        });
932        self
933    }
934
935    /// The color of the selection highlight (`selectionColor`, Tailwind's
936    /// `selection:bg-*`) of a part's input or texts
937    /// ([`super::InputPartStyle`], [`super::TextPartStyle`]). Inherent
938    /// rather than [`super::Styled`]'s: an element has
939    /// [`Element::selection_color`](super::Element::selection_color).
940    pub fn selection_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
941        self.bind_value(color, |s, color: AdaptiveColor| {
942            s.color(&[StyleKey::SelectionColor], color);
943        });
944        self
945    }
946
947    /// Applies `value` with `apply`: now when it is static, else as a bound
948    /// part.
949    pub(crate) fn bind_value<T: 'static>(
950        &mut self,
951        value: impl IntoReactive<T>,
952        apply: impl Fn(&mut StyleRefinement, T) + 'static,
953    ) {
954        match value.into_reactive() {
955            Reactive::Static(v) => apply(self, v),
956            Reactive::Bound(f) => self.bound.push(Rc::new(move |s| apply(s, f()))),
957        }
958    }
959
960    /// Adds a bound part.
961    pub(crate) fn bind(&mut self, part: impl Fn(&mut StyleRefinement) + 'static) {
962        self.bound.push(Rc::new(part));
963    }
964
965    /// Whether it has bound parts.
966    pub(crate) fn is_bound(&self) -> bool {
967        !self.bound.is_empty()
968    }
969
970    /// Its static declarations alone.
971    pub(crate) fn static_part(&self) -> StyleRefinement {
972        StyleRefinement {
973            entries: self.entries.clone(),
974            names: self.names.clone(),
975            bound: Vec::new(),
976        }
977    }
978
979    /// The style now: the static declarations, then the bound parts' (read
980    /// in the running computation, which subscribes to them).
981    pub(crate) fn resolved(&self) -> StyleRefinement {
982        // Without bound parts it is the static part, shared. With them, a
983        // copy with room for one declaration a part, the usual count: a
984        // style is kept as long as its element.
985        let entries = if self.bound.is_empty() {
986            self.entries.clone()
987        } else {
988            let mut entries = Entries::with_capacity(self.entries.len() + self.bound.len());
989            entries.extend_from_slice(&self.entries);
990            entries
991        };
992        let mut out = StyleRefinement {
993            entries,
994            names: self.names.clone(),
995            bound: Vec::new(),
996        };
997        for part in &self.bound {
998            part(&mut out);
999        }
1000        out
1001    }
1002
1003    pub(crate) fn push(&mut self, decl: Declaration) {
1004        // Elements take several declarations: no regrowth for the first.
1005        if self.entries.capacity() == 0 {
1006            self.entries.reserve(8);
1007        }
1008        self.entries.push((Variant::default(), decl));
1009    }
1010
1011    pub(crate) fn lengths(&mut self, keys: &[StyleKey], length: impl Into<Length>) {
1012        let length = length.into();
1013        for key in keys {
1014            self.checked(*key, key.length_value(length));
1015        }
1016    }
1017
1018    pub(crate) fn number(&mut self, key: StyleKey, n: f32) {
1019        self.checked(key, key.number_value(n));
1020    }
1021
1022    pub(crate) fn numbers(&mut self, keys: &[StyleKey], n: f32) {
1023        for key in keys {
1024            self.number(*key, n);
1025        }
1026    }
1027
1028    /// `key: calc(env(name) + extra)`.
1029    pub(crate) fn env_plus(&mut self, key: StyleKey, name: &str, extra: AbsoluteLength) {
1030        match crate::style::EnvVar::parse(name) {
1031            Some(var) => self.value(key, PropertyValue::EnvLength(px(points(extra)), var)),
1032            None => debug_assert!(false, "no environment variable `{name}`"),
1033        }
1034    }
1035
1036    /// `key: env(var)`.
1037    pub(crate) fn env(&mut self, key: StyleKey, var: crate::style::EnvVar) {
1038        self.value(key, PropertyValue::EnvLength(Points::ZERO, var));
1039    }
1040
1041    pub(crate) fn value(&mut self, key: StyleKey, value: PropertyValue) {
1042        self.push(Declaration::Value(key, value));
1043    }
1044
1045    /// A value the method makes, valid by construction (its type allows
1046    /// no other).
1047    fn checked(&mut self, key: StyleKey, value: Result<PropertyValue, crate::StyleError>) {
1048        match value {
1049            Ok(value) => self.value(key, value),
1050            Err(_) => debug_assert!(false, "an invalid typed value of `{}`", key.name()),
1051        }
1052    }
1053
1054    /// A value written in CSS's syntax (a grid's tracks), parsed when the
1055    /// style is made: an invalid one is logged and sets nothing.
1056    fn css(&mut self, key: StyleKey, value: &str) {
1057        match key.parse_value(crate::StyleValue::Str(value)) {
1058            Ok(value) => self.value(key, value),
1059            Err(_) => log::warn!("invalid value for style `{}`: {value}", key.name()),
1060        }
1061    }
1062
1063    pub(crate) fn color(&mut self, keys: &[StyleKey], color: AdaptiveColor) {
1064        for key in keys {
1065            self.push(Declaration::Color(*key, color));
1066        }
1067    }
1068
1069    /// `other`'s declarations, applying while in `variant` (and in their
1070    /// own).
1071    pub(crate) fn extend_as(&mut self, variant: Variant, other: StyleRefinement) {
1072        for (mut v, d) in other.entries.into_vec() {
1073            if v.group != 0 {
1074                v.group = self.name(other.names[v.group as usize - 1]);
1075            }
1076            self.entries.push((v.within(variant), d));
1077        }
1078        // Bound parts apply in the variant too. They run into whatever
1079        // refinement resolves them, so the variant's group goes by name:
1080        // its index is only valid in `self.names`.
1081        let group = (variant.group != 0).then(|| self.names[variant.group as usize - 1]);
1082        for part in other.bound {
1083            self.bound.push(Rc::new(move |s| {
1084                let mut inner = StyleRefinement::default();
1085                part(&mut inner);
1086                let mut variant = variant;
1087                if let Some(name) = group {
1088                    variant.group = s.name(name);
1089                }
1090                s.extend_as(variant, inner);
1091            }));
1092        }
1093    }
1094
1095    /// [`Variant::group`] of the group `name`.
1096    fn name(&mut self, name: &'static str) -> u8 {
1097        if name.is_empty() {
1098            return 0;
1099        }
1100        let at = match self.names.iter().position(|n| *n == name) {
1101            Some(at) => at,
1102            None => {
1103                self.names.push(name);
1104                self.names.len() - 1
1105            }
1106        };
1107        u8::try_from(at + 1).expect("fewer than 255 group names")
1108    }
1109
1110    /// The color its last static declaration of `key` in no state sets
1111    /// (bound parts left out): `None` for none or `unset`.
1112    pub(crate) fn static_color(&self, key: StyleKey) -> Option<AdaptiveColor> {
1113        self.entries.iter().rev().find_map(|(variant, d)| {
1114            if *variant != Variant::default() {
1115                return None;
1116            }
1117            match d {
1118                Declaration::Color(k, color) if *k == key => Some(Some(*color)),
1119                Declaration::Value(k, PropertyValue::Color(color)) if *k == key => {
1120                    Some(color.map(AdaptiveColor::from))
1121                }
1122                _ => None,
1123            }
1124        })?
1125    }
1126
1127    /// No declarations, and no bound parts.
1128    pub fn is_empty(&self) -> bool {
1129        self.entries.is_empty() && self.bound.is_empty()
1130    }
1131
1132    /// The rules, as Tailwind classes compile to: one per variant, in
1133    /// Tailwind's variant order.
1134    pub(crate) fn lower(&self) -> ClassList {
1135        let mut variants: Vec<Variant> = Vec::new();
1136        let mut groups: Vec<Box<str>> = Vec::new();
1137        for (v, d) in self.entries.iter() {
1138            if let Declaration::Group(name) = d {
1139                if !groups.iter().any(|g| **g == **name) {
1140                    groups.push((*name).into());
1141                }
1142            } else if !variants.contains(v) {
1143                variants.push(*v);
1144            }
1145        }
1146        let mut rules = Vec::with_capacity(variants.len());
1147        for variant in variants {
1148            let mut decls = Vec::new();
1149            // Decorations add up within a variant (`.underline()
1150            // .line_through()` draws both).
1151            let mut decoration = 0;
1152            for (v, d) in self.entries.iter() {
1153                if *v != variant {
1154                    continue;
1155                }
1156                if let Declaration::Decoration(bits) = d {
1157                    decoration = if *bits == 0 { 0 } else { decoration | bits };
1158                    Declaration::Decoration(decoration).lower(&mut decls);
1159                } else {
1160                    d.lower(&mut decls);
1161                }
1162            }
1163            if !decls.is_empty() {
1164                let name = match variant.group {
1165                    0 => "",
1166                    g => self.names[g as usize - 1],
1167                };
1168                let group = (variant.group_states != 0).then_some((name, variant.group_states));
1169                rules.push(Rule::with(
1170                    variant.states,
1171                    group,
1172                    variant.dark,
1173                    variant.rank(name),
1174                    decls,
1175                ));
1176            }
1177        }
1178        ClassList::from_rules(rules, groups)
1179    }
1180}
1181
1182/// `s` with number / letter forms `set` on and `clear` off.
1183fn font_variant<S: Styled>(mut s: S, set: u8, clear: u8) -> S {
1184    s.style().push(Declaration::FontVariant { set, clear });
1185    s
1186}
1187
1188/// A text's base direction (`writingDirection`).
1189#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1190pub enum WritingDirection {
1191    /// From the content (the default).
1192    #[default]
1193    Auto,
1194    /// Left to right.
1195    Ltr,
1196    /// Right to left.
1197    Rtl,
1198}
1199
1200/// The layout direction of a view and its subtree (`direction`).
1201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1202pub enum LayoutDirection {
1203    /// Its parent's (the default): the surface's follows the user's
1204    /// language.
1205    #[default]
1206    Inherit,
1207    /// Left to right.
1208    Ltr,
1209    /// Right to left: rows run from the right, and left / right
1210    /// properties mean start and end.
1211    Rtl,
1212}
1213crate::static_reactive!(LayoutDirection: LayoutDirection);
1214
1215/// The shape of rounded corners (`borderCurve`).
1216#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1217pub enum BorderCurve {
1218    /// Quarter circles (the default).
1219    #[default]
1220    Circular,
1221    /// Curvature easing into the edges (iOS app icons); pills stay pills.
1222    Continuous,
1223}
1224
1225/// Styling methods, named after the utility classes they match (`.p_4()` is
1226/// `p-4`). Implemented by the elements and by [`StyleRefinement`] (in
1227/// `.active(|s| …)`).
1228pub trait Styled: Sized {
1229    /// The styles being built.
1230    fn style(&mut self) -> &mut StyleRefinement;
1231
1232    nsh_macros::style_helpers! {
1233        /// Padding on all sides
1234        p => [Padding],
1235        /// Horizontal padding
1236        px => [PaddingHorizontal],
1237        /// Vertical padding
1238        py => [PaddingVertical],
1239        /// Top padding
1240        pt => [PaddingTop],
1241        /// Right padding
1242        pr => [PaddingRight],
1243        /// Bottom padding
1244        pb => [PaddingBottom],
1245        /// Left padding
1246        pl => [PaddingLeft],
1247        /// Leading padding (left in left-to-right layouts)
1248        ps => [PaddingStart],
1249        /// Trailing padding
1250        pe => [PaddingEnd],
1251        /// Margin on all sides
1252        m => [Margin],
1253        /// Horizontal margin
1254        mx => [MarginHorizontal],
1255        /// Vertical margin
1256        my => [MarginVertical],
1257        /// Top margin
1258        mt => [MarginTop],
1259        /// Right margin
1260        mr => [MarginRight],
1261        /// Bottom margin
1262        mb => [MarginBottom],
1263        /// Left margin
1264        ml => [MarginLeft],
1265        /// Leading margin
1266        ms => [MarginStart],
1267        /// Trailing margin
1268        me => [MarginEnd],
1269        /// Space between children
1270        gap => [Gap],
1271        /// Space between columns
1272        gap_x => [ColumnGap],
1273        /// Space between rows
1274        gap_y => [RowGap],
1275        /// Width
1276        w => [Width],
1277        /// Height
1278        h => [Height],
1279        /// Width and height
1280        size => [Width, Height],
1281        /// Minimum width
1282        min_w => [MinWidth],
1283        /// Minimum height
1284        min_h => [MinHeight],
1285        /// Maximum width
1286        max_w => [MaxWidth],
1287        /// Maximum height
1288        max_h => [MaxHeight],
1289        /// Distance from the parent's top edge (absolute layout)
1290        top => [Top],
1291        /// Distance from the parent's right edge
1292        right => [Right],
1293        /// Distance from the parent's bottom edge
1294        bottom => [Bottom],
1295        /// Distance from the parent's left edge
1296        left => [Left],
1297        /// Distance from every edge of the parent
1298        inset => [Top, Right, Bottom, Left],
1299        /// The flex basis
1300        basis => [FlexBasis],
1301    }
1302
1303    // Environment variables: CSS's `env()` on padding and margin.
1304
1305    /// Padding on every side by the safe area's insets where the view renders
1306    /// (CSS's `padding: env(safe-area-inset-*)`): the insets of its root
1307    /// view (the surface's safe area, a dialog's, or a page's below its
1308    /// header).
1309    fn p_safe_area(mut self) -> Self {
1310        let s = self.style();
1311        s.env(StyleKey::PaddingTop, crate::style::EnvVar::SafeAreaInsetTop);
1312        s.env(
1313            StyleKey::PaddingRight,
1314            crate::style::EnvVar::SafeAreaInsetRight,
1315        );
1316        s.env(
1317            StyleKey::PaddingBottom,
1318            crate::style::EnvVar::SafeAreaInsetBottom,
1319        );
1320        s.env(
1321            StyleKey::PaddingLeft,
1322            crate::style::EnvVar::SafeAreaInsetLeft,
1323        );
1324        self
1325    }
1326
1327    /// Left and right padding by the safe area's insets on those edges
1328    /// ([`Styled::p_safe_area`]).
1329    fn px_safe_area(mut self) -> Self {
1330        let s = self.style();
1331        s.env(
1332            StyleKey::PaddingRight,
1333            crate::style::EnvVar::SafeAreaInsetRight,
1334        );
1335        s.env(
1336            StyleKey::PaddingLeft,
1337            crate::style::EnvVar::SafeAreaInsetLeft,
1338        );
1339        self
1340    }
1341
1342    /// Top and bottom padding by the safe area's insets on those edges
1343    /// ([`Styled::p_safe_area`]).
1344    fn py_safe_area(mut self) -> Self {
1345        let s = self.style();
1346        s.env(StyleKey::PaddingTop, crate::style::EnvVar::SafeAreaInsetTop);
1347        s.env(
1348            StyleKey::PaddingBottom,
1349            crate::style::EnvVar::SafeAreaInsetBottom,
1350        );
1351        self
1352    }
1353
1354    /// Top padding by the safe area's top inset where the view renders
1355    /// (CSS's `padding-top: env(safe-area-inset-top)`, [`Styled::p_safe_area`]).
1356    fn pt_safe_area(mut self) -> Self {
1357        self.style()
1358            .env(StyleKey::PaddingTop, crate::style::EnvVar::SafeAreaInsetTop);
1359        self
1360    }
1361
1362    /// Top padding by the safe area's top inset plus `extra` (CSS's
1363    /// `padding-top: calc(env(safe-area-inset-top) + <extra>)`); `extra` is not negative.
1364    fn pt_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1365        self.style()
1366            .env_plus(StyleKey::PaddingTop, "safe-area-inset-top", extra.into());
1367        self
1368    }
1369
1370    /// Right padding by the safe area's right inset where the view renders
1371    /// (CSS's `padding-right: env(safe-area-inset-right)`, [`Styled::p_safe_area`]).
1372    fn pr_safe_area(mut self) -> Self {
1373        self.style().env(
1374            StyleKey::PaddingRight,
1375            crate::style::EnvVar::SafeAreaInsetRight,
1376        );
1377        self
1378    }
1379
1380    /// Right padding by the safe area's right inset plus `extra` (CSS's
1381    /// `padding-right: calc(env(safe-area-inset-right) + <extra>)`); `extra` is not negative.
1382    fn pr_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1383        self.style().env_plus(
1384            StyleKey::PaddingRight,
1385            "safe-area-inset-right",
1386            extra.into(),
1387        );
1388        self
1389    }
1390
1391    /// Bottom padding by the safe area's bottom inset where the view renders
1392    /// (CSS's `padding-bottom: env(safe-area-inset-bottom)`, [`Styled::p_safe_area`]).
1393    fn pb_safe_area(mut self) -> Self {
1394        self.style().env(
1395            StyleKey::PaddingBottom,
1396            crate::style::EnvVar::SafeAreaInsetBottom,
1397        );
1398        self
1399    }
1400
1401    /// Bottom padding by the safe area's bottom inset plus `extra` (CSS's
1402    /// `padding-bottom: calc(env(safe-area-inset-bottom) + <extra>)`); `extra` is not negative.
1403    fn pb_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1404        self.style().env_plus(
1405            StyleKey::PaddingBottom,
1406            "safe-area-inset-bottom",
1407            extra.into(),
1408        );
1409        self
1410    }
1411
1412    /// Left padding by the safe area's left inset where the view renders
1413    /// (CSS's `padding-left: env(safe-area-inset-left)`, [`Styled::p_safe_area`]).
1414    fn pl_safe_area(mut self) -> Self {
1415        self.style().env(
1416            StyleKey::PaddingLeft,
1417            crate::style::EnvVar::SafeAreaInsetLeft,
1418        );
1419        self
1420    }
1421
1422    /// Left padding by the safe area's left inset plus `extra` (CSS's
1423    /// `padding-left: calc(env(safe-area-inset-left) + <extra>)`); `extra` is not negative.
1424    fn pl_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1425        self.style()
1426            .env_plus(StyleKey::PaddingLeft, "safe-area-inset-left", extra.into());
1427        self
1428    }
1429
1430    /// Bottom padding by the software keyboard's height over the surface, 0
1431    /// while it is hidden (CSS's `padding-bottom: env(keyboard-inset-height)`):
1432    /// content kept above the keyboard, moving with it natively. For a
1433    /// view that reaches the bottom of the surface.
1434    fn pb_keyboard(mut self) -> Self {
1435        self.style().env(
1436            StyleKey::PaddingBottom,
1437            crate::style::EnvVar::KeyboardInsetHeight,
1438        );
1439        self
1440    }
1441
1442    /// Bottom padding by the keyboard's height plus `extra` (CSS's
1443    /// `padding-bottom: calc(env(keyboard-inset-height) + <extra>)`,
1444    /// [`Styled::pb_keyboard`]); `extra` is not negative.
1445    fn pb_keyboard_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1446        self.style().env_plus(
1447            StyleKey::PaddingBottom,
1448            "keyboard-inset-height",
1449            extra.into(),
1450        );
1451        self
1452    }
1453
1454    /// Margin on every side by the safe area's insets where the view renders
1455    /// (CSS's `margin: env(safe-area-inset-*)`): the insets of its root
1456    /// view (the surface's safe area, a dialog's, or a page's below its
1457    /// header).
1458    fn m_safe_area(mut self) -> Self {
1459        let s = self.style();
1460        s.env(StyleKey::MarginTop, crate::style::EnvVar::SafeAreaInsetTop);
1461        s.env(
1462            StyleKey::MarginRight,
1463            crate::style::EnvVar::SafeAreaInsetRight,
1464        );
1465        s.env(
1466            StyleKey::MarginBottom,
1467            crate::style::EnvVar::SafeAreaInsetBottom,
1468        );
1469        s.env(
1470            StyleKey::MarginLeft,
1471            crate::style::EnvVar::SafeAreaInsetLeft,
1472        );
1473        self
1474    }
1475
1476    /// Left and right margin by the safe area's insets on those edges
1477    /// ([`Styled::m_safe_area`]).
1478    fn mx_safe_area(mut self) -> Self {
1479        let s = self.style();
1480        s.env(
1481            StyleKey::MarginRight,
1482            crate::style::EnvVar::SafeAreaInsetRight,
1483        );
1484        s.env(
1485            StyleKey::MarginLeft,
1486            crate::style::EnvVar::SafeAreaInsetLeft,
1487        );
1488        self
1489    }
1490
1491    /// Top and bottom margin by the safe area's insets on those edges
1492    /// ([`Styled::m_safe_area`]).
1493    fn my_safe_area(mut self) -> Self {
1494        let s = self.style();
1495        s.env(StyleKey::MarginTop, crate::style::EnvVar::SafeAreaInsetTop);
1496        s.env(
1497            StyleKey::MarginBottom,
1498            crate::style::EnvVar::SafeAreaInsetBottom,
1499        );
1500        self
1501    }
1502
1503    /// Top margin by the safe area's top inset where the view renders
1504    /// (CSS's `margin-top: env(safe-area-inset-top)`, [`Styled::m_safe_area`]).
1505    fn mt_safe_area(mut self) -> Self {
1506        self.style()
1507            .env(StyleKey::MarginTop, crate::style::EnvVar::SafeAreaInsetTop);
1508        self
1509    }
1510
1511    /// Top margin by the safe area's top inset plus `extra` (CSS's
1512    /// `margin-top: calc(env(safe-area-inset-top) + <extra>)`).
1513    fn mt_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1514        self.style()
1515            .env_plus(StyleKey::MarginTop, "safe-area-inset-top", extra.into());
1516        self
1517    }
1518
1519    /// Right margin by the safe area's right inset where the view renders
1520    /// (CSS's `margin-right: env(safe-area-inset-right)`, [`Styled::m_safe_area`]).
1521    fn mr_safe_area(mut self) -> Self {
1522        self.style().env(
1523            StyleKey::MarginRight,
1524            crate::style::EnvVar::SafeAreaInsetRight,
1525        );
1526        self
1527    }
1528
1529    /// Right margin by the safe area's right inset plus `extra` (CSS's
1530    /// `margin-right: calc(env(safe-area-inset-right) + <extra>)`).
1531    fn mr_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1532        self.style()
1533            .env_plus(StyleKey::MarginRight, "safe-area-inset-right", extra.into());
1534        self
1535    }
1536
1537    /// Bottom margin by the safe area's bottom inset where the view renders
1538    /// (CSS's `margin-bottom: env(safe-area-inset-bottom)`, [`Styled::m_safe_area`]).
1539    fn mb_safe_area(mut self) -> Self {
1540        self.style().env(
1541            StyleKey::MarginBottom,
1542            crate::style::EnvVar::SafeAreaInsetBottom,
1543        );
1544        self
1545    }
1546
1547    /// Bottom margin by the safe area's bottom inset plus `extra` (CSS's
1548    /// `margin-bottom: calc(env(safe-area-inset-bottom) + <extra>)`).
1549    fn mb_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1550        self.style().env_plus(
1551            StyleKey::MarginBottom,
1552            "safe-area-inset-bottom",
1553            extra.into(),
1554        );
1555        self
1556    }
1557
1558    /// Left margin by the safe area's left inset where the view renders
1559    /// (CSS's `margin-left: env(safe-area-inset-left)`, [`Styled::m_safe_area`]).
1560    fn ml_safe_area(mut self) -> Self {
1561        self.style().env(
1562            StyleKey::MarginLeft,
1563            crate::style::EnvVar::SafeAreaInsetLeft,
1564        );
1565        self
1566    }
1567
1568    /// Left margin by the safe area's left inset plus `extra` (CSS's
1569    /// `margin-left: calc(env(safe-area-inset-left) + <extra>)`).
1570    fn ml_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1571        self.style()
1572            .env_plus(StyleKey::MarginLeft, "safe-area-inset-left", extra.into());
1573        self
1574    }
1575
1576    /// Bottom margin by the software keyboard's height over the surface, 0
1577    /// while it is hidden (CSS's `margin-bottom: env(keyboard-inset-height)`):
1578    /// content kept above the keyboard, moving with it natively. For a
1579    /// view that reaches the bottom of the surface.
1580    fn mb_keyboard(mut self) -> Self {
1581        self.style().env(
1582            StyleKey::MarginBottom,
1583            crate::style::EnvVar::KeyboardInsetHeight,
1584        );
1585        self
1586    }
1587
1588    /// Bottom margin by the keyboard's height plus `extra` (CSS's
1589    /// `margin-bottom: calc(env(keyboard-inset-height) + <extra>)`,
1590    /// [`Styled::mb_keyboard`]).
1591    fn mb_keyboard_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
1592        self.style().env_plus(
1593            StyleKey::MarginBottom,
1594            "keyboard-inset-height",
1595            extra.into(),
1596        );
1597        self
1598    }
1599
1600    // Layout.
1601
1602    /// Flex layout, its children in a row unless a direction is set (CSS's
1603    /// `display: flex`, Tailwind's `flex`). A view that sets no display
1604    /// lays its children out in a column.
1605    fn flex(mut self) -> Self {
1606        let s = self.style();
1607        s.value(
1608            StyleKey::Display,
1609            PropertyValue::Display(taffy::Display::Flex),
1610        );
1611        s.push(Declaration::Default(
1612            StyleKey::FlexDirection,
1613            PropertyValue::FlexDirection(taffy::FlexDirection::Row),
1614        ));
1615        self
1616    }
1617
1618    /// Grid layout.
1619    fn grid(mut self) -> Self {
1620        self.style().value(
1621            StyleKey::Display,
1622            PropertyValue::Display(taffy::Display::Grid),
1623        );
1624        self
1625    }
1626
1627    /// `count` equal grid columns (Tailwind's `grid-cols-3`).
1628    fn grid_cols(mut self, count: impl IntoReactive<u16>) -> Self {
1629        self.style().bind_value(count, |s, count: u16| {
1630            s.push(Declaration::Tracks(StyleKey::GridTemplateColumns, count));
1631        });
1632        self
1633    }
1634
1635    /// `count` equal grid rows.
1636    fn grid_rows(mut self, count: impl IntoReactive<u16>) -> Self {
1637        self.style().bind_value(count, |s, count: u16| {
1638            s.push(Declaration::Tracks(StyleKey::GridTemplateRows, count));
1639        });
1640        self
1641    }
1642
1643    /// The grid's columns as CSS tracks (`"200px 1fr"`, `"repeat(auto-fill,
1644    /// minmax(80px, 1fr))"`, line names).
1645    fn grid_template_columns(mut self, tracks: impl IntoReactive<SharedString>) -> Self {
1646        self.style().bind_value(tracks, |s, tracks: SharedString| {
1647            s.css(StyleKey::GridTemplateColumns, &tracks);
1648        });
1649        self
1650    }
1651
1652    /// The grid's rows as CSS tracks.
1653    fn grid_template_rows(mut self, tracks: impl IntoReactive<SharedString>) -> Self {
1654        self.style().bind_value(tracks, |s, tracks: SharedString| {
1655            s.css(StyleKey::GridTemplateRows, &tracks);
1656        });
1657        self
1658    }
1659
1660    /// Items fill the grid column by column.
1661    fn grid_flow_col(mut self) -> Self {
1662        self.style().value(
1663            StyleKey::GridAutoFlow,
1664            PropertyValue::GridAutoFlow(taffy::GridAutoFlow::Column),
1665        );
1666        self
1667    }
1668
1669    /// Items fill the grid's holes left by larger ones.
1670    fn grid_flow_dense(mut self) -> Self {
1671        self.style().value(
1672            StyleKey::GridAutoFlow,
1673            PropertyValue::GridAutoFlow(taffy::GridAutoFlow::RowDense),
1674        );
1675        self
1676    }
1677
1678    /// In the grid, `count` columns wide.
1679    fn col_span(mut self, count: impl IntoReactive<u16>) -> Self {
1680        self.style().bind_value(count, |s, count: u16| {
1681            s.push(Declaration::Span(StyleKey::GridColumn, count));
1682        });
1683        self
1684    }
1685
1686    /// In the grid, `count` rows high.
1687    fn row_span(mut self, count: impl IntoReactive<u16>) -> Self {
1688        self.style().bind_value(count, |s, count: u16| {
1689            s.push(Declaration::Span(StyleKey::GridRow, count));
1690        });
1691        self
1692    }
1693
1694    /// Across every column of the grid.
1695    fn col_span_full(mut self) -> Self {
1696        self.style()
1697            .value(StyleKey::GridColumn, PropertyValue::GridLine(full_line()));
1698        self
1699    }
1700
1701    /// Across every row of the grid.
1702    fn row_span_full(mut self) -> Self {
1703        self.style()
1704            .value(StyleKey::GridRow, PropertyValue::GridLine(full_line()));
1705        self
1706    }
1707
1708    /// Starts at column line `line` (1 is the first; negative from the
1709    /// end).
1710    fn col_start(mut self, line: impl IntoReactive<i16>) -> Self {
1711        self.style().bind_value(line, |s, line: i16| {
1712            s.number(StyleKey::GridColumnStart, f32::from(line));
1713        });
1714        self
1715    }
1716
1717    /// Ends at column line `line`.
1718    fn col_end(mut self, line: impl IntoReactive<i16>) -> Self {
1719        self.style().bind_value(line, |s, line: i16| {
1720            s.number(StyleKey::GridColumnEnd, f32::from(line));
1721        });
1722        self
1723    }
1724
1725    /// Starts at row line `line`.
1726    fn row_start(mut self, line: impl IntoReactive<i16>) -> Self {
1727        self.style().bind_value(line, |s, line: i16| {
1728            s.number(StyleKey::GridRowStart, f32::from(line));
1729        });
1730        self
1731    }
1732
1733    /// Ends at row line `line`.
1734    fn row_end(mut self, line: impl IntoReactive<i16>) -> Self {
1735        self.style().bind_value(line, |s, line: i16| {
1736            s.number(StyleKey::GridRowEnd, f32::from(line));
1737        });
1738        self
1739    }
1740
1741    /// Not laid out nor shown.
1742    fn hidden(mut self) -> Self {
1743        self.style().value(
1744            StyleKey::Display,
1745            PropertyValue::Display(taffy::Display::None),
1746        );
1747        self
1748    }
1749
1750    /// Laid out but not shown, nor what is inside it (CSS's `visibility:
1751    /// hidden`, Tailwind's `invisible`, GPUI's `Styled::invisible`): it
1752    /// keeps its place and frame, and takes no presses or keyboard focus.
1753    /// On a text nested in another (a span), its characters keep their
1754    /// place in the lines and are left out of copies and screen readers.
1755    fn invisible(mut self) -> Self {
1756        self.style()
1757            .value(StyleKey::Visibility, PropertyValue::Bool(true));
1758        self
1759    }
1760
1761    /// Children in a row.
1762    fn flex_row(mut self) -> Self {
1763        self.style().value(
1764            StyleKey::FlexDirection,
1765            PropertyValue::FlexDirection(taffy::FlexDirection::Row),
1766        );
1767        self
1768    }
1769
1770    /// Children in a row, last first.
1771    fn flex_row_reverse(mut self) -> Self {
1772        self.style().value(
1773            StyleKey::FlexDirection,
1774            PropertyValue::FlexDirection(taffy::FlexDirection::RowReverse),
1775        );
1776        self
1777    }
1778
1779    /// Children in a column (the default of a view that sets no display).
1780    fn flex_col(mut self) -> Self {
1781        self.style().value(
1782            StyleKey::FlexDirection,
1783            PropertyValue::FlexDirection(taffy::FlexDirection::Column),
1784        );
1785        self
1786    }
1787
1788    /// Children in a column, last first.
1789    fn flex_col_reverse(mut self) -> Self {
1790        self.style().value(
1791            StyleKey::FlexDirection,
1792            PropertyValue::FlexDirection(taffy::FlexDirection::ColumnReverse),
1793        );
1794        self
1795    }
1796
1797    /// Children wrap onto new lines.
1798    fn flex_wrap(mut self) -> Self {
1799        self.style().value(
1800            StyleKey::FlexWrap,
1801            PropertyValue::FlexWrap(taffy::FlexWrap::Wrap),
1802        );
1803        self
1804    }
1805
1806    /// Grows and shrinks, ignoring its own size (`flex: 1 1 0`).
1807    fn flex_1(mut self) -> Self {
1808        let s = self.style();
1809        s.number(StyleKey::FlexGrow, 1.0);
1810        s.number(StyleKey::FlexShrink, 1.0);
1811        s.lengths(&[StyleKey::FlexBasis], px(0.0));
1812        self
1813    }
1814
1815    /// Grows and shrinks from its own size (`flex: 1 1 auto`).
1816    fn flex_auto(mut self) -> Self {
1817        let s = self.style();
1818        s.number(StyleKey::FlexGrow, 1.0);
1819        s.number(StyleKey::FlexShrink, 1.0);
1820        s.lengths(&[StyleKey::FlexBasis], Length::Auto);
1821        self
1822    }
1823
1824    /// Neither grows nor shrinks.
1825    fn flex_none(mut self) -> Self {
1826        let s = self.style();
1827        s.number(StyleKey::FlexGrow, 0.0);
1828        s.number(StyleKey::FlexShrink, 0.0);
1829        self
1830    }
1831
1832    /// Takes free space, `factor` times as much as a sibling growing by 1
1833    /// (`flex-grow`; Tailwind's `grow-*`).
1834    fn flex_grow(mut self, factor: impl IntoReactive<f32>) -> Self {
1835        self.style().bind_value(factor, |s, factor: f32| {
1836            s.number(StyleKey::FlexGrow, factor);
1837        });
1838        self
1839    }
1840
1841    /// Gives up space when there is too little, `factor` times as much as
1842    /// a sibling shrinking by 1 (`flex-shrink`).
1843    fn flex_shrink(mut self, factor: impl IntoReactive<f32>) -> Self {
1844        self.style().bind_value(factor, |s, factor: f32| {
1845            s.number(StyleKey::FlexShrink, factor);
1846        });
1847        self
1848    }
1849
1850    /// Never shrinks.
1851    fn flex_shrink_0(mut self) -> Self {
1852        self.style().number(StyleKey::FlexShrink, 0.0);
1853        self
1854    }
1855
1856    /// Children at the cross axis' start.
1857    fn items_start(mut self) -> Self {
1858        self.style().value(
1859            StyleKey::AlignItems,
1860            PropertyValue::AlignItems(Some(taffy::AlignItems::FLEX_START)),
1861        );
1862        self
1863    }
1864
1865    /// Children centered on the cross axis.
1866    fn items_center(mut self) -> Self {
1867        self.style().value(
1868            StyleKey::AlignItems,
1869            PropertyValue::AlignItems(Some(taffy::AlignItems::CENTER)),
1870        );
1871        self
1872    }
1873
1874    /// Children at the cross axis' end.
1875    fn items_end(mut self) -> Self {
1876        self.style().value(
1877            StyleKey::AlignItems,
1878            PropertyValue::AlignItems(Some(taffy::AlignItems::FLEX_END)),
1879        );
1880        self
1881    }
1882
1883    /// Children stretched across (the default).
1884    fn items_stretch(mut self) -> Self {
1885        self.style().value(
1886            StyleKey::AlignItems,
1887            PropertyValue::AlignItems(Some(taffy::AlignItems::STRETCH)),
1888        );
1889        self
1890    }
1891
1892    /// Children aligned on their text baseline.
1893    fn items_baseline(mut self) -> Self {
1894        self.style().value(
1895            StyleKey::AlignItems,
1896            PropertyValue::AlignItems(Some(taffy::AlignItems::BASELINE)),
1897        );
1898        self
1899    }
1900
1901    /// Children at the main axis' start (the default).
1902    fn justify_start(mut self) -> Self {
1903        self.style().value(
1904            StyleKey::JustifyContent,
1905            PropertyValue::AlignContent(taffy::AlignContent::FLEX_START),
1906        );
1907        self
1908    }
1909
1910    /// Children centered on the main axis.
1911    fn justify_center(mut self) -> Self {
1912        self.style().value(
1913            StyleKey::JustifyContent,
1914            PropertyValue::AlignContent(taffy::AlignContent::CENTER),
1915        );
1916        self
1917    }
1918
1919    /// Children at the main axis' end.
1920    fn justify_end(mut self) -> Self {
1921        self.style().value(
1922            StyleKey::JustifyContent,
1923            PropertyValue::AlignContent(taffy::AlignContent::FLEX_END),
1924        );
1925        self
1926    }
1927
1928    /// Free space between children.
1929    fn justify_between(mut self) -> Self {
1930        self.style().value(
1931            StyleKey::JustifyContent,
1932            PropertyValue::AlignContent(taffy::AlignContent::SPACE_BETWEEN),
1933        );
1934        self
1935    }
1936
1937    /// Free space around children.
1938    fn justify_around(mut self) -> Self {
1939        self.style().value(
1940            StyleKey::JustifyContent,
1941            PropertyValue::AlignContent(taffy::AlignContent::SPACE_AROUND),
1942        );
1943        self
1944    }
1945
1946    /// Free space evenly between and around children.
1947    fn justify_evenly(mut self) -> Self {
1948        self.style().value(
1949            StyleKey::JustifyContent,
1950            PropertyValue::AlignContent(taffy::AlignContent::SPACE_EVENLY),
1951        );
1952        self
1953    }
1954
1955    /// Wrapped lines at the cross axis' start (`alignContent`, the default; Tailwind's `content-start`).
1956    fn content_start(mut self) -> Self {
1957        self.style().value(
1958            StyleKey::AlignContent,
1959            PropertyValue::AlignContent(taffy::AlignContent::FLEX_START),
1960        );
1961        self
1962    }
1963
1964    /// Wrapped lines centered on the cross axis (`content-center`).
1965    fn content_center(mut self) -> Self {
1966        self.style().value(
1967            StyleKey::AlignContent,
1968            PropertyValue::AlignContent(taffy::AlignContent::CENTER),
1969        );
1970        self
1971    }
1972
1973    /// Wrapped lines at the cross axis' end (`content-end`).
1974    fn content_end(mut self) -> Self {
1975        self.style().value(
1976            StyleKey::AlignContent,
1977            PropertyValue::AlignContent(taffy::AlignContent::FLEX_END),
1978        );
1979        self
1980    }
1981
1982    /// Free space between wrapped lines (`content-between`).
1983    fn content_between(mut self) -> Self {
1984        self.style().value(
1985            StyleKey::AlignContent,
1986            PropertyValue::AlignContent(taffy::AlignContent::SPACE_BETWEEN),
1987        );
1988        self
1989    }
1990
1991    /// Free space around wrapped lines (`content-around`).
1992    fn content_around(mut self) -> Self {
1993        self.style().value(
1994            StyleKey::AlignContent,
1995            PropertyValue::AlignContent(taffy::AlignContent::SPACE_AROUND),
1996        );
1997        self
1998    }
1999
2000    /// Free space evenly between and around wrapped lines (`content-evenly`).
2001    fn content_evenly(mut self) -> Self {
2002        self.style().value(
2003            StyleKey::AlignContent,
2004            PropertyValue::AlignContent(taffy::AlignContent::SPACE_EVENLY),
2005        );
2006        self
2007    }
2008
2009    /// Wrapped lines stretched to fill the cross axis (`content-stretch`).
2010    fn content_stretch(mut self) -> Self {
2011        self.style().value(
2012            StyleKey::AlignContent,
2013            PropertyValue::AlignContent(taffy::AlignContent::STRETCH),
2014        );
2015        self
2016    }
2017
2018    /// Itself at the cross axis' start.
2019    fn self_start(mut self) -> Self {
2020        self.style().value(
2021            StyleKey::AlignSelf,
2022            PropertyValue::AlignItems(Some(taffy::AlignItems::FLEX_START)),
2023        );
2024        self
2025    }
2026
2027    /// Itself centered on the cross axis.
2028    fn self_center(mut self) -> Self {
2029        self.style().value(
2030            StyleKey::AlignSelf,
2031            PropertyValue::AlignItems(Some(taffy::AlignItems::CENTER)),
2032        );
2033        self
2034    }
2035
2036    /// Itself at the cross axis' end.
2037    fn self_end(mut self) -> Self {
2038        self.style().value(
2039            StyleKey::AlignSelf,
2040            PropertyValue::AlignItems(Some(taffy::AlignItems::FLEX_END)),
2041        );
2042        self
2043    }
2044
2045    /// Itself stretched across.
2046    fn self_stretch(mut self) -> Self {
2047        self.style().value(
2048            StyleKey::AlignSelf,
2049            PropertyValue::AlignItems(Some(taffy::AlignItems::STRETCH)),
2050        );
2051        self
2052    }
2053
2054    /// The parent's full width.
2055    fn w_full(self) -> Self {
2056        self.w(relative(1.0))
2057    }
2058
2059    /// The parent's full height.
2060    fn h_full(self) -> Self {
2061        self.h(relative(1.0))
2062    }
2063
2064    /// The parent's full size.
2065    fn size_full(self) -> Self {
2066        self.size(relative(1.0))
2067    }
2068
2069    /// Width over height.
2070    fn aspect_ratio(mut self, ratio: impl IntoReactive<f32>) -> Self {
2071        self.style().bind_value(ratio, |s, ratio: f32| {
2072            s.number(StyleKey::AspectRatio, ratio);
2073        });
2074        self
2075    }
2076
2077    /// As wide as high.
2078    fn aspect_square(self) -> Self {
2079        self.aspect_ratio(1.0)
2080    }
2081
2082    /// Laid out in the flow (the default).
2083    fn relative(mut self) -> Self {
2084        self.style().value(
2085            StyleKey::Position,
2086            PropertyValue::Position(taffy::Position::Relative, false, false),
2087        );
2088        self
2089    }
2090
2091    /// Out of the flow, placed by `top` / `left` / ... in the parent.
2092    fn absolute(mut self) -> Self {
2093        self.style().value(
2094            StyleKey::Position,
2095            PropertyValue::Position(taffy::Position::Absolute, false, false),
2096        );
2097        self
2098    }
2099
2100    /// In the flow, and while its parent shows it sticks `top` (in a
2101    /// horizontal scroll view `left`) from the start of the viewport of the
2102    /// scroll view around it, as far as the end of its parent's content box
2103    /// (CSS `position: sticky`; `.top(..)` / `.bind_sticky_top(..)` say
2104    /// where).
2105    fn sticky(mut self) -> Self {
2106        self.style().value(
2107            StyleKey::Position,
2108            PropertyValue::Position(taffy::Position::Relative, false, true),
2109        );
2110        self
2111    }
2112
2113    /// Clips its children.
2114    fn overflow_hidden(mut self) -> Self {
2115        self.style()
2116            .value(StyleKey::Overflow, PropertyValue::Bool(true));
2117        self
2118    }
2119
2120    /// Stacking order among siblings.
2121    fn z_index(mut self, z: impl IntoReactive<i32>) -> Self {
2122        self.style()
2123            .bind_value(z, |s, z: i32| s.number(StyleKey::ZIndex, z as f32));
2124        self
2125    }
2126
2127    // Visuals.
2128
2129    /// The background color.
2130    fn bg(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2131        self.style().bind_value(color, |s, color: AdaptiveColor| {
2132            s.color(&[StyleKey::BackgroundColor], color);
2133        });
2134        self
2135    }
2136
2137    /// Opacity, 0 (invisible) to 1.
2138    fn opacity(mut self, opacity: impl IntoReactive<f32>) -> Self {
2139        self.style().bind_value(opacity, |s, opacity: f32| {
2140            s.number(StyleKey::Opacity, opacity.clamp(0.0, 1.0));
2141        });
2142        self
2143    }
2144
2145    /// The corner radius.
2146    fn rounded(mut self, radius: impl IntoReactive<Length>) -> Self {
2147        self.style().bind_value(radius, |s, radius: Length| {
2148            s.lengths(&[StyleKey::BorderRadius], radius);
2149        });
2150        self
2151    }
2152
2153    /// No rounded corners.
2154    fn rounded_none(self) -> Self {
2155        self.rounded(px(0.0))
2156    }
2157
2158    /// 2pt corners.
2159    fn rounded_xs(self) -> Self {
2160        self.rounded(px(2.0))
2161    }
2162
2163    /// 4pt corners.
2164    fn rounded_sm(self) -> Self {
2165        self.rounded(px(4.0))
2166    }
2167
2168    /// 6pt corners.
2169    fn rounded_md(self) -> Self {
2170        self.rounded(px(6.0))
2171    }
2172
2173    /// 8pt corners.
2174    fn rounded_lg(self) -> Self {
2175        self.rounded(px(8.0))
2176    }
2177
2178    /// 12pt corners.
2179    fn rounded_xl(self) -> Self {
2180        self.rounded(px(12.0))
2181    }
2182
2183    /// 16pt corners.
2184    fn rounded_2xl(self) -> Self {
2185        self.rounded(px(16.0))
2186    }
2187
2188    /// 24pt corners.
2189    fn rounded_3xl(self) -> Self {
2190        self.rounded(px(24.0))
2191    }
2192
2193    /// Fully round ends (pills, circles).
2194    fn rounded_full(self) -> Self {
2195        self.rounded(px(9999.0))
2196    }
2197
2198    /// The top corners' radius.
2199    fn rounded_t(mut self, radius: impl IntoReactive<Length>) -> Self {
2200        self.style().bind_value(radius, |s, radius: Length| {
2201            s.lengths(
2202                &[
2203                    StyleKey::BorderTopLeftRadius,
2204                    StyleKey::BorderTopRightRadius,
2205                ],
2206                radius,
2207            );
2208        });
2209        self
2210    }
2211
2212    /// The bottom corners' radius.
2213    fn rounded_b(mut self, radius: impl IntoReactive<Length>) -> Self {
2214        self.style().bind_value(radius, |s, radius: Length| {
2215            s.lengths(
2216                &[
2217                    StyleKey::BorderBottomLeftRadius,
2218                    StyleKey::BorderBottomRightRadius,
2219                ],
2220                radius,
2221            );
2222        });
2223        self
2224    }
2225
2226    /// The border width on all sides.
2227    fn border(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2228        self.style().bind_value(width, |s, width: AbsoluteLength| {
2229            s.number(StyleKey::BorderWidth, points(width));
2230        });
2231        self
2232    }
2233
2234    /// A 1pt border.
2235    fn border_1(self) -> Self {
2236        self.border(px(1.0))
2237    }
2238
2239    /// A 2pt border.
2240    fn border_2(self) -> Self {
2241        self.border(px(2.0))
2242    }
2243
2244    /// A 1pt top border.
2245    fn border_t_1(mut self) -> Self {
2246        self.style().number(StyleKey::BorderTopWidth, 1.0);
2247        self
2248    }
2249
2250    /// A 1pt bottom border.
2251    fn border_b_1(mut self) -> Self {
2252        self.style().number(StyleKey::BorderBottomWidth, 1.0);
2253        self
2254    }
2255
2256    /// A 1pt left border.
2257    fn border_l_1(mut self) -> Self {
2258        self.style().number(StyleKey::BorderLeftWidth, 1.0);
2259        self
2260    }
2261
2262    /// A 1pt right border.
2263    fn border_r_1(mut self) -> Self {
2264        self.style().number(StyleKey::BorderRightWidth, 1.0);
2265        self
2266    }
2267
2268    /// The border color.
2269    fn border_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2270        self.style().bind_value(color, |s, color: AdaptiveColor| {
2271            s.color(&[StyleKey::BorderColor], color);
2272        });
2273        self
2274    }
2275
2276    /// The top border's width.
2277    fn border_t(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2278        self.style().bind_value(width, |s, width: AbsoluteLength| {
2279            s.number(StyleKey::BorderTopWidth, points(width));
2280        });
2281        self
2282    }
2283
2284    /// The right border's width.
2285    fn border_r(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2286        self.style().bind_value(width, |s, width: AbsoluteLength| {
2287            s.number(StyleKey::BorderRightWidth, points(width));
2288        });
2289        self
2290    }
2291
2292    /// The bottom border's width.
2293    fn border_b(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2294        self.style().bind_value(width, |s, width: AbsoluteLength| {
2295            s.number(StyleKey::BorderBottomWidth, points(width));
2296        });
2297        self
2298    }
2299
2300    /// The left border's width.
2301    fn border_l(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2302        self.style().bind_value(width, |s, width: AbsoluteLength| {
2303            s.number(StyleKey::BorderLeftWidth, points(width));
2304        });
2305        self
2306    }
2307
2308    /// The left and right borders' width.
2309    fn border_x(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2310        self.style().bind_value(width, |s, width: AbsoluteLength| {
2311            s.numbers(
2312                &[StyleKey::BorderLeftWidth, StyleKey::BorderRightWidth],
2313                points(width),
2314            );
2315        });
2316        self
2317    }
2318
2319    /// The top and bottom borders' width.
2320    fn border_y(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2321        self.style().bind_value(width, |s, width: AbsoluteLength| {
2322            s.numbers(
2323                &[StyleKey::BorderTopWidth, StyleKey::BorderBottomWidth],
2324                points(width),
2325            );
2326        });
2327        self
2328    }
2329
2330    /// The leading border's width (left in left-to-right layouts).
2331    fn border_s(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2332        self.style().bind_value(width, |s, width: AbsoluteLength| {
2333            s.number(StyleKey::BorderStartWidth, points(width));
2334        });
2335        self
2336    }
2337
2338    /// The trailing border's width.
2339    fn border_e(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2340        self.style().bind_value(width, |s, width: AbsoluteLength| {
2341            s.number(StyleKey::BorderEndWidth, points(width));
2342        });
2343        self
2344    }
2345
2346    /// The top border's color.
2347    fn border_t_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2348        self.style().bind_value(color, |s, color: AdaptiveColor| {
2349            s.color(&[StyleKey::BorderTopColor], color);
2350        });
2351        self
2352    }
2353
2354    /// The right border's color.
2355    fn border_r_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2356        self.style().bind_value(color, |s, color: AdaptiveColor| {
2357            s.color(&[StyleKey::BorderRightColor], color);
2358        });
2359        self
2360    }
2361
2362    /// The bottom border's color.
2363    fn border_b_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2364        self.style().bind_value(color, |s, color: AdaptiveColor| {
2365            s.color(&[StyleKey::BorderBottomColor], color);
2366        });
2367        self
2368    }
2369
2370    /// The left border's color.
2371    fn border_l_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2372        self.style().bind_value(color, |s, color: AdaptiveColor| {
2373            s.color(&[StyleKey::BorderLeftColor], color);
2374        });
2375        self
2376    }
2377
2378    /// The left and right borders' color.
2379    fn border_x_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2380        self.style().bind_value(color, |s, color: AdaptiveColor| {
2381            s.color(
2382                &[StyleKey::BorderLeftColor, StyleKey::BorderRightColor],
2383                color,
2384            );
2385        });
2386        self
2387    }
2388
2389    /// The top and bottom borders' color.
2390    fn border_y_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2391        self.style().bind_value(color, |s, color: AdaptiveColor| {
2392            s.color(
2393                &[StyleKey::BorderTopColor, StyleKey::BorderBottomColor],
2394                color,
2395            );
2396        });
2397        self
2398    }
2399
2400    /// The leading border's color.
2401    fn border_s_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2402        self.style().bind_value(color, |s, color: AdaptiveColor| {
2403            s.color(&[StyleKey::BorderStartColor], color);
2404        });
2405        self
2406    }
2407
2408    /// The trailing border's color.
2409    fn border_e_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2410        self.style().bind_value(color, |s, color: AdaptiveColor| {
2411            s.color(&[StyleKey::BorderEndColor], color);
2412        });
2413        self
2414    }
2415
2416    /// Solid borders (the default).
2417    fn border_solid(mut self) -> Self {
2418        self.style().value(
2419            StyleKey::BorderStyle,
2420            PropertyValue::BorderStyle(crate::BorderStyle::Solid, false),
2421        );
2422        self
2423    }
2424
2425    /// Dashed borders.
2426    fn border_dashed(mut self) -> Self {
2427        self.style().value(
2428            StyleKey::BorderStyle,
2429            PropertyValue::BorderStyle(crate::BorderStyle::Dashed, false),
2430        );
2431        self
2432    }
2433
2434    /// Dotted borders.
2435    fn border_dotted(mut self) -> Self {
2436        self.style().value(
2437            StyleKey::BorderStyle,
2438            PropertyValue::BorderStyle(crate::BorderStyle::Dotted, false),
2439        );
2440        self
2441    }
2442
2443    /// No border, whatever the widths set before or after (they take no
2444    /// space); [`Styled::border_solid`] and the other styles show it again.
2445    fn border_none(mut self) -> Self {
2446        self.style().value(
2447            StyleKey::BorderStyle,
2448            PropertyValue::BorderStyle(crate::BorderStyle::Solid, true),
2449        );
2450        self
2451    }
2452
2453    /// The shape of its rounded corners.
2454    fn border_curve(mut self, curve: BorderCurve) -> Self {
2455        self.style().value(
2456            StyleKey::BorderCurve,
2457            PropertyValue::Bool(matches!(curve, BorderCurve::Continuous)),
2458        );
2459        self
2460    }
2461
2462    /// The top left corner's radius.
2463    fn rounded_tl(mut self, radius: impl IntoReactive<Length>) -> Self {
2464        self.style().bind_value(radius, |s, radius: Length| {
2465            s.lengths(&[StyleKey::BorderTopLeftRadius], radius);
2466        });
2467        self
2468    }
2469
2470    /// The top right corner's radius.
2471    fn rounded_tr(mut self, radius: impl IntoReactive<Length>) -> Self {
2472        self.style().bind_value(radius, |s, radius: Length| {
2473            s.lengths(&[StyleKey::BorderTopRightRadius], radius);
2474        });
2475        self
2476    }
2477
2478    /// The bottom right corner's radius.
2479    fn rounded_br(mut self, radius: impl IntoReactive<Length>) -> Self {
2480        self.style().bind_value(radius, |s, radius: Length| {
2481            s.lengths(&[StyleKey::BorderBottomRightRadius], radius);
2482        });
2483        self
2484    }
2485
2486    /// The bottom left corner's radius.
2487    fn rounded_bl(mut self, radius: impl IntoReactive<Length>) -> Self {
2488        self.style().bind_value(radius, |s, radius: Length| {
2489            s.lengths(&[StyleKey::BorderBottomLeftRadius], radius);
2490        });
2491        self
2492    }
2493
2494    /// The left corners' radius.
2495    fn rounded_l(mut self, radius: impl IntoReactive<Length>) -> Self {
2496        self.style().bind_value(radius, |s, radius: Length| {
2497            s.lengths(
2498                &[
2499                    StyleKey::BorderTopLeftRadius,
2500                    StyleKey::BorderBottomLeftRadius,
2501                ],
2502                radius,
2503            );
2504        });
2505        self
2506    }
2507
2508    /// The right corners' radius.
2509    fn rounded_r(mut self, radius: impl IntoReactive<Length>) -> Self {
2510        self.style().bind_value(radius, |s, radius: Length| {
2511            s.lengths(
2512                &[
2513                    StyleKey::BorderTopRightRadius,
2514                    StyleKey::BorderBottomRightRadius,
2515                ],
2516                radius,
2517            );
2518        });
2519        self
2520    }
2521
2522    /// The top leading corner's radius (top left in left-to-right
2523    /// layouts; Tailwind's `rounded-ss`).
2524    fn rounded_ss(mut self, radius: impl IntoReactive<Length>) -> Self {
2525        self.style().bind_value(radius, |s, radius: Length| {
2526            s.lengths(&[StyleKey::BorderTopStartRadius], radius);
2527        });
2528        self
2529    }
2530
2531    /// The top trailing corner's radius (`rounded-se`).
2532    fn rounded_se(mut self, radius: impl IntoReactive<Length>) -> Self {
2533        self.style().bind_value(radius, |s, radius: Length| {
2534            s.lengths(&[StyleKey::BorderTopEndRadius], radius);
2535        });
2536        self
2537    }
2538
2539    /// The bottom trailing corner's radius (`rounded-ee`).
2540    fn rounded_ee(mut self, radius: impl IntoReactive<Length>) -> Self {
2541        self.style().bind_value(radius, |s, radius: Length| {
2542            s.lengths(&[StyleKey::BorderBottomEndRadius], radius);
2543        });
2544        self
2545    }
2546
2547    /// The bottom leading corner's radius (`rounded-es`).
2548    fn rounded_es(mut self, radius: impl IntoReactive<Length>) -> Self {
2549        self.style().bind_value(radius, |s, radius: Length| {
2550            s.lengths(&[StyleKey::BorderBottomStartRadius], radius);
2551        });
2552        self
2553    }
2554
2555    /// The leading corners' radius.
2556    fn rounded_s(mut self, radius: impl IntoReactive<Length>) -> Self {
2557        self.style().bind_value(radius, |s, radius: Length| {
2558            s.lengths(
2559                &[
2560                    StyleKey::BorderTopStartRadius,
2561                    StyleKey::BorderBottomStartRadius,
2562                ],
2563                radius,
2564            );
2565        });
2566        self
2567    }
2568
2569    /// The trailing corners' radius.
2570    fn rounded_e(mut self, radius: impl IntoReactive<Length>) -> Self {
2571        self.style().bind_value(radius, |s, radius: Length| {
2572            s.lengths(
2573                &[
2574                    StyleKey::BorderTopEndRadius,
2575                    StyleKey::BorderBottomEndRadius,
2576                ],
2577                radius,
2578            );
2579        });
2580        self
2581    }
2582
2583    /// An outline `width` wide, outside the border; it takes no space.
2584    /// Solid unless a style method says otherwise, before or after it.
2585    fn outline(mut self, width: impl Into<AbsoluteLength>) -> Self {
2586        let s = self.style();
2587        s.number(StyleKey::OutlineWidth, points(width.into()));
2588        s.push(Declaration::Default(
2589            StyleKey::OutlineStyle,
2590            PropertyValue::BorderStyle(crate::BorderStyle::Solid, false),
2591        ));
2592        self
2593    }
2594
2595    /// The outline's color.
2596    fn outline_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2597        self.style().bind_value(color, |s, color: AdaptiveColor| {
2598            s.color(&[StyleKey::OutlineColor], color);
2599        });
2600        self
2601    }
2602
2603    /// The outline's distance from the border (negative: inside it).
2604    fn outline_offset(mut self, offset: impl IntoReactive<AbsoluteLength>) -> Self {
2605        self.style()
2606            .bind_value(offset, |s, offset: AbsoluteLength| {
2607                s.number(StyleKey::OutlineOffset, points(offset));
2608            });
2609        self
2610    }
2611
2612    /// A dashed outline (3 points wide unless [`Styled::outline`] sets a
2613    /// width, as CSS's `medium`).
2614    fn outline_dashed(mut self) -> Self {
2615        let s = self.style();
2616        s.value(
2617            StyleKey::OutlineStyle,
2618            PropertyValue::BorderStyle(crate::BorderStyle::Dashed, false),
2619        );
2620        s.push(Declaration::Default(
2621            StyleKey::OutlineWidth,
2622            PropertyValue::Points(px(3.0)),
2623        ));
2624        self
2625    }
2626
2627    /// A dotted outline (3 points wide unless [`Styled::outline`] sets a
2628    /// width).
2629    fn outline_dotted(mut self) -> Self {
2630        let s = self.style();
2631        s.value(
2632            StyleKey::OutlineStyle,
2633            PropertyValue::BorderStyle(crate::BorderStyle::Dotted, false),
2634        );
2635        s.push(Declaration::Default(
2636            StyleKey::OutlineWidth,
2637            PropertyValue::Points(px(3.0)),
2638        ));
2639        self
2640    }
2641
2642    /// No outline.
2643    fn outline_none(mut self) -> Self {
2644        self.style().value(
2645            StyleKey::OutlineStyle,
2646            PropertyValue::BorderStyle(crate::BorderStyle::Solid, true),
2647        );
2648        self
2649    }
2650
2651    /// No shadow.
2652    fn shadow_none(mut self) -> Self {
2653        self.style().push(Declaration::Shadow("none"));
2654        self
2655    }
2656
2657    /// Tailwind's `shadow-2xs`.
2658    fn shadow_2xs(mut self) -> Self {
2659        self.style().push(Declaration::Shadow("2xs"));
2660        self
2661    }
2662
2663    /// Tailwind's `shadow-xs`.
2664    fn shadow_xs(mut self) -> Self {
2665        self.style().push(Declaration::Shadow("xs"));
2666        self
2667    }
2668
2669    /// Tailwind's `shadow-sm`.
2670    fn shadow_sm(mut self) -> Self {
2671        self.style().push(Declaration::Shadow("sm"));
2672        self
2673    }
2674
2675    /// Tailwind's `shadow-md`.
2676    fn shadow_md(mut self) -> Self {
2677        self.style().push(Declaration::Shadow("md"));
2678        self
2679    }
2680
2681    /// Tailwind's `shadow-lg`.
2682    fn shadow_lg(mut self) -> Self {
2683        self.style().push(Declaration::Shadow("lg"));
2684        self
2685    }
2686
2687    /// Tailwind's `shadow-xl`.
2688    fn shadow_xl(mut self) -> Self {
2689        self.style().push(Declaration::Shadow("xl"));
2690        self
2691    }
2692
2693    /// Tailwind's `shadow-2xl`.
2694    fn shadow_2xl(mut self) -> Self {
2695        self.style().push(Declaration::Shadow("2xl"));
2696        self
2697    }
2698
2699    /// Box shadows of its own (CSS's `box-shadow`: offsets, blur, spread,
2700    /// color, `inset`), instead of a preset's.
2701    fn shadow(mut self, layers: impl IntoIterator<Item = BoxShadow>) -> Self {
2702        let layers: Arc<[BoxShadow]> = layers.into_iter().collect();
2703        self.style().push(Declaration::Shadows(Layers(layers)));
2704        self
2705    }
2706
2707    /// The shadow's color: of the presets' layers (an opaque color keeps
2708    /// their alpha, Tailwind's `shadow-sky-500`; one with an alpha sets it,
2709    /// `shadow-sky-500/50`).
2710    fn shadow_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
2711        let color = color.into();
2712        self.style()
2713            .push(Declaration::PartColor(ColorPart::Shadow, color));
2714        self
2715    }
2716
2717    /// Tailwind's `inset-shadow-2xs`.
2718    fn inset_shadow_2xs(mut self) -> Self {
2719        self.style().push(Declaration::InsetShadow("2xs"));
2720        self
2721    }
2722
2723    /// Tailwind's `inset-shadow-xs`.
2724    fn inset_shadow_xs(mut self) -> Self {
2725        self.style().push(Declaration::InsetShadow("xs"));
2726        self
2727    }
2728
2729    /// Tailwind's `inset-shadow-sm`.
2730    fn inset_shadow_sm(mut self) -> Self {
2731        self.style().push(Declaration::InsetShadow("sm"));
2732        self
2733    }
2734
2735    /// No inset shadow.
2736    fn inset_shadow_none(mut self) -> Self {
2737        self.style().push(Declaration::InsetShadow("none"));
2738        self
2739    }
2740
2741    /// The inset shadow's color (as [`Styled::shadow_color`] for the
2742    /// presets).
2743    fn inset_shadow_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2744        self.style().bind_value(color, |s, color: AdaptiveColor| {
2745            s.push(Declaration::PartColor(ColorPart::InsetShadow, color));
2746        });
2747        self
2748    }
2749
2750    /// A ring `width` wide around the border (a solid shadow; it takes no
2751    /// space), in the text color unless [`Styled::ring_color`].
2752    fn ring(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2753        self.style().bind_value(width, |s, width: AbsoluteLength| {
2754            s.push(Declaration::Ring(Bits(points(width))));
2755        });
2756        self
2757    }
2758
2759    /// The ring's color.
2760    fn ring_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2761        self.style().bind_value(color, |s, color: AdaptiveColor| {
2762            s.push(Declaration::PartColor(ColorPart::Ring, color));
2763        });
2764        self
2765    }
2766
2767    /// A gap of `width` between the border and the ring.
2768    fn ring_offset(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2769        self.style().bind_value(width, |s, width: AbsoluteLength| {
2770            s.push(Declaration::RingOffset(Bits(points(width))));
2771        });
2772        self
2773    }
2774
2775    /// The gap's color (white by default).
2776    fn ring_offset_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2777        self.style().bind_value(color, |s, color: AdaptiveColor| {
2778            s.push(Declaration::PartColor(ColorPart::RingOffset, color));
2779        });
2780        self
2781    }
2782
2783    /// The ring inside the border instead.
2784    fn ring_inset(mut self) -> Self {
2785        self.style().push(Declaration::RingInset);
2786        self
2787    }
2788
2789    /// A second ring `width` wide, inside the border.
2790    fn inset_ring(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2791        self.style().bind_value(width, |s, width: AbsoluteLength| {
2792            s.push(Declaration::InsetRing(Bits(points(width))));
2793        });
2794        self
2795    }
2796
2797    /// The inside ring's color.
2798    fn inset_ring_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2799        self.style().bind_value(color, |s, color: AdaptiveColor| {
2800            s.push(Declaration::PartColor(ColorPart::InsetRing, color));
2801        });
2802        self
2803    }
2804
2805    /// A linear gradient over the background, along `angle` (0 up,
2806    /// `deg(90.0)` right), from [`Styled::gradient_from`] through
2807    /// [`Styled::gradient_via`] to [`Styled::gradient_to`].
2808    fn bg_linear(mut self, angle: impl IntoReactive<Radians>) -> Self {
2809        self.style().bind_value(angle, |s, angle: Radians| {
2810            s.push(Declaration::Gradient(GradientShape::Linear(Bits(angle.0))));
2811        });
2812        self
2813    }
2814
2815    /// A linear gradient towards the top.
2816    fn bg_linear_to_t(self) -> Self {
2817        self.bg_linear(deg(0.0))
2818    }
2819
2820    /// A linear gradient towards the right.
2821    fn bg_linear_to_r(self) -> Self {
2822        self.bg_linear(deg(90.0))
2823    }
2824
2825    /// A linear gradient towards the bottom.
2826    fn bg_linear_to_b(self) -> Self {
2827        self.bg_linear(deg(180.0))
2828    }
2829
2830    /// A linear gradient towards the left.
2831    fn bg_linear_to_l(self) -> Self {
2832        self.bg_linear(deg(270.0))
2833    }
2834
2835    /// A linear gradient towards the top right corner.
2836    fn bg_linear_to_tr(mut self) -> Self {
2837        self.style()
2838            .push(Declaration::Gradient(GradientShape::Corner {
2839                right: true,
2840                bottom: false,
2841            }));
2842        self
2843    }
2844
2845    /// A linear gradient towards the bottom right corner.
2846    fn bg_linear_to_br(mut self) -> Self {
2847        self.style()
2848            .push(Declaration::Gradient(GradientShape::Corner {
2849                right: true,
2850                bottom: true,
2851            }));
2852        self
2853    }
2854
2855    /// A linear gradient towards the bottom left corner.
2856    fn bg_linear_to_bl(mut self) -> Self {
2857        self.style()
2858            .push(Declaration::Gradient(GradientShape::Corner {
2859                right: false,
2860                bottom: true,
2861            }));
2862        self
2863    }
2864
2865    /// A linear gradient towards the top left corner.
2866    fn bg_linear_to_tl(mut self) -> Self {
2867        self.style()
2868            .push(Declaration::Gradient(GradientShape::Corner {
2869                right: false,
2870                bottom: false,
2871            }));
2872        self
2873    }
2874
2875    /// A radial gradient from the center to the farthest corner.
2876    fn bg_radial(mut self) -> Self {
2877        self.style()
2878            .push(Declaration::Gradient(GradientShape::Radial));
2879        self
2880    }
2881
2882    /// A conic gradient around the center, starting at `angle` (0 up).
2883    fn bg_conic(mut self, angle: impl IntoReactive<Radians>) -> Self {
2884        self.style().bind_value(angle, |s, angle: Radians| {
2885            s.push(Declaration::Gradient(GradientShape::Conic(Bits(angle.0))));
2886        });
2887        self
2888    }
2889
2890    /// No gradient.
2891    fn bg_gradient_none(mut self) -> Self {
2892        self.style().push(Declaration::GradientNone);
2893        self
2894    }
2895
2896    /// The gradient's first color (transparent by default).
2897    fn gradient_from(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2898        self.style().bind_value(color, |s, color: AdaptiveColor| {
2899            s.push(Declaration::PartColor(ColorPart::From, color));
2900        });
2901        self
2902    }
2903
2904    /// A color in the middle of the gradient.
2905    fn gradient_via(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2906        self.style().bind_value(color, |s, color: AdaptiveColor| {
2907            s.push(Declaration::PartColor(ColorPart::Via, color));
2908        });
2909        self
2910    }
2911
2912    /// The gradient's last color (transparent by default).
2913    fn gradient_to(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2914        self.style().bind_value(color, |s, color: AdaptiveColor| {
2915            s.push(Declaration::PartColor(ColorPart::To, color));
2916        });
2917        self
2918    }
2919
2920    /// Where the first color is along the gradient (0% by default).
2921    fn gradient_from_position(mut self, at: impl IntoReactive<Percentage>) -> Self {
2922        self.style().bind_value(at, |s, at: Percentage| {
2923            s.push(Declaration::StopPosition(0, Bits(at.0)));
2924        });
2925        self
2926    }
2927
2928    /// Where the middle color is (50% by default).
2929    fn gradient_via_position(mut self, at: impl IntoReactive<Percentage>) -> Self {
2930        self.style().bind_value(at, |s, at: Percentage| {
2931            s.push(Declaration::StopPosition(1, Bits(at.0)));
2932        });
2933        self
2934    }
2935
2936    /// Where the last color is (100% by default).
2937    fn gradient_to_position(mut self, at: impl IntoReactive<Percentage>) -> Self {
2938        self.style().bind_value(at, |s, at: Percentage| {
2939            s.push(Declaration::StopPosition(2, Bits(at.0)));
2940        });
2941        self
2942    }
2943
2944    /// Masks the view and its content with a linear gradient's alpha:
2945    /// opaque stops reveal it, transparent stops hide it. Colors do not tint it.
2946    /// The angle follows CSS (0 up, `deg(90.0)` right). Stops accept colors or
2947    /// `(color, position)` pairs, with typed fractions or lengths. Both arguments
2948    /// accept signals and closures (`Vec<ColorStop>` for reactive stops); static
2949    /// values create no binding.
2950    /// `.mask_linear(deg(90.0), [transparent_black(), black(), transparent_black()])`.
2951    /// An empty stop vector clears the mask reactively. Includes backdrop filters.
2952    /// Not drawn on Windows and GPUI.
2953    fn mask_linear(
2954        mut self,
2955        angle: impl IntoReactive<Radians>,
2956        stops: impl IntoReactive<Vec<ColorStop>>,
2957    ) -> Self {
2958        let angle = angle.into_reactive();
2959        let stops = stops.into_reactive();
2960        let gradient = match (angle, stops) {
2961            (Reactive::Static(angle), Reactive::Static(stops)) => Reactive::Static(Gradient {
2962                kind: GradientKind::Linear { angle },
2963                stops,
2964                repeating: false,
2965            }),
2966            (angle, stops) => Reactive::Bound(Rc::new(move || Gradient {
2967                kind: GradientKind::Linear { angle: angle.get() },
2968                stops: stops.get(),
2969                repeating: false,
2970            })),
2971        };
2972        self.style().bind_value(gradient, |s, gradient| {
2973            s.value(
2974                StyleKey::MaskImage,
2975                PropertyValue::Gradients(if gradient.stops.is_empty() {
2976                    Vec::new().into()
2977                } else {
2978                    vec![gradient].into()
2979                }),
2980            );
2981        });
2982        self
2983    }
2984
2985    /// Masks with an elliptical gradient from the center to the farthest corner.
2986    /// Stops and platform support follow [`Styled::mask_linear`]. Use a
2987    /// `Vec<ColorStop>` for signal/closure results, or an array of colors/pairs
2988    /// for static stops. An empty vector clears the mask reactively.
2989    fn mask_radial(mut self, stops: impl IntoReactive<Vec<ColorStop>>) -> Self {
2990        self.style().bind_value(stops, |s, stops| {
2991            let gradients = if stops.is_empty() {
2992                Vec::new()
2993            } else {
2994                vec![Gradient {
2995                    kind: GradientKind::Radial {
2996                        circle: false,
2997                        size: GradientSize::FarthestCorner,
2998                        x: percentage(0.5),
2999                        y: percentage(0.5),
3000                    },
3001                    stops,
3002                    repeating: false,
3003                }]
3004            };
3005            s.value(
3006                StyleKey::MaskImage,
3007                PropertyValue::Gradients(gradients.into()),
3008            );
3009        });
3010        self
3011    }
3012
3013    /// Clears the gradient mask, including in state styles.
3014    fn mask_none(mut self) -> Self {
3015        self.style().value(
3016            StyleKey::MaskImage,
3017            PropertyValue::Gradients(Vec::new().into()),
3018        );
3019        self
3020    }
3021
3022    /// Clips everything it draws, the elements in it included, to `clip`
3023    /// (CSS's `clip-path: inset(..)`): a rectangle inset from its box with
3024    /// rounded corners, outside which presses reach neither it nor what is
3025    /// in it. Its changes animate with [`Styled::transition_clip_path`]
3026    /// (or [`Styled::transition_all`]), so a panel opens out of a corner:
3027    /// `.clip_path(ClipInset::new().bottom(percentage(1.0)).left(percentage(1.0)).rounded(px(12.0)))`
3028    /// while closed, `.clip_path(ClipInset::new().rounded(px(12.0)))` open.
3029    fn clip_path(mut self, clip: impl IntoReactive<ClipInset>) -> Self {
3030        self.style().bind_value(clip, |s, clip| {
3031            s.value(StyleKey::ClipPath, PropertyValue::ClipPath(Some(clip)));
3032        });
3033        self
3034    }
3035
3036    /// Clears the clip path, including in state styles.
3037    fn clip_path_none(mut self) -> Self {
3038        self.style()
3039            .value(StyleKey::ClipPath, PropertyValue::ClipPath(None));
3040        self
3041    }
3042
3043    /// Blurs it and its content by `radius` (Tailwind's `blur-sm` is 8
3044    /// points).
3045    fn blur(self, radius: impl Into<Points>) -> Self {
3046        filter(self, false, FilterFn::Blur, radius.into().0)
3047    }
3048
3049    /// Brightens (> 1) or darkens (< 1) it.
3050    fn brightness(self, amount: f32) -> Self {
3051        filter(self, false, FilterFn::Brightness, amount)
3052    }
3053
3054    /// Raises (> 1) or lowers (< 1) its contrast.
3055    fn contrast(self, amount: f32) -> Self {
3056        filter(self, false, FilterFn::Contrast, amount)
3057    }
3058
3059    /// Turns it gray (1: fully).
3060    fn grayscale(self, amount: f32) -> Self {
3061        filter(self, false, FilterFn::Grayscale, amount)
3062    }
3063
3064    /// Turns its hues by `angle`.
3065    fn hue_rotate(self, angle: impl Into<Radians>) -> Self {
3066        filter(self, false, FilterFn::HueRotate, angle.into().to_degrees())
3067    }
3068
3069    /// Inverts its colors (1: fully).
3070    fn invert(self, amount: f32) -> Self {
3071        filter(self, false, FilterFn::Invert, amount)
3072    }
3073
3074    /// Saturates (> 1) or desaturates (< 1) it.
3075    fn saturate(self, amount: f32) -> Self {
3076        filter(self, false, FilterFn::Saturate, amount)
3077    }
3078
3079    /// Tones it sepia (1: fully).
3080    fn sepia(self, amount: f32) -> Self {
3081        filter(self, false, FilterFn::Sepia, amount)
3082    }
3083
3084    /// No filters.
3085    fn filter_none(mut self) -> Self {
3086        self.style().push(Declaration::FilterNone(false));
3087        self
3088    }
3089
3090    /// Blurs what is behind it by `radius` (frosted glass; give it a
3091    /// translucent background).
3092    fn backdrop_blur(self, radius: impl Into<Points>) -> Self {
3093        filter(self, true, FilterFn::Blur, radius.into().0)
3094    }
3095
3096    /// Brightens or darkens what is behind it.
3097    fn backdrop_brightness(self, amount: f32) -> Self {
3098        filter(self, true, FilterFn::Brightness, amount)
3099    }
3100
3101    /// Changes the contrast of what is behind it.
3102    fn backdrop_contrast(self, amount: f32) -> Self {
3103        filter(self, true, FilterFn::Contrast, amount)
3104    }
3105
3106    /// Turns what is behind it gray.
3107    fn backdrop_grayscale(self, amount: f32) -> Self {
3108        filter(self, true, FilterFn::Grayscale, amount)
3109    }
3110
3111    /// Turns the hues of what is behind it.
3112    fn backdrop_hue_rotate(self, angle: impl Into<Radians>) -> Self {
3113        filter(self, true, FilterFn::HueRotate, angle.into().to_degrees())
3114    }
3115
3116    /// Inverts what is behind it.
3117    fn backdrop_invert(self, amount: f32) -> Self {
3118        filter(self, true, FilterFn::Invert, amount)
3119    }
3120
3121    /// Fades what is behind it.
3122    fn backdrop_opacity(self, amount: f32) -> Self {
3123        filter(self, true, FilterFn::Opacity, amount)
3124    }
3125
3126    /// Saturates what is behind it.
3127    fn backdrop_saturate(self, amount: f32) -> Self {
3128        filter(self, true, FilterFn::Saturate, amount)
3129    }
3130
3131    /// Tones what is behind it sepia.
3132    fn backdrop_sepia(self, amount: f32) -> Self {
3133        filter(self, true, FilterFn::Sepia, amount)
3134    }
3135
3136    /// No backdrop filters.
3137    fn backdrop_filter_none(mut self) -> Self {
3138        self.style().push(Declaration::FilterNone(true));
3139        self
3140    }
3141
3142    /// How it blends with what is behind it.
3143    fn mix_blend_mode(mut self, mode: BlendMode) -> Self {
3144        self.style()
3145            .value(StyleKey::MixBlendMode, PropertyValue::BlendMode(mode));
3146        self
3147    }
3148
3149    /// Which touches it and the views in it take (`pointerEvents`):
3150    /// `PointerEvents::None` none, for the views in it too unless one says
3151    /// `Auto`; `BoxNone` none on itself; `BoxOnly` none on the views in it.
3152    fn pointer_events(mut self, pointer_events: impl IntoReactive<crate::PointerEvents>) -> Self {
3153        self.style()
3154            .bind_value(pointer_events, |s, p: crate::PointerEvents| {
3155                s.value(
3156                    StyleKey::PointerEvents,
3157                    PropertyValue::PointerEvents(Some(p)),
3158                );
3159            });
3160        self
3161    }
3162
3163    /// Its texts can be selected and copied (`userSelect: "text"`,
3164    /// Tailwind's `select-text`).
3165    fn select_text(mut self) -> Self {
3166        self.style()
3167            .value(StyleKey::UserSelect, PropertyValue::OptBool(Some(true)));
3168        self
3169    }
3170
3171    /// Its texts cannot be selected (`userSelect: "none"`, Tailwind's
3172    /// `select-none`).
3173    fn select_none(mut self) -> Self {
3174        self.style()
3175            .value(StyleKey::UserSelect, PropertyValue::OptBool(Some(false)));
3176        self
3177    }
3178
3179    /// Apple's Liquid Glass behind the element (`glassEffect`; iOS 26 and
3180    /// macOS 26), its `backdropFilter` elsewhere.
3181    fn glass_effect(mut self, glass: crate::GlassEffect) -> Self {
3182        self.style()
3183            .value(StyleKey::GlassEffect, PropertyValue::GlassEffect(glass));
3184        self
3185    }
3186
3187    /// The tint of the glass material (`glassTintColor`). A color tints the
3188    /// native glass; `None` restores its default. Bind an optional adaptive
3189    /// color to set and clear the tint; static colors can be passed directly.
3190    /// Has no effect without `glassEffect`.
3191    fn glass_tint_color(mut self, color: impl IntoReactive<Option<AdaptiveColor>>) -> Self {
3192        self.style()
3193            .bind_value(color, |s, color: Option<AdaptiveColor>| match color {
3194                Some(color) => s.color(&[StyleKey::GlassTintColor], color),
3195                None => s.value(StyleKey::GlassTintColor, PropertyValue::Color(None)),
3196            });
3197        self
3198    }
3199
3200    /// The pointer's look over the element (`cursor`; desktops, and iPad
3201    /// and Android with a mouse).
3202    fn cursor(mut self, cursor: Cursor) -> Self {
3203        self.style()
3204            .value(StyleKey::Cursor, PropertyValue::Cursor(cursor));
3205        self
3206    }
3207
3208    /// The pointing hand over the element: something to press (Tailwind's
3209    /// `cursor-pointer`).
3210    fn cursor_pointer(self) -> Self {
3211        self.cursor(Cursor::Pointer)
3212    }
3213
3214    /// Changes of colors, opacity, shadows and transforms animate
3215    /// (Tailwind's `transition`: 150ms, ease-in-out by default).
3216    fn transition(self) -> Self {
3217        transition(
3218            self,
3219            TransitionProps::COLORS
3220                | TransitionProps::OPACITY
3221                | TransitionProps::SHADOW
3222                | TransitionProps::TRANSFORM,
3223        )
3224    }
3225
3226    /// Changes of everything that can animate do.
3227    fn transition_all(self) -> Self {
3228        transition(self, TransitionProps::ALL)
3229    }
3230
3231    /// Changes of colors animate.
3232    fn transition_colors(self) -> Self {
3233        transition(self, TransitionProps::COLORS)
3234    }
3235
3236    /// Changes of opacity animate.
3237    fn transition_opacity(self) -> Self {
3238        transition(self, TransitionProps::OPACITY)
3239    }
3240
3241    /// Changes of shadows animate.
3242    fn transition_shadow(self) -> Self {
3243        transition(self, TransitionProps::SHADOW)
3244    }
3245
3246    /// Changes of the transform animate.
3247    fn transition_transform(self) -> Self {
3248        transition(self, TransitionProps::TRANSFORM)
3249    }
3250
3251    /// Changes of the clip path animate (CSS's `transition-property:
3252    /// clip-path`).
3253    fn transition_clip_path(self) -> Self {
3254        transition(self, TransitionProps::CLIP_PATH)
3255    }
3256
3257    /// Changes of the mask animate (CSS's `transition-property:
3258    /// mask-image`): gradients of the same shape and stop count move stop
3259    /// by stop; any other change applies at once.
3260    fn transition_mask(self) -> Self {
3261        transition(self, TransitionProps::MASK)
3262    }
3263
3264    /// Changes jump.
3265    fn transition_none(mut self) -> Self {
3266        self.style().push(Declaration::TransitionNone);
3267        self
3268    }
3269
3270    /// Transitions last `ms` milliseconds.
3271    fn duration(mut self, ms: impl IntoReactive<f32>) -> Self {
3272        self.style().bind_value(ms, |s, ms: f32| {
3273            s.push(Declaration::Duration(Bits(ms)));
3274        });
3275        self
3276    }
3277
3278    /// Transitions start after `ms` milliseconds.
3279    fn delay(mut self, ms: impl IntoReactive<f32>) -> Self {
3280        self.style().bind_value(ms, |s, ms: f32| {
3281            s.push(Declaration::Delay(Bits(ms)));
3282        });
3283        self
3284    }
3285
3286    /// Transitions at a constant pace.
3287    fn ease_linear(mut self) -> Self {
3288        self.style().push(Declaration::EasePreset("linear"));
3289        self
3290    }
3291
3292    /// Transitions that start slowly.
3293    fn ease_in(mut self) -> Self {
3294        self.style().push(Declaration::EasePreset("in"));
3295        self
3296    }
3297
3298    /// Transitions that end slowly.
3299    fn ease_out(mut self) -> Self {
3300        self.style().push(Declaration::EasePreset("out"));
3301        self
3302    }
3303
3304    /// Transitions that start and end slowly.
3305    fn ease_in_out(mut self) -> Self {
3306        self.style().push(Declaration::EasePreset("in-out"));
3307        self
3308    }
3309
3310    /// Transitions along the cubic Bézier curve `x1, y1, x2, y2` (a `y`
3311    /// outside 0..1 overshoots).
3312    fn ease_bezier(mut self, x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
3313        self.style()
3314            .push(Declaration::Ease([x1, y1, x2, y2].map(Bits)));
3315        self
3316    }
3317
3318    /// Transitions on a spring's physics (its stiffness, damping and mass;
3319    /// Tailwind extension `ease-spring-[620,36]`): they time themselves,
3320    /// lasting until the spring settles ([`Spring::settle_ms`]), so
3321    /// [`Self::duration`] is not used. A spring that cannot settle (a
3322    /// stiffness, damping or mass that is not positive) sets nothing.
3323    ///
3324    /// [`Spring::settle_ms`]: crate::element::Spring::settle_ms
3325    fn ease_spring(mut self, spring: crate::element::Spring) -> Self {
3326        self.style().push(Declaration::EaseSpring(
3327            [spring.stiffness, spring.damping, spring.mass].map(Bits),
3328        ));
3329        self
3330    }
3331
3332    /// Turns around, forever (Tailwind's `animate-spin`: a loader).
3333    fn animate_spin(mut self) -> Self {
3334        self.style().push(Declaration::Animate(Some(0)));
3335        self
3336    }
3337
3338    /// Scales up and fades out, forever (`animate-ping`: a badge's pulse).
3339    fn animate_ping(mut self) -> Self {
3340        self.style().push(Declaration::Animate(Some(1)));
3341        self
3342    }
3343
3344    /// Fades to half and back, forever (`animate-pulse`: a skeleton).
3345    fn animate_pulse(mut self) -> Self {
3346        self.style().push(Declaration::Animate(Some(2)));
3347        self
3348    }
3349
3350    /// Jumps and lands, forever (`animate-bounce`).
3351    fn animate_bounce(mut self) -> Self {
3352        self.style().push(Declaration::Animate(Some(3)));
3353        self
3354    }
3355
3356    /// A keyframe animation with its own timing (TS: `animationName`
3357    /// with `animationDuration`, `animationDelay`,
3358    /// `animationTimingFunction`, `animationIterationCount`,
3359    /// `animationFrameRate`):
3360    /// `.animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0))`.
3361    fn animation(mut self, animation: KeyframeAnimation) -> Self {
3362        let index = KEYFRAMES
3363            .iter()
3364            .position(|k| *k == animation.keyframes)
3365            .expect("every keyframes") as u8;
3366        self.style().push(Declaration::Animation(
3367            index,
3368            Bits(animation.duration),
3369            Bits(animation.delay),
3370            animation.easing.map(Bits),
3371            animation.iterations,
3372            crate::style::frame_rate(animation.frame_rate).map(Bits),
3373        ));
3374        self
3375    }
3376
3377    /// No keyframe animation.
3378    fn animate_none(mut self) -> Self {
3379        self.style().push(Declaration::Animate(None));
3380        self
3381    }
3382
3383    /// Scales from the center (1 is the natural size).
3384    fn scale(self, scale: impl IntoReactive<f32>) -> Self {
3385        self.transform_step(TransformKind::Scale, scale)
3386    }
3387
3388    /// Scales horizontally.
3389    fn scale_x(self, scale: impl IntoReactive<f32>) -> Self {
3390        self.transform_step(TransformKind::ScaleX, scale)
3391    }
3392
3393    /// Scales vertically.
3394    fn scale_y(self, scale: impl IntoReactive<f32>) -> Self {
3395        self.transform_step(TransformKind::ScaleY, scale)
3396    }
3397
3398    /// Moves horizontally by `offset` (after layout): points, or a
3399    /// fraction of its own width (`relative(-0.5)`).
3400    fn translate_x(self, offset: impl IntoReactive<DefiniteLength>) -> Self {
3401        transform_with(self, offset, |offset| {
3402            translation(
3403                offset,
3404                TransformKind::TranslateX,
3405                TransformKind::TranslateXFraction,
3406            )
3407        })
3408    }
3409
3410    /// Moves vertically by `offset` (after layout): points, or a fraction
3411    /// of its own height.
3412    fn translate_y(self, offset: impl IntoReactive<DefiniteLength>) -> Self {
3413        transform_with(self, offset, |offset| {
3414            translation(
3415                offset,
3416                TransformKind::TranslateY,
3417                TransformKind::TranslateYFraction,
3418            )
3419        })
3420    }
3421
3422    /// Rotates by `angle`, clockwise.
3423    fn rotate(self, angle: impl IntoReactive<Radians>) -> Self {
3424        transform_with(self, angle, |a: Radians| {
3425            (TransformKind::Rotate, a.to_degrees())
3426        })
3427    }
3428
3429    /// Rotates by `angle` around the horizontal axis (3D; in a view with
3430    /// [`Styled::perspective`] it tilts towards the viewer).
3431    fn rotate_x(self, angle: impl IntoReactive<Radians>) -> Self {
3432        transform_with(self, angle, |a: Radians| {
3433            (TransformKind::RotateX, a.to_degrees())
3434        })
3435    }
3436
3437    /// Rotates by `angle` around the vertical axis (3D).
3438    fn rotate_y(self, angle: impl IntoReactive<Radians>) -> Self {
3439        transform_with(self, angle, |a: Radians| {
3440            (TransformKind::RotateY, a.to_degrees())
3441        })
3442    }
3443
3444    /// Slants vertical edges by `angle` (iOS; Android has no skew).
3445    fn skew_x(self, angle: impl IntoReactive<Radians>) -> Self {
3446        transform_with(self, angle, |a: Radians| {
3447            (TransformKind::SkewX, a.to_degrees())
3448        })
3449    }
3450
3451    /// Slants horizontal edges by `angle` (iOS).
3452    fn skew_y(self, angle: impl IntoReactive<Radians>) -> Self {
3453        transform_with(self, angle, |a: Radians| {
3454            (TransformKind::SkewY, a.to_degrees())
3455        })
3456    }
3457
3458    /// Gives its children depth: their 3D rotations are seen from
3459    /// `distance` away (smaller: stronger), from its center (CSS's
3460    /// `perspective`, `perspective-*`).
3461    fn perspective(self, distance: impl IntoReactive<AbsoluteLength>) -> Self {
3462        transform_with(self, distance, |d: AbsoluteLength| {
3463            (TransformKind::Perspective, points(d))
3464        })
3465    }
3466
3467    /// The step `kind` of its transform, by `amount`. The steps compose in
3468    /// CSS's order, whatever the order of the calls: translate, rotate,
3469    /// scale, then the 3D rotations and the skews.
3470    /// [`TransformKind::Perspective`] is [`Styled::perspective`], its
3471    /// children's depth.
3472    fn transform_step(self, kind: TransformKind, amount: impl IntoReactive<f32>) -> Self {
3473        transform_with(self, amount, move |amount| (kind, amount))
3474    }
3475
3476    /// No 3D rotations and skews (CSS's `transform: none`; the
3477    /// translation, rotation and scale are properties of their own, which
3478    /// [`Styled::translate_none`], [`Styled::rotate_none`] and
3479    /// [`Styled::scale_none`] remove).
3480    fn transform_none(self) -> Self {
3481        transform_reset(self, Declaration::TransformNone)
3482    }
3483
3484    /// No translation (also none set before).
3485    fn translate_none(self) -> Self {
3486        transform_reset(self, Declaration::TranslateNone)
3487    }
3488
3489    /// No scale (also none set before).
3490    fn scale_none(self) -> Self {
3491        transform_reset(self, Declaration::ScaleNone)
3492    }
3493
3494    /// No rotation (also none set before; the 3D rotations stay).
3495    fn rotate_none(self) -> Self {
3496        transform_reset(self, Declaration::RotateNone)
3497    }
3498
3499    /// The point its transform turns and scales around (the center by
3500    /// default).
3501    fn transform_origin(mut self, origin: TransformOrigin) -> Self {
3502        let axis = |l: DefiniteLength| match l {
3503            DefiniteLength::Absolute(a) => (false, Bits(a.to_points(REM_SIZE).0)),
3504            DefiniteLength::Fraction(f) => (true, Bits(f.0)),
3505        };
3506        self.style()
3507            .push(Declaration::Origin([axis(origin.x), axis(origin.y)]));
3508        self
3509    }
3510
3511    /// Transforms around its top left corner.
3512    fn origin_top_left(mut self) -> Self {
3513        self.style().value(
3514            StyleKey::TransformOrigin,
3515            PropertyValue::TransformOrigin(origin(0.0, 0.0)),
3516        );
3517        self
3518    }
3519
3520    /// Transforms around the middle of its top edge.
3521    fn origin_top(mut self) -> Self {
3522        self.style().value(
3523            StyleKey::TransformOrigin,
3524            PropertyValue::TransformOrigin(origin(0.5, 0.0)),
3525        );
3526        self
3527    }
3528
3529    /// Transforms around its top right corner.
3530    fn origin_top_right(mut self) -> Self {
3531        self.style().value(
3532            StyleKey::TransformOrigin,
3533            PropertyValue::TransformOrigin(origin(1.0, 0.0)),
3534        );
3535        self
3536    }
3537
3538    /// Transforms around the middle of its left edge.
3539    fn origin_left(mut self) -> Self {
3540        self.style().value(
3541            StyleKey::TransformOrigin,
3542            PropertyValue::TransformOrigin(origin(0.0, 0.5)),
3543        );
3544        self
3545    }
3546
3547    /// Transforms around its center (the default).
3548    fn origin_center(mut self) -> Self {
3549        self.style().value(
3550            StyleKey::TransformOrigin,
3551            PropertyValue::TransformOrigin(origin(0.5, 0.5)),
3552        );
3553        self
3554    }
3555
3556    /// Transforms around the middle of its right edge.
3557    fn origin_right(mut self) -> Self {
3558        self.style().value(
3559            StyleKey::TransformOrigin,
3560            PropertyValue::TransformOrigin(origin(1.0, 0.5)),
3561        );
3562        self
3563    }
3564
3565    /// Transforms around its bottom left corner.
3566    fn origin_bottom_left(mut self) -> Self {
3567        self.style().value(
3568            StyleKey::TransformOrigin,
3569            PropertyValue::TransformOrigin(origin(0.0, 1.0)),
3570        );
3571        self
3572    }
3573
3574    /// Transforms around the middle of its bottom edge.
3575    fn origin_bottom(mut self) -> Self {
3576        self.style().value(
3577            StyleKey::TransformOrigin,
3578            PropertyValue::TransformOrigin(origin(0.5, 1.0)),
3579        );
3580        self
3581    }
3582
3583    /// Transforms around its bottom right corner.
3584    fn origin_bottom_right(mut self) -> Self {
3585        self.style().value(
3586            StyleKey::TransformOrigin,
3587            PropertyValue::TransformOrigin(origin(1.0, 1.0)),
3588        );
3589        self
3590    }
3591
3592    /// How an image or a video fits its box (`objectFit`): `Cover` (an
3593    /// image's default), `Contain` (a video's), `Stretch` (CSS's `fill`),
3594    /// `Center` (`none`) or `ScaleDown`.
3595    fn object_fit(mut self, fit: impl IntoReactive<crate::ResizeMode>) -> Self {
3596        self.style().bind_value(fit, |s, fit: crate::ResizeMode| {
3597            s.value(StyleKey::ObjectFit, PropertyValue::ObjectFit(Some(fit)));
3598        });
3599        self
3600    }
3601
3602    /// Where an image sits in its box once its resize mode has sized it
3603    /// (CSS's `object-position`; the center by default): a covering image
3604    /// is cropped around it.
3605    fn object_position(mut self, position: ObjectPosition) -> Self {
3606        self.style().value(
3607            StyleKey::ObjectPosition,
3608            PropertyValue::ObjectPosition(position),
3609        );
3610        self
3611    }
3612
3613    /// Shows an image's top left corner (Tailwind's `object-top-left`).
3614    fn object_top_left(mut self) -> Self {
3615        self.style().value(
3616            StyleKey::ObjectPosition,
3617            PropertyValue::ObjectPosition(ObjectPosition::new(
3618                PositionAxis::START,
3619                PositionAxis::START,
3620            )),
3621        );
3622        self
3623    }
3624
3625    /// Shows an image's top (Tailwind's `object-top`): a tall image
3626    /// covering its box is cropped at the bottom.
3627    fn object_top(mut self) -> Self {
3628        self.style().value(
3629            StyleKey::ObjectPosition,
3630            PropertyValue::ObjectPosition(ObjectPosition::new(
3631                PositionAxis::CENTER,
3632                PositionAxis::START,
3633            )),
3634        );
3635        self
3636    }
3637
3638    /// Shows an image's top right corner (Tailwind's `object-top-right`).
3639    fn object_top_right(mut self) -> Self {
3640        self.style().value(
3641            StyleKey::ObjectPosition,
3642            PropertyValue::ObjectPosition(ObjectPosition::new(
3643                PositionAxis::END,
3644                PositionAxis::START,
3645            )),
3646        );
3647        self
3648    }
3649
3650    /// Shows an image's left side (Tailwind's `object-left`).
3651    fn object_left(mut self) -> Self {
3652        self.style().value(
3653            StyleKey::ObjectPosition,
3654            PropertyValue::ObjectPosition(ObjectPosition::new(
3655                PositionAxis::START,
3656                PositionAxis::CENTER,
3657            )),
3658        );
3659        self
3660    }
3661
3662    /// Centers an image in its box (Tailwind's `object-center`, the
3663    /// default).
3664    fn object_center(mut self) -> Self {
3665        self.style().value(
3666            StyleKey::ObjectPosition,
3667            PropertyValue::ObjectPosition(ObjectPosition::new(
3668                PositionAxis::CENTER,
3669                PositionAxis::CENTER,
3670            )),
3671        );
3672        self
3673    }
3674
3675    /// Shows an image's right side (Tailwind's `object-right`).
3676    fn object_right(mut self) -> Self {
3677        self.style().value(
3678            StyleKey::ObjectPosition,
3679            PropertyValue::ObjectPosition(ObjectPosition::new(
3680                PositionAxis::END,
3681                PositionAxis::CENTER,
3682            )),
3683        );
3684        self
3685    }
3686
3687    /// Shows an image's bottom left corner (Tailwind's
3688    /// `object-bottom-left`).
3689    fn object_bottom_left(mut self) -> Self {
3690        self.style().value(
3691            StyleKey::ObjectPosition,
3692            PropertyValue::ObjectPosition(ObjectPosition::new(
3693                PositionAxis::START,
3694                PositionAxis::END,
3695            )),
3696        );
3697        self
3698    }
3699
3700    /// Shows an image's bottom (Tailwind's `object-bottom`).
3701    fn object_bottom(mut self) -> Self {
3702        self.style().value(
3703            StyleKey::ObjectPosition,
3704            PropertyValue::ObjectPosition(ObjectPosition::new(
3705                PositionAxis::CENTER,
3706                PositionAxis::END,
3707            )),
3708        );
3709        self
3710    }
3711
3712    /// Shows an image's bottom right corner (Tailwind's
3713    /// `object-bottom-right`).
3714    fn object_bottom_right(mut self) -> Self {
3715        self.style().value(
3716            StyleKey::ObjectPosition,
3717            PropertyValue::ObjectPosition(ObjectPosition::new(
3718                PositionAxis::END,
3719                PositionAxis::END,
3720            )),
3721        );
3722        self
3723    }
3724
3725    /// Invisible while its 3D rotations turn it away (a card's back).
3726    fn backface_hidden(mut self) -> Self {
3727        self.style()
3728            .value(StyleKey::BackfaceVisibility, PropertyValue::Bool(true));
3729        self
3730    }
3731
3732    /// Visible from behind too (the default).
3733    fn backface_visible(mut self) -> Self {
3734        self.style()
3735            .value(StyleKey::BackfaceVisibility, PropertyValue::Bool(false));
3736        self
3737    }
3738
3739    // Text (inherited by the texts inside).
3740
3741    /// The text color.
3742    fn text_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3743        self.style().bind_value(color, |s, color: AdaptiveColor| {
3744            s.color(&[StyleKey::Color], color);
3745        });
3746        self
3747    }
3748
3749    /// The tint color (Tailwind's `tint-*`): of template images, and of a
3750    /// page header's buttons in [`super::Screen::header_style_with`].
3751    fn tint_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3752        self.style().bind_value(color, |s, color: AdaptiveColor| {
3753            s.color(&[StyleKey::TintColor], color);
3754        });
3755        self
3756    }
3757
3758    /// The color a system control shows its state in (`accentColor`, CSS's
3759    /// `accent-color`, Tailwind's `accent-*`), which a native component gets
3760    /// as its `accentColor` prop, such as the track of a system switch when
3761    /// on. Set on the control itself; it is not inherited.
3762    fn accent_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3763        self.style().bind_value(color, |s, color: AdaptiveColor| {
3764            s.color(&[StyleKey::AccentColor], color);
3765        });
3766        self
3767    }
3768
3769    /// What the shapes the element draws are filled with (`fill`,
3770    /// Tailwind's `fill-<color>`; the elements inside inherit it, as in
3771    /// CSS): the areas of `nsh_base::plot`.
3772    fn fill_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3773        self.style().bind_value(color, |s, color: AdaptiveColor| {
3774            s.color(&[StyleKey::Fill], color);
3775        });
3776        self
3777    }
3778
3779    /// No fill (`fill-none`).
3780    fn fill_none(mut self) -> Self {
3781        self.style().value(
3782            StyleKey::Fill,
3783            PropertyValue::Paint(Some(crate::SvgPaint::None)),
3784        );
3785        self
3786    }
3787
3788    /// The text color as the fill (`fill-current`, `currentColor`).
3789    fn fill_current(mut self) -> Self {
3790        self.style().value(
3791            StyleKey::Fill,
3792            PropertyValue::Paint(Some(crate::SvgPaint::CurrentColor)),
3793        );
3794        self
3795    }
3796
3797    /// What the outlines of the shapes the element draws are painted with
3798    /// (`stroke`, Tailwind's `stroke-<color>`; inherited, as in CSS): the
3799    /// lines and grids of `nsh_base::plot`.
3800    fn stroke_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3801        self.style().bind_value(color, |s, color: AdaptiveColor| {
3802            s.color(&[StyleKey::Stroke], color);
3803        });
3804        self
3805    }
3806
3807    /// No stroke (`stroke-none`).
3808    fn stroke_none(mut self) -> Self {
3809        self.style().value(
3810            StyleKey::Stroke,
3811            PropertyValue::Paint(Some(crate::SvgPaint::None)),
3812        );
3813        self
3814    }
3815
3816    /// The text color as the stroke (`stroke-current`, `currentColor`).
3817    fn stroke_current(mut self) -> Self {
3818        self.style().value(
3819            StyleKey::Stroke,
3820            PropertyValue::Paint(Some(crate::SvgPaint::CurrentColor)),
3821        );
3822        self
3823    }
3824
3825    /// The width of those outlines (`strokeWidth`, Tailwind's
3826    /// `stroke-<number>`; 1 by default, inherited).
3827    fn stroke_width(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
3828        self.style().bind_value(width, |s, width: AbsoluteLength| {
3829            s.number(StyleKey::StrokeWidth, points(width));
3830        });
3831        self
3832    }
3833
3834    /// The font size, in points.
3835    fn text_size(mut self, size: impl IntoReactive<Length>) -> Self {
3836        self.style().bind_value(size, |s, size: Length| {
3837            s.lengths(&[StyleKey::FontSize], size);
3838        });
3839        self
3840    }
3841
3842    /// 12pt text, 16pt lines.
3843    fn text_xs(mut self) -> Self {
3844        self.style().push(Declaration::TextPreset("xs"));
3845        self
3846    }
3847
3848    /// 14pt text, 20pt lines.
3849    fn text_sm(mut self) -> Self {
3850        self.style().push(Declaration::TextPreset("sm"));
3851        self
3852    }
3853
3854    /// 16pt text, 24pt lines.
3855    fn text_base(mut self) -> Self {
3856        self.style().push(Declaration::TextPreset("base"));
3857        self
3858    }
3859
3860    /// 18pt text, 28pt lines.
3861    fn text_lg(mut self) -> Self {
3862        self.style().push(Declaration::TextPreset("lg"));
3863        self
3864    }
3865
3866    /// 20pt text, 28pt lines.
3867    fn text_xl(mut self) -> Self {
3868        self.style().push(Declaration::TextPreset("xl"));
3869        self
3870    }
3871
3872    /// 24pt text, 32pt lines.
3873    fn text_2xl(mut self) -> Self {
3874        self.style().push(Declaration::TextPreset("2xl"));
3875        self
3876    }
3877
3878    /// 30pt text, 36pt lines.
3879    fn text_3xl(mut self) -> Self {
3880        self.style().push(Declaration::TextPreset("3xl"));
3881        self
3882    }
3883
3884    /// 36pt text, 40pt lines.
3885    fn text_4xl(mut self) -> Self {
3886        self.style().push(Declaration::TextPreset("4xl"));
3887        self
3888    }
3889
3890    /// 48pt text, 48pt lines.
3891    fn text_5xl(mut self) -> Self {
3892        self.style().push(Declaration::TextPreset("5xl"));
3893        self
3894    }
3895
3896    /// 60pt text, 60pt lines.
3897    fn text_6xl(mut self) -> Self {
3898        self.style().push(Declaration::TextPreset("6xl"));
3899        self
3900    }
3901
3902    /// 72pt text, 72pt lines.
3903    fn text_7xl(mut self) -> Self {
3904        self.style().push(Declaration::TextPreset("7xl"));
3905        self
3906    }
3907
3908    /// 96pt text, 96pt lines.
3909    fn text_8xl(mut self) -> Self {
3910        self.style().push(Declaration::TextPreset("8xl"));
3911        self
3912    }
3913
3914    /// 128pt text, 128pt lines.
3915    fn text_9xl(mut self) -> Self {
3916        self.style().push(Declaration::TextPreset("9xl"));
3917        self
3918    }
3919
3920    /// The line height: points (`px(20.0)`), or a multiple of the font
3921    /// size (`LineHeight::Multiple(1.5)`).
3922    fn line_height(mut self, height: impl IntoReactive<LineHeight>) -> Self {
3923        self.style().bind_value(height, |s, height: LineHeight| {
3924            s.value(StyleKey::LineHeight, PropertyValue::LineHeight(height));
3925        });
3926        self
3927    }
3928
3929    /// The font weight.
3930    fn font_weight(mut self, weight: FontWeight) -> Self {
3931        self.style().number(StyleKey::FontWeight, weight.0 as f32);
3932        self
3933    }
3934
3935    /// The font family (`None` style: the system font is the default).
3936    fn font_family(mut self, family: impl IntoReactive<SharedString>) -> Self {
3937        self.style().bind_value(family, |s, family: SharedString| {
3938            s.value(
3939                StyleKey::FontFamily,
3940                PropertyValue::FontFamily(Some(crate::FontFamily::new(family.trim()))),
3941            );
3942        });
3943        self
3944    }
3945
3946    /// Italic text.
3947    fn italic(mut self) -> Self {
3948        self.style()
3949            .value(StyleKey::FontStyle, PropertyValue::OptBool(Some(true)));
3950        self
3951    }
3952
3953    /// Underlined text (with [`Styled::line_through`], both lines).
3954    fn underline(mut self) -> Self {
3955        self.style().push(Declaration::Decoration(UNDERLINE));
3956        self
3957    }
3958
3959    /// Struck-through text (with [`Styled::underline`], both lines).
3960    fn line_through(mut self) -> Self {
3961        self.style().push(Declaration::Decoration(LINE_THROUGH));
3962        self
3963    }
3964
3965    /// No underline nor strike-through.
3966    fn no_underline(mut self) -> Self {
3967        self.style().push(Declaration::Decoration(0));
3968        self
3969    }
3970
3971    /// The color of the underline and strike-through (the text's by
3972    /// default).
3973    fn text_decoration_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3974        self.style().bind_value(color, |s, color: AdaptiveColor| {
3975            s.color(&[StyleKey::TextDecorationColor], color);
3976        });
3977        self
3978    }
3979
3980    /// Solid decoration lines (the default).
3981    fn text_decoration_solid(mut self) -> Self {
3982        self.style().value(
3983            StyleKey::TextDecorationStyle,
3984            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Solid)),
3985        );
3986        self
3987    }
3988
3989    /// Double decoration lines.
3990    fn text_decoration_double(mut self) -> Self {
3991        self.style().value(
3992            StyleKey::TextDecorationStyle,
3993            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Double)),
3994        );
3995        self
3996    }
3997
3998    /// Dotted decoration lines.
3999    fn text_decoration_dotted(mut self) -> Self {
4000        self.style().value(
4001            StyleKey::TextDecorationStyle,
4002            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Dotted)),
4003        );
4004        self
4005    }
4006
4007    /// Dashed decoration lines.
4008    fn text_decoration_dashed(mut self) -> Self {
4009        self.style().value(
4010            StyleKey::TextDecorationStyle,
4011            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Dashed)),
4012        );
4013        self
4014    }
4015
4016    /// Wavy decoration lines (spelling marks).
4017    fn text_decoration_wavy(mut self) -> Self {
4018        self.style().value(
4019            StyleKey::TextDecorationStyle,
4020            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Wavy)),
4021        );
4022        self
4023    }
4024
4025    /// The decoration lines' thickness.
4026    fn text_decoration_thickness(mut self, thickness: impl IntoReactive<Points>) -> Self {
4027        self.style().bind_value(thickness, |s, thickness: Points| {
4028            s.number(StyleKey::TextDecorationThickness, thickness.0);
4029        });
4030        self
4031    }
4032
4033    /// The underline's distance below the baseline.
4034    fn underline_offset(mut self, offset: impl IntoReactive<Points>) -> Self {
4035        self.style().bind_value(offset, |s, offset: Points| {
4036            s.number(StyleKey::TextUnderlineOffset, offset.0);
4037        });
4038        self
4039    }
4040
4041    /// Shown in capitals (the content stays as it is).
4042    fn uppercase(mut self) -> Self {
4043        self.style().value(
4044            StyleKey::TextTransform,
4045            PropertyValue::TextTransform(Some(crate::TextTransform::Uppercase)),
4046        );
4047        self
4048    }
4049
4050    /// Shown in small letters.
4051    fn lowercase(mut self) -> Self {
4052        self.style().value(
4053            StyleKey::TextTransform,
4054            PropertyValue::TextTransform(Some(crate::TextTransform::Lowercase)),
4055        );
4056        self
4057    }
4058
4059    /// Each word shown with a capital first letter.
4060    fn capitalize(mut self) -> Self {
4061        self.style().value(
4062            StyleKey::TextTransform,
4063            PropertyValue::TextTransform(Some(crate::TextTransform::Capitalize)),
4064        );
4065        self
4066    }
4067
4068    /// Shown as written (undoes an inherited case).
4069    fn normal_case(mut self) -> Self {
4070        self.style().value(
4071            StyleKey::TextTransform,
4072            PropertyValue::TextTransform(Some(crate::TextTransform::None)),
4073        );
4074        self
4075    }
4076
4077    /// Digits of one width, for columns of numbers.
4078    fn tabular_nums(self) -> Self {
4079        font_variant(
4080            self,
4081            FontVariant::TABULAR_NUMS,
4082            FontVariant::PROPORTIONAL_NUMS,
4083        )
4084    }
4085
4086    /// Digits of their own widths (the default).
4087    fn proportional_nums(self) -> Self {
4088        font_variant(
4089            self,
4090            FontVariant::PROPORTIONAL_NUMS,
4091            FontVariant::TABULAR_NUMS,
4092        )
4093    }
4094
4095    /// Old-style digits, with ascenders and descenders.
4096    fn oldstyle_nums(self) -> Self {
4097        font_variant(self, FontVariant::OLDSTYLE_NUMS, FontVariant::LINING_NUMS)
4098    }
4099
4100    /// Lining digits, all of capital height.
4101    fn lining_nums(self) -> Self {
4102        font_variant(self, FontVariant::LINING_NUMS, FontVariant::OLDSTYLE_NUMS)
4103    }
4104
4105    /// Small capitals for lower-case letters.
4106    fn small_caps(self) -> Self {
4107        font_variant(self, FontVariant::SMALL_CAPS, 0)
4108    }
4109
4110    /// The font's own number forms (undoes the number forms set before;
4111    /// `small_caps` stays).
4112    fn normal_nums(self) -> Self {
4113        font_variant(self, 0, !FontVariant::SMALL_CAPS)
4114    }
4115
4116    /// The layout direction of the view and its subtree (by default its
4117    /// parent's; the surface's follows the user's language).
4118    fn direction(mut self, direction: impl IntoReactive<LayoutDirection>) -> Self {
4119        self.style()
4120            .bind_value(direction, |s, direction: LayoutDirection| {
4121                s.value(
4122                    StyleKey::Direction,
4123                    PropertyValue::OptBool(match direction {
4124                        LayoutDirection::Inherit => None,
4125                        LayoutDirection::Ltr => Some(false),
4126                        LayoutDirection::Rtl => Some(true),
4127                    }),
4128                );
4129            });
4130        self
4131    }
4132
4133    /// At most `lines` lines (`numberOfLines`; 0: no limit), the last one cut
4134    /// as [`Styled::text_overflow`] says.
4135    fn number_of_lines(mut self, lines: impl IntoReactive<u32>) -> Self {
4136        self.style().bind_value(lines, |s, lines: u32| {
4137            s.value(
4138                StyleKey::NumberOfLines,
4139                PropertyValue::NumberOfLines(Some(lines)),
4140            );
4141        });
4142        self
4143    }
4144
4145    /// Where a clamped text is cut (`textOverflow`): its end with an
4146    /// ellipsis (`Tail`, the default), its start or middle, or clipped.
4147    fn text_overflow(mut self, mode: impl IntoReactive<crate::EllipsizeMode>) -> Self {
4148        self.style()
4149            .bind_value(mode, |s, mode: crate::EllipsizeMode| {
4150                s.value(
4151                    StyleKey::TextOverflow,
4152                    PropertyValue::TextOverflow(Some(mode)),
4153                );
4154            });
4155        self
4156    }
4157
4158    /// One line, cut with an ellipsis (Tailwind's `truncate`).
4159    fn truncate(self) -> Self {
4160        self.number_of_lines(1u32)
4161            .text_overflow(crate::EllipsizeMode::Tail)
4162    }
4163
4164    /// Its texts' lines never wrap (Tailwind's `whitespace-nowrap`). A
4165    /// view's reaches the texts in it, as CSS's `white-space` does.
4166    fn whitespace_nowrap(mut self) -> Self {
4167        self.style().push(Declaration::NoWrap(true));
4168        self
4169    }
4170
4171    /// Its texts' lines wrap (Tailwind's `whitespace-normal`): undoes a
4172    /// view's `whitespace_nowrap` or `text_pretty` around them.
4173    fn whitespace_normal(mut self) -> Self {
4174        self.style().push(Declaration::NoWrap(false));
4175        self
4176    }
4177
4178    /// Its texts' lines wrap without leaving a word or two alone on the
4179    /// last line (Tailwind's `text-pretty`): a last line shorter than a
4180    /// quarter of the box takes words from the lines above, without adding
4181    /// a line. A view's reaches the texts in it.
4182    fn text_pretty(mut self) -> Self {
4183        self.style().push(Declaration::Pretty);
4184        self
4185    }
4186
4187    /// The text's base direction (by default its content's).
4188    fn writing_direction(mut self, direction: WritingDirection) -> Self {
4189        self.style().value(
4190            StyleKey::WritingDirection,
4191            PropertyValue::OptBool(match direction {
4192                WritingDirection::Auto => None,
4193                WritingDirection::Ltr => Some(false),
4194                WritingDirection::Rtl => Some(true),
4195            }),
4196        );
4197        self
4198    }
4199
4200    /// Lines stretched to both edges.
4201    fn text_justify(mut self) -> Self {
4202        self.style().value(
4203            StyleKey::TextAlign,
4204            PropertyValue::TextAlign(Some(crate::TextAlign::Justify), false),
4205        );
4206        self
4207    }
4208
4209    /// Tailwind's `text-shadow-2xs`.
4210    fn text_shadow_2xs(mut self) -> Self {
4211        self.style().push(Declaration::TextShadow("2xs"));
4212        self
4213    }
4214
4215    /// Tailwind's `text-shadow-xs`.
4216    fn text_shadow_xs(mut self) -> Self {
4217        self.style().push(Declaration::TextShadow("xs"));
4218        self
4219    }
4220
4221    /// Tailwind's `text-shadow-sm`.
4222    fn text_shadow_sm(mut self) -> Self {
4223        self.style().push(Declaration::TextShadow("sm"));
4224        self
4225    }
4226
4227    /// Tailwind's `text-shadow-md`.
4228    fn text_shadow_md(mut self) -> Self {
4229        self.style().push(Declaration::TextShadow("md"));
4230        self
4231    }
4232
4233    /// Tailwind's `text-shadow-lg`.
4234    fn text_shadow_lg(mut self) -> Self {
4235        self.style().push(Declaration::TextShadow("lg"));
4236        self
4237    }
4238
4239    /// No text shadow from the presets.
4240    fn text_shadow_none(mut self) -> Self {
4241        self.style().push(Declaration::TextShadow("none"));
4242        self
4243    }
4244
4245    /// The text shadow's color: of a preset or of [`Styled::text_shadow`]'s
4246    /// layers (an opaque color keeps their alpha).
4247    fn text_shadow_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
4248        let color = color.into();
4249        self.style()
4250            .push(Declaration::PartColor(ColorPart::TextShadow, color));
4251        self
4252    }
4253
4254    /// Text shadows of its own (CSS's `text-shadow`: offsets, blur and
4255    /// color), instead of a preset's; drawn as the widest one.
4256    fn text_shadow(mut self, layers: impl IntoIterator<Item = crate::TextShadow>) -> Self {
4257        let layers: Arc<[crate::TextShadow]> = layers.into_iter().collect();
4258        self.style()
4259            .push(Declaration::TextShadows(TextLayers(layers)));
4260        self
4261    }
4262
4263    /// Text aligned left.
4264    fn text_left(mut self) -> Self {
4265        self.style().value(
4266            StyleKey::TextAlign,
4267            PropertyValue::TextAlign(Some(crate::TextAlign::Left), true),
4268        );
4269        self
4270    }
4271
4272    /// Text centered.
4273    fn text_center(mut self) -> Self {
4274        self.style().value(
4275            StyleKey::TextAlign,
4276            PropertyValue::TextAlign(Some(crate::TextAlign::Center), false),
4277        );
4278        self
4279    }
4280
4281    /// Text aligned right.
4282    fn text_right(mut self) -> Self {
4283        self.style().value(
4284            StyleKey::TextAlign,
4285            PropertyValue::TextAlign(Some(crate::TextAlign::Right), true),
4286        );
4287        self
4288    }
4289
4290    /// The first line of every paragraph indented by `indent` from the
4291    /// leading edge (CSS's `text-indent`); a negative value is 0, the first
4292    /// line not hanging into the margin.
4293    fn text_indent(mut self, indent: impl IntoReactive<AbsoluteLength>) -> Self {
4294        self.style()
4295            .bind_value(indent, |s, indent: AbsoluteLength| {
4296                s.value(
4297                    StyleKey::TextIndent,
4298                    PropertyValue::TextIndent(Some(crate::geometry::px(points(indent))), None),
4299                );
4300            });
4301        self
4302    }
4303
4304    /// Inside a text, its bottom on the baseline (the default:
4305    /// `align-baseline`).
4306    fn align_baseline(mut self) -> Self {
4307        self.style().value(
4308            StyleKey::VerticalAlign,
4309            PropertyValue::VerticalAlign(crate::VerticalAlign::Baseline),
4310        );
4311        self
4312    }
4313
4314    /// Inside a text, its top at the top of the text's font
4315    /// (`align-text-top`).
4316    fn align_text_top(mut self) -> Self {
4317        self.style().value(
4318            StyleKey::VerticalAlign,
4319            PropertyValue::VerticalAlign(crate::VerticalAlign::TextTop),
4320        );
4321        self
4322    }
4323
4324    /// Inside a text, its bottom at the bottom of the text's font
4325    /// (`align-text-bottom`).
4326    fn align_text_bottom(mut self) -> Self {
4327        self.style().value(
4328            StyleKey::VerticalAlign,
4329            PropertyValue::VerticalAlign(crate::VerticalAlign::TextBottom),
4330        );
4331        self
4332    }
4333
4334    /// Inside a text, its middle half the font's x height above the
4335    /// baseline (`align-middle`).
4336    fn align_middle(mut self) -> Self {
4337        self.style().value(
4338            StyleKey::VerticalAlign,
4339            PropertyValue::VerticalAlign(crate::VerticalAlign::Middle),
4340        );
4341        self
4342    }
4343
4344    /// Extra space between letters.
4345    fn letter_spacing(mut self, spacing: impl IntoReactive<AbsoluteLength>) -> Self {
4346        self.style()
4347            .bind_value(spacing, |s, spacing: AbsoluteLength| {
4348                s.number(StyleKey::LetterSpacing, points(spacing));
4349            });
4350        self
4351    }
4352
4353    // Variants (native: nothing runs).
4354
4355    /// `f`'s styles while `when` holds: a value decides once, a signal or a
4356    /// closure switches them as it changes (Tailwind's classes made
4357    /// conditional; native states such as `.active` need none).
4358    fn style_when(
4359        mut self,
4360        when: impl IntoReactive<bool>,
4361        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4362    ) -> Self {
4363        let layer = f(StyleRefinement::default());
4364        match when.into_reactive() {
4365            Reactive::Static(true) => self.style().extend_as(Variant::default(), layer),
4366            Reactive::Static(false) => {}
4367            Reactive::Bound(when) => self.style().bind(move |s| {
4368                if when() {
4369                    s.extend_as(Variant::default(), layer.resolved());
4370                }
4371            }),
4372        }
4373        self
4374    }
4375
4376    /// The styles `f` makes, made again when what it reads changes (any
4377    /// style that depends on the app's state; a value that changes alone
4378    /// is better given to its method: `.w(move || px(width.get()))`).
4379    fn style_with(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
4380        self.style().bind(move |s| {
4381            let made = f(StyleRefinement::default()).resolved();
4382            s.extend_as(Variant::default(), made);
4383        });
4384        self
4385    }
4386
4387    /// Styles in dark appearance (Tailwind's `dark:`), for what is not a
4388    /// color: theme colors switch by themselves.
4389    fn dark(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4390        let s = f(StyleRefinement::default());
4391        self.style().extend_as(Variant::DARK, s);
4392        self
4393    }
4394
4395    /// Styles while selected (Tailwind's `selected:`): the element's
4396    /// accessibility state says so (a `Button`'s `selected`, a tab's).
4397    fn selected(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4398        let s = f(StyleRefinement::default());
4399        self.style().extend_as(Variant::SELECTED, s);
4400        self
4401    }
4402
4403    /// Styles while checked (Tailwind's `checked:`): the element's
4404    /// accessibility state says so, not mixed (a checkbox's, a switch's, a
4405    /// radio's), or the control it is a part of is
4406    /// (`Interactive::project_checked`: a switch's thumb).
4407    fn checked(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4408        let s = f(StyleRefinement::default());
4409        self.style().extend_as(Variant::CHECKED, s);
4410        self
4411    }
4412
4413    /// Styles while indeterminate (Tailwind's `indeterminate:`): the
4414    /// element's accessibility state says checked is mixed (a checkbox
4415    /// that is neither), or the control it is a part of is
4416    /// (`Interactive::project_indeterminate`: a checkbox's indicator).
4417    fn indeterminate(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4418        let s = f(StyleRefinement::default());
4419        self.style().extend_as(Variant::INDETERMINATE, s);
4420        self
4421    }
4422
4423    /// Styles while expanded (Tailwind's `aria-expanded:`): the element's
4424    /// accessibility state says so (a `Popover`'s or `Menu`'s trigger
4425    /// while its popup is open, a collapsible's header).
4426    fn expanded(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4427        let s = f(StyleRefinement::default());
4428        self.style().extend_as(Variant::EXPANDED, s);
4429        self
4430    }
4431
4432    /// Styles while a toggle button is on (Tailwind's `aria-pressed:`):
4433    /// the element's accessibility state says it is pressed, not mixed
4434    /// (`gpui-base`'s `Toggle` styled `pressed`). Not `.active(..)`, a
4435    /// press in progress.
4436    fn aria_pressed(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4437        let s = f(StyleRefinement::default());
4438        self.style().extend_as(Variant::ARIA_PRESSED, s);
4439        self
4440    }
4441
4442    /// Makes it a group: the `group_*` styles of the elements inside follow
4443    /// its press, hover and focus (Tailwind's `group`).
4444    fn group(mut self) -> Self {
4445        self.style().push(Declaration::Group(""));
4446        self
4447    }
4448
4449    /// Makes it the group `name` (`group/name`), for `group_*_named`
4450    /// styles inside it that skip nearer groups.
4451    fn group_named(mut self, name: &'static str) -> Self {
4452        self.style().push(Declaration::Group(name));
4453        self
4454    }
4455
4456    /// Styles while the nearest [`Styled::group`] around it is pressed
4457    /// (`group-active:`).
4458    fn group_active(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4459        in_group(self, "", state::PRESSED, f)
4460    }
4461
4462    /// Styles while the nearest group around it is hovered.
4463    fn group_hover(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4464        in_group(self, "", state::HOVERED, f)
4465    }
4466
4467    /// Styles while an input in the nearest group around it has focus
4468    /// (`group-focus-within:`).
4469    fn group_focus_within(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4470        in_group(self, "", state::FOCUS_WITHIN, f)
4471    }
4472
4473    /// Styles while the nearest group around it has the keyboard focus
4474    /// and shows it (`group-focus-visible:`).
4475    fn group_focus_visible(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4476        in_group(self, "", state::FOCUS_VISIBLE, f)
4477    }
4478
4479    /// Styles while the group `name` around it is pressed
4480    /// (`group-active/name:`).
4481    fn group_active_named(
4482        self,
4483        name: &'static str,
4484        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4485    ) -> Self {
4486        in_group(self, name, state::PRESSED, f)
4487    }
4488
4489    /// Styles while the group `name` around it is hovered.
4490    fn group_hover_named(
4491        self,
4492        name: &'static str,
4493        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4494    ) -> Self {
4495        in_group(self, name, state::HOVERED, f)
4496    }
4497
4498    /// Styles while an input in the group `name` around it has focus.
4499    fn group_focus_within_named(
4500        self,
4501        name: &'static str,
4502        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4503    ) -> Self {
4504        in_group(self, name, state::FOCUS_WITHIN, f)
4505    }
4506
4507    /// Styles while the group `name` around it has the keyboard focus and
4508    /// shows it (`group-focus-visible/name:`).
4509    fn group_focus_visible_named(
4510        self,
4511        name: &'static str,
4512        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4513    ) -> Self {
4514        in_group(self, name, state::FOCUS_VISIBLE, f)
4515    }
4516}
4517
4518/// `s` with filter `f` by `amount` (of what is behind it when `backdrop`).
4519/// `s` with the transform step `step` makes of `value` (its kind and
4520/// operand).
4521fn transform_with<S: Styled, T: Clone + 'static>(
4522    mut s: S,
4523    value: impl IntoReactive<T>,
4524    step: impl Fn(T) -> (TransformKind, f32) + 'static,
4525) -> S {
4526    // Steps compose in order: after a bound part, a static step is
4527    // applied with the bound ones too.
4528    let style = s.style();
4529    match value.into_reactive() {
4530        Reactive::Static(value) if !style.is_bound() => {
4531            let (kind, amount) = step(value);
4532            style.push(Declaration::Transform(kind, Bits(amount)));
4533        }
4534        value => style.bind(move |st| {
4535            let (kind, amount) = step(value.get());
4536            st.push(Declaration::Transform(kind, Bits(amount)));
4537        }),
4538    }
4539    s
4540}
4541
4542/// `reset` (`transform_none()`, ...), in order with the bound steps.
4543fn transform_reset<S: Styled>(mut s: S, reset: Declaration) -> S {
4544    let style = s.style();
4545    if style.is_bound() {
4546        style.bind(move |st| st.push(reset.clone()));
4547    } else {
4548        style.push(reset);
4549    }
4550    s
4551}
4552
4553/// A translation's step: points (a rem at [`REM_SIZE`]) or a fraction of
4554/// the size.
4555fn translation(
4556    offset: DefiniteLength,
4557    points_kind: TransformKind,
4558    fraction_kind: TransformKind,
4559) -> (TransformKind, f32) {
4560    match offset {
4561        DefiniteLength::Absolute(a) => (points_kind, points(a)),
4562        DefiniteLength::Fraction(f) => (fraction_kind, f.0),
4563    }
4564}
4565
4566fn filter<S: Styled>(mut s: S, backdrop: bool, f: FilterFn, amount: f32) -> S {
4567    s.style()
4568        .push(Declaration::Filter(backdrop, f, Bits(amount)));
4569    s
4570}
4571
4572/// `s` with transitions of the [`TransitionProps`] `props`.
4573fn transition<S: Styled>(mut s: S, props: u8) -> S {
4574    s.style().push(Declaration::Transition(props));
4575    s
4576}
4577
4578/// `s` with `f`'s styles while the group `name` is in `states`.
4579fn in_group<S: Styled>(
4580    mut s: S,
4581    name: &'static str,
4582    states: u16,
4583    f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4584) -> S {
4585    let styles = f(StyleRefinement::default());
4586    let style = s.style();
4587    let group = style.name(name);
4588    style.extend_as(
4589        Variant {
4590            group_states: states,
4591            group,
4592            ..Variant::default()
4593        },
4594        styles,
4595    );
4596    s
4597}
4598
4599impl Styled for StyleRefinement {
4600    fn style(&mut self) -> &mut StyleRefinement {
4601        self
4602    }
4603}
4604
4605#[cfg(test)]
4606mod tests {
4607    use super::*;
4608    use crate::{
4609        Style,
4610        color::{black, rgba},
4611        element::palette::{EMERALD, PINK, RED, SKY, VIOLET},
4612        geometry::point,
4613        tailwind::{ClassEnvironment, ClassProps, Context},
4614    };
4615
4616    /// What `list` resolves to in `dark` appearance, in [`state`] `states`,
4617    /// inside a group in `group` (as text, to compare).
4618    fn resolve(list: &ClassList, dark: bool, states: u16, group: u16) -> String {
4619        resolve_with(list, dark, states, group, &|_| {})
4620    }
4621
4622    /// [`resolve`], then `inline` on the style.
4623    fn resolve_with(
4624        list: &ClassList,
4625        dark: bool,
4626        states: u16,
4627        group: u16,
4628        inline: &dyn Fn(&mut Style),
4629    ) -> String {
4630        let cx = Context {
4631            env: ClassEnvironment {
4632                dark,
4633                ..Default::default()
4634            },
4635            window: crate::geometry::size_pt(390.0, 844.0),
4636            rtl: false,
4637            states,
4638            position: 0,
4639            group: &|_| group,
4640        };
4641        let mut style = Style::default();
4642        let mut props = ClassProps::default();
4643        list.apply(&cx, &PRESETS, &mut style, &mut props, inline);
4644        format!("{style:?} {props:?}")
4645    }
4646
4647    /// `typed` styles an element as Tailwind's `classes` do, in both
4648    /// appearances and in every state.
4649    #[track_caller]
4650    fn same(typed: StyleRefinement, classes: &str) {
4651        same_with(typed, classes, &|_| {});
4652    }
4653
4654    /// [`same`], `classes` then `inline` (what classes cannot say).
4655    #[track_caller]
4656    fn same_with(typed: StyleRefinement, classes: &str, inline: &dyn Fn(&mut Style)) {
4657        let typed = typed.lower();
4658        let parsed = tailwind::parse(&PRESETS, classes);
4659        assert!(parsed.unknown().is_empty(), "{:?}", parsed.unknown());
4660        assert_eq!(typed.deps(), parsed.deps(), "{classes}: deps");
4661        assert_eq!(typed.groups(), parsed.groups(), "{classes}: groups");
4662        for dark in [false, true] {
4663            for states in [0, state::PRESSED, state::DISABLED] {
4664                for group in [0, state::PRESSED, state::HOVERED] {
4665                    assert_eq!(
4666                        resolve(&typed, dark, states, group),
4667                        resolve_with(&parsed, dark, states, group, inline),
4668                        "{classes} (dark {dark}, states {states}, group {group})"
4669                    );
4670                }
4671            }
4672        }
4673    }
4674
4675    fn s() -> StyleRefinement {
4676        StyleRefinement::default()
4677    }
4678
4679    #[test]
4680    fn env_methods_are_the_arbitrary_classes() {
4681        let env_of = |list: &ClassList| {
4682            let cx = Context {
4683                env: ClassEnvironment::default(),
4684                window: crate::geometry::size_pt(390.0, 844.0),
4685                rtl: false,
4686                states: 0,
4687                position: 0,
4688                group: &|_| 0,
4689            };
4690            let mut style = Style::default();
4691            list.apply(
4692                &cx,
4693                &PRESETS,
4694                &mut style,
4695                &mut ClassProps::default(),
4696                |_: &mut Style| {},
4697            );
4698            style.pending.env
4699        };
4700        let sides = |p: &str| {
4701            ["top", "right", "bottom", "left"]
4702                .map(|side| format!("{p}{}-[env(safe-area-inset-{side})]", &side[..1]))
4703                .join(" ")
4704        };
4705        for (typed, classes) in [
4706            (s().p_safe_area(), sides("p")),
4707            (s().m_safe_area(), sides("m")),
4708            (
4709                s().px_safe_area(),
4710                "pr-[env(safe-area-inset-right)] pl-[env(safe-area-inset-left)]".into(),
4711            ),
4712            (
4713                s().my_safe_area(),
4714                "mt-[env(safe-area-inset-top)] mb-[env(safe-area-inset-bottom)]".into(),
4715            ),
4716            (s().pl_safe_area(), "pl-[env(safe-area-inset-left)]".into()),
4717            (
4718                s().pt_safe_area_plus(px(8.0)),
4719                "pt-[calc(env(safe-area-inset-top)+8px)]".into(),
4720            ),
4721            (s().pb_keyboard(), "pb-[env(keyboard-inset-height)]".into()),
4722            (
4723                s().mb_keyboard_plus(px(49.0)),
4724                "mb-[calc(env(keyboard-inset-height)+49px)]".into(),
4725            ),
4726        ] {
4727            same(typed.clone(), &classes);
4728            let parsed = tailwind::parse(&PRESETS, &classes);
4729            assert_eq!(env_of(&typed.lower()), env_of(&parsed), "{classes}");
4730            assert!(!env_of(&parsed).is_empty(), "{classes}");
4731        }
4732    }
4733
4734    #[test]
4735    fn svg_paint_is_tailwinds() {
4736        same(
4737            s().fill_color(RED.shade(600))
4738                .stroke_color(SKY.shade(500))
4739                .stroke_width(px(2.0)),
4740            "fill-red-600 stroke-sky-500 stroke-2",
4741        );
4742        same(s().fill_none().stroke_current(), "fill-none stroke-current");
4743        same(s().fill_current().stroke_none(), "fill-current stroke-none");
4744    }
4745
4746    #[test]
4747    fn flex_is_tailwinds_row() {
4748        // `.flex()` is a row unless a direction is set, as the class is.
4749        same(s().flex(), "flex");
4750        same(s().flex().flex_col(), "flex flex-col");
4751        same(s().flex_col().flex(), "flex-col flex");
4752        same(s().items_center(), "items-center");
4753    }
4754
4755    #[test]
4756    fn auto_minimum_sizes_are_tailwinds() {
4757        // CSS's automatic minimum, as `min-w-auto` / `min-h-auto` are.
4758        same(
4759            s().min_w(crate::geometry::auto())
4760                .min_h(crate::geometry::auto()),
4761            "min-w-auto min-h-auto",
4762        );
4763    }
4764
4765    #[test]
4766    fn borders_and_corners_are_tailwinds() {
4767        same(
4768            s().border_t(px(6.0))
4769                .border_t_color(RED.shade(600))
4770                .border_r(px(2.0))
4771                .border_b(px(4.0))
4772                .border_l(px(1.0))
4773                .border_x_color(SKY.shade(500)),
4774            "border-t-6 border-t-red-600 border-r-2 border-b-4 border-l border-x-sky-500",
4775        );
4776        same(
4777            s().border_y(px(3.0))
4778                .border_s(px(1.0))
4779                .border_e(px(2.0))
4780                .border_dashed(),
4781            "border-y-3 border-s border-e-2 border-dashed",
4782        );
4783        same(s().border_none().border(px(2.0)), "border-none border-2");
4784        same(
4785            s().border(px(3.0)).border_dotted(),
4786            "border-3 border-dotted",
4787        );
4788        same(
4789            s().rounded_tl(px(44.0))
4790                .rounded_tr(px(6.0))
4791                .rounded_br(px(28.0))
4792                .rounded_bl(px(2.0)),
4793            "rounded-tl-[44px] rounded-tr-[6px] rounded-br-[28px] rounded-bl-[2px]",
4794        );
4795        same(
4796            s().rounded_ss(px(22.0))
4797                .rounded_ee(px(8.0))
4798                .rounded_l(px(4.0)),
4799            "rounded-ss-[22px] rounded-ee-[8px] rounded-l-[4px]",
4800        );
4801        same(
4802            s().outline(px(2.0))
4803                .outline_offset(px(2.0))
4804                .outline_dashed()
4805                .outline_color(PINK.shade(500)),
4806            "outline-2 outline-offset-2 outline-dashed outline-pink-500",
4807        );
4808        same(
4809            s().outline_dotted().outline(px(2.0)),
4810            "outline-dotted outline-2",
4811        );
4812        same(s().outline_dashed(), "outline-dashed");
4813        let curved = s().border_curve(BorderCurve::Continuous).lower();
4814        let mut style = Style::default();
4815        let _ = style.set_key(StyleKey::BorderCurve, crate::StyleValue::Str("continuous"));
4816        assert_eq!(
4817            resolve(&curved, false, 0, 0),
4818            format!("{style:?} {:?}", ClassProps::default())
4819        );
4820    }
4821
4822    #[test]
4823    fn shadows_and_rings_are_tailwinds() {
4824        let emerald = EMERALD.shade(500).opacity(0.5);
4825        same(
4826            s().shadow_lg().shadow_color(emerald),
4827            "shadow-lg shadow-emerald-500/50",
4828        );
4829        same(
4830            s().shadow_xl().shadow_color(SKY.shade(500)),
4831            "shadow-xl shadow-sky-500",
4832        );
4833        same(s().inset_shadow_sm(), "inset-shadow-sm");
4834        same(
4835            s().ring(px(2.0))
4836                .ring_color(SKY.shade(500))
4837                .ring_offset(px(2.0)),
4838            "ring-2 ring-sky-500 ring-offset-2",
4839        );
4840        same(
4841            s().ring(px(1.0)).ring_color(rgba(0x0000_000d)).ring_inset(),
4842            "ring-1 ring-black/5 ring-inset",
4843        );
4844        same(s().text_shadow_md(), "text-shadow-md");
4845        // A theme color of the shadow switches with the appearance.
4846        let adaptive = s()
4847            .shadow_md()
4848            .shadow_color(AdaptiveColor::new(SKY.shade(500), PINK.shade(500)))
4849            .lower();
4850        assert_eq!(adaptive.deps(), tailwind::deps::DARK);
4851        for (dark, hue) in [(false, SKY), (true, PINK)] {
4852            let classes = format!("shadow-md shadow-{}-500", hue.name());
4853            assert_eq!(
4854                resolve(&adaptive, dark, 0, 0),
4855                resolve(&tailwind::parse(&PRESETS, &classes), dark, 0, 0)
4856            );
4857        }
4858    }
4859
4860    #[test]
4861    fn a_parts_input_colors_come_from_the_typed_style() {
4862        let list = s()
4863            .placeholder_color(RED.shade(500))
4864            .caret_color(SKY.shade(500))
4865            .selection_color(EMERALD.shade(500))
4866            .lower();
4867        let mut style = Style::default();
4868        list.apply(
4869            &Context {
4870                env: ClassEnvironment::default(),
4871                window: crate::geometry::size_pt(390.0, 844.0),
4872                rtl: false,
4873                states: 0,
4874                position: 0,
4875                group: &|_| 0,
4876            },
4877            &PRESETS,
4878            &mut style,
4879            &mut ClassProps::default(),
4880            |_| {},
4881        );
4882        assert_eq!(style.text.placeholder_color, Some(RED.shade(500).into()));
4883        assert_eq!(style.text.caret_color, Some(SKY.shade(500).into()));
4884        assert_eq!(style.text.selection_color, Some(EMERALD.shade(500).into()));
4885    }
4886
4887    #[test]
4888    fn custom_shadows_are_layers_of_their_own() {
4889        let list = s()
4890            .text_shadow([crate::TextShadow {
4891                color: rgba(0x0000_0099).into(),
4892                offset_x: px(2.0),
4893                offset_y: px(2.0),
4894                radius: px(4.0),
4895            }])
4896            .lower();
4897        let mut style = Style::default();
4898        list.apply(
4899            &Context {
4900                env: ClassEnvironment::default(),
4901                window: crate::geometry::size_pt(390.0, 844.0),
4902                rtl: false,
4903                states: 0,
4904                position: 0,
4905                group: &|_| 0,
4906            },
4907            &PRESETS,
4908            &mut style,
4909            &mut ClassProps::default(),
4910            |_| {},
4911        );
4912        assert_eq!(style.text.shadow_color, Some(rgba(0x0000_0099).into()));
4913        assert_eq!(style.text.shadow_radius, Some(px(4.0)));
4914        assert_eq!(style.text.shadow_offset, Some(point(px(2.0), px(2.0))));
4915        let layer = BoxShadow {
4916            offset_x: px(0.0),
4917            offset_y: px(2.0),
4918            blur: px(4.0),
4919            spread: px(0.0),
4920            color: rgba(0x0000_000d).into(),
4921            inset: true,
4922        };
4923        same(
4924            s().shadow([layer]),
4925            "shadow-[inset_0_2px_4px_rgb(0_0_0/0.05)]",
4926        );
4927    }
4928
4929    #[test]
4930    fn effects_are_tailwinds() {
4931        same(
4932            s().bg_linear_to_br()
4933                .gradient_from(VIOLET.shade(500))
4934                .gradient_via(PINK.shade(500))
4935                .gradient_to(RED.shade(400)),
4936            "bg-linear-to-br from-violet-500 via-pink-500 to-red-400",
4937        );
4938        same(
4939            s().bg_linear(deg(45.0))
4940                .gradient_from(SKY.shade(400))
4941                .gradient_to(VIOLET.shade(600))
4942                .gradient_to_position(percentage(0.8)),
4943            "bg-linear-45 from-sky-400 to-violet-600 to-80%",
4944        );
4945        same(
4946            s().bg_radial().gradient_from(SKY.shade(200)),
4947            "bg-radial from-sky-200",
4948        );
4949        same(
4950            s().bg_conic(deg(0.0)).gradient_from(RED.shade(500)),
4951            "bg-conic from-red-500",
4952        );
4953        same(s().grayscale(1.0).sepia(1.0), "grayscale sepia");
4954        same(s().blur(px(8.0)).brightness(0.5), "blur-sm brightness-50");
4955        same(
4956            s().saturate(1.5).hue_rotate(deg(90.0)),
4957            "saturate-150 hue-rotate-90",
4958        );
4959        same(
4960            s().backdrop_blur(px(12.0))
4961                .backdrop_saturate(1.5)
4962                .backdrop_sepia(1.0),
4963            "backdrop-blur-md backdrop-saturate-150 backdrop-sepia",
4964        );
4965        same(
4966            s().mix_blend_mode(BlendMode::Multiply),
4967            "mix-blend-multiply",
4968        );
4969        same(s().transition(), "transition");
4970        same(
4971            s().transition_colors()
4972                .duration(150.0)
4973                .ease_in_out()
4974                .delay(75.0),
4975            "transition-colors duration-150 ease-in-out delay-75",
4976        );
4977        same(
4978            s().transition_transform().duration(200.0),
4979            "transition-transform duration-200",
4980        );
4981        let spring = crate::element::Spring {
4982            stiffness: 620.0,
4983            damping: 36.0,
4984            ..crate::element::Spring::default()
4985        };
4986        same(
4987            s().transition_transform().ease_spring(spring),
4988            "transition-transform ease-spring-[620,36]",
4989        );
4990        same(
4991            s().transition_opacity()
4992                .ease_spring(crate::element::Spring {
4993                    mass: 2.0,
4994                    ..spring
4995                }),
4996            "transition-opacity ease-spring-[620,36,2]",
4997        );
4998        same(
4999            s().transition().ease_bezier(0.3, 1.25, 0.6, 1.0),
5000            "transition ease-[cubic-bezier(0.3,1.25,0.6,1)]",
5001        );
5002        for (typed, classes) in [
5003            (s().animate_spin(), "animate-spin"),
5004            (s().animate_ping(), "animate-ping"),
5005            (s().animate_pulse(), "animate-pulse"),
5006            (s().animate_bounce(), "animate-bounce"),
5007        ] {
5008            same(typed, classes);
5009        }
5010    }
5011
5012    #[test]
5013    fn mask_gradients_match_css() {
5014        let css = |value: &'static str| {
5015            move |style: &mut Style| {
5016                style
5017                    .set_key(StyleKey::MaskImage, crate::StyleValue::Str(value))
5018                    .unwrap();
5019            }
5020        };
5021        same_with(
5022            s().mask_linear(
5023                deg(90.0),
5024                [transparent_black(), black(), transparent_black()],
5025            ),
5026            "",
5027            &css("linear-gradient(to right, transparent, black, transparent)"),
5028        );
5029        same_with(
5030            s().mask_linear(
5031                deg(180.0),
5032                [
5033                    (transparent_black(), percentage(0.2)),
5034                    (black(), percentage(0.8)),
5035                ],
5036            ),
5037            "",
5038            &css("linear-gradient(to bottom, transparent 20%, black 80%)"),
5039        );
5040        same_with(
5041            s().mask_linear(
5042                deg(90.0),
5043                [(transparent_black(), px(12.0)), (black(), px(24.0))],
5044            ),
5045            "",
5046            &css("linear-gradient(to right, transparent 12px, black 24px)"),
5047        );
5048        same_with(
5049            s().mask_radial([black(), transparent_black()]),
5050            "",
5051            &css("radial-gradient(black, transparent)"),
5052        );
5053        same_with(
5054            s().mask_radial([black(), transparent_black()]).mask_none(),
5055            "",
5056            &css("none"),
5057        );
5058    }
5059
5060    #[test]
5061    fn empty_stops_clear_masks_and_radial_accepts_reactive_stops() {
5062        same_with(
5063            s().mask_linear(deg(90.0), Vec::<ColorStop>::new()),
5064            "",
5065            &|style| {
5066                style
5067                    .set_key(StyleKey::MaskImage, crate::StyleValue::Str("none"))
5068                    .unwrap();
5069            },
5070        );
5071        same_with(s().mask_radial(Vec::<ColorStop>::new()), "", &|style| {
5072            style
5073                .set_key(StyleKey::MaskImage, crate::StyleValue::Str("none"))
5074                .unwrap();
5075        });
5076        // Constructed inside a component in normal use; these static reactive
5077        // wrappers exercise the same accepted type without needing an owner.
5078        let stops = Reactive::Static(vec![ColorStop::from(black()), transparent_black().into()]);
5079        same_with(s().mask_radial(stops), "", &|style| {
5080            style
5081                .set_key(
5082                    StyleKey::MaskImage,
5083                    crate::StyleValue::Str("radial-gradient(black, transparent)"),
5084                )
5085                .unwrap();
5086        });
5087    }
5088
5089    #[test]
5090    fn masks_keep_background_stops_separate() {
5091        let typed = s()
5092            .bg_linear(deg(180.0))
5093            .gradient_from(black())
5094            .gradient_to(crate::color::white())
5095            .mask_linear(deg(90.0), [black(), transparent_black()]);
5096        same_with(typed, "bg-linear-180 from-black to-white", &|style| {
5097            style
5098                .set_key(
5099                    StyleKey::MaskImage,
5100                    crate::StyleValue::Str("linear-gradient(to right, black, transparent)"),
5101                )
5102                .unwrap();
5103        });
5104    }
5105
5106    #[test]
5107    fn keyframe_animations_take_their_own_timing() {
5108        // As TS's `animationName` and its timing keys over no animation.
5109        let timed = |name: &'static str, ms: f32, easing: &'static str| {
5110            move |style: &mut Style| {
5111                use crate::StyleValue;
5112                style
5113                    .set_key(StyleKey::AnimationName, StyleValue::Str(name))
5114                    .unwrap();
5115                style
5116                    .set_key(StyleKey::AnimationDuration, StyleValue::Number(ms))
5117                    .unwrap();
5118                style
5119                    .set_key(StyleKey::AnimationTimingFunction, StyleValue::Str(easing))
5120                    .unwrap();
5121            }
5122        };
5123        same_with(
5124            s().animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0)),
5125            "animate-none",
5126            &timed("spin", 800.0, "linear"),
5127        );
5128        same_with(
5129            s().animation(
5130                KeyframeAnimation::new(Keyframes::Pulse)
5131                    .duration(900.0)
5132                    .easing([0.42, 0.0, 0.58, 1.0]),
5133            ),
5134            "animate-none",
5135            &timed("pulse", 900.0, "ease-in-out"),
5136        );
5137        // The later declaration wins, either way round.
5138        same(
5139            s().animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0))
5140                .animate_ping(),
5141            "animate-ping",
5142        );
5143        same_with(
5144            s().animate_ping()
5145                .animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0)),
5146            "animate-none",
5147            &timed("spin", 800.0, "linear"),
5148        );
5149    }
5150
5151    #[test]
5152    fn keyframe_animations_take_their_frame_rate() {
5153        // As TS's `animationFrameRate` with the animation's other keys.
5154        let capped = |hz: f32| {
5155            move |style: &mut Style| {
5156                use crate::StyleValue;
5157                for (key, value) in [
5158                    (StyleKey::AnimationName, StyleValue::Str("spin")),
5159                    (StyleKey::AnimationDuration, StyleValue::Number(800.0)),
5160                    (StyleKey::AnimationTimingFunction, StyleValue::Str("linear")),
5161                    (StyleKey::AnimationFrameRate, StyleValue::Number(hz)),
5162                ] {
5163                    style.set_key(key, value).unwrap();
5164                }
5165            }
5166        };
5167        same_with(
5168            s().animation(
5169                KeyframeAnimation::new(Keyframes::Spin)
5170                    .duration(800.0)
5171                    .frame_rate(30.0),
5172            ),
5173            "animate-none",
5174            &capped(30.0),
5175        );
5176        let typed = s()
5177            .animation(KeyframeAnimation::new(Keyframes::Spin).frame_rate(24.0))
5178            .lower();
5179        assert!(resolve(&typed, false, 0, 0).contains("frame_rate: Some(24.0)"));
5180    }
5181
5182    #[test]
5183    fn transforms_are_tailwinds() {
5184        same(
5185            s().rotate(deg(12.0)).skew_x(deg(6.0)).scale(0.9),
5186            "rotate-12 skew-x-6 scale-90",
5187        );
5188        same(
5189            s().perspective(px(400.0))
5190                .rotate_y(deg(35.0))
5191                .rotate_x(deg(40.0)),
5192            "perspective-[400px] rotate-y-35 rotate-x-40",
5193        );
5194        same(s().scale_x(1.5).skew_y(deg(-3.0)), "scale-x-150 -skew-y-3");
5195        same(
5196            s().rotate(deg(12.0))
5197                .rotate_x(deg(40.0))
5198                .skew_x(deg(6.0))
5199                .scale(0.9)
5200                .transform_none(),
5201            "rotate-12 rotate-x-40 skew-x-6 scale-90 transform-none",
5202        );
5203        same(
5204            s().translate_x(px(8.0))
5205                .rotate(deg(12.0))
5206                .scale(0.9)
5207                .translate_none()
5208                .rotate_none()
5209                .scale_none(),
5210            "translate-x-2 rotate-12 scale-90 translate-none rotate-none scale-none",
5211        );
5212        same(
5213            s().origin_top_left().backface_hidden(),
5214            "origin-top-left backface-hidden",
5215        );
5216        same(
5217            s().transform_origin(TransformOrigin {
5218                x: px(10.0).into(),
5219                y: relative(0.25),
5220                z: Points::ZERO,
5221            }),
5222            "origin-[10px_25%]",
5223        );
5224    }
5225
5226    #[test]
5227    fn text_is_tailwinds() {
5228        same(
5229            s().underline()
5230                .text_decoration_wavy()
5231                .text_decoration_color(RED.shade(500))
5232                .text_decoration_thickness(px(2.0))
5233                .underline_offset(px(4.0)),
5234            "underline decoration-wavy decoration-red-500 decoration-2 underline-offset-4",
5235        );
5236        same(s().uppercase().tabular_nums(), "uppercase tabular-nums");
5237        same(s().small_caps().oldstyle_nums(), "small-caps oldstyle-nums");
5238        same(s().capitalize().text_justify(), "capitalize text-justify");
5239        same(s().align_baseline(), "align-baseline");
5240        same(s().align_text_top(), "align-text-top");
5241        same(s().align_text_bottom(), "align-text-bottom");
5242        same(s().align_middle(), "align-middle");
5243        same(s().text_pretty(), "text-pretty");
5244        same(s().whitespace_nowrap(), "whitespace-nowrap");
5245        same(s().whitespace_normal(), "whitespace-normal");
5246        // The last of them holds, as the classes'.
5247        same(
5248            s().text_pretty().whitespace_normal(),
5249            "text-pretty whitespace-normal",
5250        );
5251        same(
5252            s().whitespace_nowrap().text_pretty(),
5253            "whitespace-nowrap text-pretty",
5254        );
5255        // Unlike classes, the two lines add up.
5256        let both = s().underline().line_through().lower();
5257        let mut style = Style::default();
5258        let _ = style.set_key(
5259            StyleKey::TextDecorationLine,
5260            crate::StyleValue::Str("underline line-through"),
5261        );
5262        assert_eq!(
5263            resolve(&both, false, 0, 0),
5264            format!("{style:?} {:?}", ClassProps::default())
5265        );
5266        same(
5267            s().underline().line_through().no_underline(),
5268            "no-underline",
5269        );
5270        let rtl = s().writing_direction(WritingDirection::Rtl).lower();
5271        let mut style = Style::default();
5272        let _ = style.set_key(StyleKey::WritingDirection, crate::StyleValue::Str("rtl"));
5273        assert_eq!(
5274            resolve(&rtl, false, 0, 0),
5275            format!("{style:?} {:?}", ClassProps::default())
5276        );
5277    }
5278
5279    #[test]
5280    fn layout_is_tailwinds() {
5281        same(s().grid().grid_cols(3).gap_2(), "grid grid-cols-3 gap-2");
5282        same(s().col_span(2).row_span(2), "col-span-2 row-span-2");
5283        same(s().col_start(2).col_end(-1), "col-start-2 col-end-[-1]");
5284        same(s().flex_grow(2.0).flex_shrink(0.0), "grow-2 shrink-0");
5285        same(
5286            s().grid_rows(2).grid_flow_col(),
5287            "grid-rows-2 grid-flow-col",
5288        );
5289    }
5290
5291    #[test]
5292    fn variants_are_tailwinds() {
5293        same(
5294            s().group_active(|s| s.text_color(VIOLET.shade(600)).translate_x(px(4.0))),
5295            "group-active:text-violet-600 group-active:translate-x-1",
5296        );
5297        same(s().group(), "group");
5298        same(
5299            s().group_named("item")
5300                .group_hover_named("item", |s| s.opacity(0.5)),
5301            "group/item group-hover/item:opacity-50",
5302        );
5303        same(s().dark(|s| s.shadow_none()), "dark:shadow-none");
5304        let mut disabled = s();
5305        disabled.extend_as(Variant::DISABLED, s().opacity(0.4));
5306        same(disabled, "disabled:opacity-40");
5307        // Nested variants: both hold.
5308        let mut nested = s();
5309        nested.extend_as(Variant::ACTIVE, s().dark(|s| s.opacity(0.5)));
5310        same(nested, "dark:active:opacity-50");
5311    }
5312
5313    /// A bound value in a named group variant nested in another variant
5314    /// keeps its group: its part runs into a fresh refinement, whose
5315    /// group names start empty.
5316    #[test]
5317    fn bound_values_keep_their_named_group_when_nested() {
5318        let opacity = 0.5_f32;
5319        let mut hovered = s();
5320        hovered.extend_as(
5321            Variant::HOVER,
5322            s().group_active_named("card", |s| s.opacity(move || opacity)),
5323        );
5324        same(hovered.resolved(), "hover:group-active/card:opacity-50");
5325    }
5326
5327    /// Styles that differ only in a value, as the widths of a list's rows
5328    /// do, hash apart: the core caches their lowered rules by them, and
5329    /// styles hashing alike leave its table one long probe.
5330    #[test]
5331    fn styles_that_differ_in_a_value_hash_apart() {
5332        use std::hash::BuildHasher;
5333        let hash = |s: &StyleRefinement| rustc_hash::FxBuildHasher.hash_one(s);
5334        let styles: [fn(f32) -> StyleRefinement; 9] = [
5335            |v| s().w(px(v)),
5336            |v| s().h(relative(v / 100.0)),
5337            |v| s().p(px(v)),
5338            |v| s().ml(px(v)),
5339            |v| s().top(px(v)),
5340            |v| s().basis(px(v)),
5341            |v| s().gap(px(v)),
5342            |v| s().text_size(px(v)),
5343            |v| s().line_height(LineHeight::Multiple(v / 10.0)),
5344        ];
5345        for style in styles {
5346            let hashes = (1..=64)
5347                .map(|v| hash(&style(v as f32)))
5348                .collect::<rustc_hash::FxHashSet<_>>();
5349            assert_eq!(hashes.len(), 64, "{:?}", style(1.0));
5350            assert_eq!(hash(&style(8.0)), hash(&style(8.0)));
5351        }
5352        // Keywords as well.
5353        let pairs = [
5354            (s().flex_row(), s().flex_col()),
5355            (s().items_start(), s().items_center()),
5356            (s().relative(), s().absolute()),
5357            (s().cursor(Cursor::Pointer), s().cursor(Cursor::Text)),
5358        ];
5359        for (a, b) in pairs {
5360            assert_ne!(hash(&a), hash(&b), "{a:?}");
5361        }
5362    }
5363}