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