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