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