Skip to main content

nsh_core/element/
style.rs

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