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 jump.
3251    fn transition_none(mut self) -> Self {
3252        self.style().push(Declaration::TransitionNone);
3253        self
3254    }
3255
3256    /// Transitions last `ms` milliseconds.
3257    fn duration(mut self, ms: impl IntoReactive<f32>) -> Self {
3258        self.style().bind_value(ms, |s, ms: f32| {
3259            s.push(Declaration::Duration(Bits(ms)));
3260        });
3261        self
3262    }
3263
3264    /// Transitions start after `ms` milliseconds.
3265    fn delay(mut self, ms: impl IntoReactive<f32>) -> Self {
3266        self.style().bind_value(ms, |s, ms: f32| {
3267            s.push(Declaration::Delay(Bits(ms)));
3268        });
3269        self
3270    }
3271
3272    /// Transitions at a constant pace.
3273    fn ease_linear(mut self) -> Self {
3274        self.style().push(Declaration::EasePreset("linear"));
3275        self
3276    }
3277
3278    /// Transitions that start slowly.
3279    fn ease_in(mut self) -> Self {
3280        self.style().push(Declaration::EasePreset("in"));
3281        self
3282    }
3283
3284    /// Transitions that end slowly.
3285    fn ease_out(mut self) -> Self {
3286        self.style().push(Declaration::EasePreset("out"));
3287        self
3288    }
3289
3290    /// Transitions that start and end slowly.
3291    fn ease_in_out(mut self) -> Self {
3292        self.style().push(Declaration::EasePreset("in-out"));
3293        self
3294    }
3295
3296    /// Transitions along the cubic Bézier curve `x1, y1, x2, y2` (a `y`
3297    /// outside 0..1 overshoots).
3298    fn ease_bezier(mut self, x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
3299        self.style()
3300            .push(Declaration::Ease([x1, y1, x2, y2].map(Bits)));
3301        self
3302    }
3303
3304    /// Transitions on a spring's physics (its stiffness, damping and mass;
3305    /// Tailwind extension `ease-spring-[620,36]`): they time themselves,
3306    /// lasting until the spring settles ([`Spring::settle_ms`]), so
3307    /// [`Self::duration`] is not used. A spring that cannot settle (a
3308    /// stiffness, damping or mass that is not positive) sets nothing.
3309    ///
3310    /// [`Spring::settle_ms`]: crate::element::Spring::settle_ms
3311    fn ease_spring(mut self, spring: crate::element::Spring) -> Self {
3312        self.style().push(Declaration::EaseSpring(
3313            [spring.stiffness, spring.damping, spring.mass].map(Bits),
3314        ));
3315        self
3316    }
3317
3318    /// Turns around, forever (Tailwind's `animate-spin`: a loader).
3319    fn animate_spin(mut self) -> Self {
3320        self.style().push(Declaration::Animate(Some(0)));
3321        self
3322    }
3323
3324    /// Scales up and fades out, forever (`animate-ping`: a badge's pulse).
3325    fn animate_ping(mut self) -> Self {
3326        self.style().push(Declaration::Animate(Some(1)));
3327        self
3328    }
3329
3330    /// Fades to half and back, forever (`animate-pulse`: a skeleton).
3331    fn animate_pulse(mut self) -> Self {
3332        self.style().push(Declaration::Animate(Some(2)));
3333        self
3334    }
3335
3336    /// Jumps and lands, forever (`animate-bounce`).
3337    fn animate_bounce(mut self) -> Self {
3338        self.style().push(Declaration::Animate(Some(3)));
3339        self
3340    }
3341
3342    /// A keyframe animation with its own timing (TS: `animationName`
3343    /// with `animationDuration`, `animationDelay`,
3344    /// `animationTimingFunction`, `animationIterationCount`,
3345    /// `animationFrameRate`):
3346    /// `.animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0))`.
3347    fn animation(mut self, animation: KeyframeAnimation) -> Self {
3348        let index = KEYFRAMES
3349            .iter()
3350            .position(|k| *k == animation.keyframes)
3351            .expect("every keyframes") as u8;
3352        self.style().push(Declaration::Animation(
3353            index,
3354            Bits(animation.duration),
3355            Bits(animation.delay),
3356            animation.easing.map(Bits),
3357            animation.iterations,
3358            crate::style::frame_rate(animation.frame_rate).map(Bits),
3359        ));
3360        self
3361    }
3362
3363    /// No keyframe animation.
3364    fn animate_none(mut self) -> Self {
3365        self.style().push(Declaration::Animate(None));
3366        self
3367    }
3368
3369    /// Scales from the center (1 is the natural size).
3370    fn scale(self, scale: impl IntoReactive<f32>) -> Self {
3371        self.transform_step(TransformKind::Scale, scale)
3372    }
3373
3374    /// Scales horizontally.
3375    fn scale_x(self, scale: impl IntoReactive<f32>) -> Self {
3376        self.transform_step(TransformKind::ScaleX, scale)
3377    }
3378
3379    /// Scales vertically.
3380    fn scale_y(self, scale: impl IntoReactive<f32>) -> Self {
3381        self.transform_step(TransformKind::ScaleY, scale)
3382    }
3383
3384    /// Moves horizontally by `offset` (after layout): points, or a
3385    /// fraction of its own width (`relative(-0.5)`).
3386    fn translate_x(self, offset: impl IntoReactive<DefiniteLength>) -> Self {
3387        transform_with(self, offset, |offset| {
3388            translation(
3389                offset,
3390                TransformKind::TranslateX,
3391                TransformKind::TranslateXFraction,
3392            )
3393        })
3394    }
3395
3396    /// Moves vertically by `offset` (after layout): points, or a fraction
3397    /// of its own height.
3398    fn translate_y(self, offset: impl IntoReactive<DefiniteLength>) -> Self {
3399        transform_with(self, offset, |offset| {
3400            translation(
3401                offset,
3402                TransformKind::TranslateY,
3403                TransformKind::TranslateYFraction,
3404            )
3405        })
3406    }
3407
3408    /// Rotates by `angle`, clockwise.
3409    fn rotate(self, angle: impl IntoReactive<Radians>) -> Self {
3410        transform_with(self, angle, |a: Radians| {
3411            (TransformKind::Rotate, a.to_degrees())
3412        })
3413    }
3414
3415    /// Rotates by `angle` around the horizontal axis (3D; in a view with
3416    /// [`Styled::perspective`] it tilts towards the viewer).
3417    fn rotate_x(self, angle: impl IntoReactive<Radians>) -> Self {
3418        transform_with(self, angle, |a: Radians| {
3419            (TransformKind::RotateX, a.to_degrees())
3420        })
3421    }
3422
3423    /// Rotates by `angle` around the vertical axis (3D).
3424    fn rotate_y(self, angle: impl IntoReactive<Radians>) -> Self {
3425        transform_with(self, angle, |a: Radians| {
3426            (TransformKind::RotateY, a.to_degrees())
3427        })
3428    }
3429
3430    /// Slants vertical edges by `angle` (iOS; Android has no skew).
3431    fn skew_x(self, angle: impl IntoReactive<Radians>) -> Self {
3432        transform_with(self, angle, |a: Radians| {
3433            (TransformKind::SkewX, a.to_degrees())
3434        })
3435    }
3436
3437    /// Slants horizontal edges by `angle` (iOS).
3438    fn skew_y(self, angle: impl IntoReactive<Radians>) -> Self {
3439        transform_with(self, angle, |a: Radians| {
3440            (TransformKind::SkewY, a.to_degrees())
3441        })
3442    }
3443
3444    /// Gives its children depth: their 3D rotations are seen from
3445    /// `distance` away (smaller: stronger), from its center (CSS's
3446    /// `perspective`, `perspective-*`).
3447    fn perspective(self, distance: impl IntoReactive<AbsoluteLength>) -> Self {
3448        transform_with(self, distance, |d: AbsoluteLength| {
3449            (TransformKind::Perspective, points(d))
3450        })
3451    }
3452
3453    /// The step `kind` of its transform, by `amount`. The steps compose in
3454    /// CSS's order, whatever the order of the calls: translate, rotate,
3455    /// scale, then the 3D rotations and the skews.
3456    /// [`TransformKind::Perspective`] is [`Styled::perspective`], its
3457    /// children's depth.
3458    fn transform_step(self, kind: TransformKind, amount: impl IntoReactive<f32>) -> Self {
3459        transform_with(self, amount, move |amount| (kind, amount))
3460    }
3461
3462    /// No 3D rotations and skews (CSS's `transform: none`; the
3463    /// translation, rotation and scale are properties of their own, which
3464    /// [`Styled::translate_none`], [`Styled::rotate_none`] and
3465    /// [`Styled::scale_none`] remove).
3466    fn transform_none(self) -> Self {
3467        transform_reset(self, Declaration::TransformNone)
3468    }
3469
3470    /// No translation (also none set before).
3471    fn translate_none(self) -> Self {
3472        transform_reset(self, Declaration::TranslateNone)
3473    }
3474
3475    /// No scale (also none set before).
3476    fn scale_none(self) -> Self {
3477        transform_reset(self, Declaration::ScaleNone)
3478    }
3479
3480    /// No rotation (also none set before; the 3D rotations stay).
3481    fn rotate_none(self) -> Self {
3482        transform_reset(self, Declaration::RotateNone)
3483    }
3484
3485    /// The point its transform turns and scales around (the center by
3486    /// default).
3487    fn transform_origin(mut self, origin: TransformOrigin) -> Self {
3488        let axis = |l: DefiniteLength| match l {
3489            DefiniteLength::Absolute(a) => (false, Bits(a.to_points(REM_SIZE).0)),
3490            DefiniteLength::Fraction(f) => (true, Bits(f.0)),
3491        };
3492        self.style()
3493            .push(Declaration::Origin([axis(origin.x), axis(origin.y)]));
3494        self
3495    }
3496
3497    /// Transforms around its top left corner.
3498    fn origin_top_left(mut self) -> Self {
3499        self.style().value(
3500            StyleKey::TransformOrigin,
3501            PropertyValue::TransformOrigin(origin(0.0, 0.0)),
3502        );
3503        self
3504    }
3505
3506    /// Transforms around the middle of its top edge.
3507    fn origin_top(mut self) -> Self {
3508        self.style().value(
3509            StyleKey::TransformOrigin,
3510            PropertyValue::TransformOrigin(origin(0.5, 0.0)),
3511        );
3512        self
3513    }
3514
3515    /// Transforms around its top right corner.
3516    fn origin_top_right(mut self) -> Self {
3517        self.style().value(
3518            StyleKey::TransformOrigin,
3519            PropertyValue::TransformOrigin(origin(1.0, 0.0)),
3520        );
3521        self
3522    }
3523
3524    /// Transforms around the middle of its left edge.
3525    fn origin_left(mut self) -> Self {
3526        self.style().value(
3527            StyleKey::TransformOrigin,
3528            PropertyValue::TransformOrigin(origin(0.0, 0.5)),
3529        );
3530        self
3531    }
3532
3533    /// Transforms around its center (the default).
3534    fn origin_center(mut self) -> Self {
3535        self.style().value(
3536            StyleKey::TransformOrigin,
3537            PropertyValue::TransformOrigin(origin(0.5, 0.5)),
3538        );
3539        self
3540    }
3541
3542    /// Transforms around the middle of its right edge.
3543    fn origin_right(mut self) -> Self {
3544        self.style().value(
3545            StyleKey::TransformOrigin,
3546            PropertyValue::TransformOrigin(origin(1.0, 0.5)),
3547        );
3548        self
3549    }
3550
3551    /// Transforms around its bottom left corner.
3552    fn origin_bottom_left(mut self) -> Self {
3553        self.style().value(
3554            StyleKey::TransformOrigin,
3555            PropertyValue::TransformOrigin(origin(0.0, 1.0)),
3556        );
3557        self
3558    }
3559
3560    /// Transforms around the middle of its bottom edge.
3561    fn origin_bottom(mut self) -> Self {
3562        self.style().value(
3563            StyleKey::TransformOrigin,
3564            PropertyValue::TransformOrigin(origin(0.5, 1.0)),
3565        );
3566        self
3567    }
3568
3569    /// Transforms around its bottom right corner.
3570    fn origin_bottom_right(mut self) -> Self {
3571        self.style().value(
3572            StyleKey::TransformOrigin,
3573            PropertyValue::TransformOrigin(origin(1.0, 1.0)),
3574        );
3575        self
3576    }
3577
3578    /// How an image or a video fits its box (`objectFit`): `Cover` (an
3579    /// image's default), `Contain` (a video's), `Stretch` (CSS's `fill`),
3580    /// `Center` (`none`) or `ScaleDown`.
3581    fn object_fit(mut self, fit: impl IntoReactive<crate::ResizeMode>) -> Self {
3582        self.style().bind_value(fit, |s, fit: crate::ResizeMode| {
3583            s.value(StyleKey::ObjectFit, PropertyValue::ObjectFit(Some(fit)));
3584        });
3585        self
3586    }
3587
3588    /// Where an image sits in its box once its resize mode has sized it
3589    /// (CSS's `object-position`; the center by default): a covering image
3590    /// is cropped around it.
3591    fn object_position(mut self, position: ObjectPosition) -> Self {
3592        self.style().value(
3593            StyleKey::ObjectPosition,
3594            PropertyValue::ObjectPosition(position),
3595        );
3596        self
3597    }
3598
3599    /// Shows an image's top left corner (Tailwind's `object-top-left`).
3600    fn object_top_left(mut self) -> Self {
3601        self.style().value(
3602            StyleKey::ObjectPosition,
3603            PropertyValue::ObjectPosition(ObjectPosition::new(
3604                PositionAxis::START,
3605                PositionAxis::START,
3606            )),
3607        );
3608        self
3609    }
3610
3611    /// Shows an image's top (Tailwind's `object-top`): a tall image
3612    /// covering its box is cropped at the bottom.
3613    fn object_top(mut self) -> Self {
3614        self.style().value(
3615            StyleKey::ObjectPosition,
3616            PropertyValue::ObjectPosition(ObjectPosition::new(
3617                PositionAxis::CENTER,
3618                PositionAxis::START,
3619            )),
3620        );
3621        self
3622    }
3623
3624    /// Shows an image's top right corner (Tailwind's `object-top-right`).
3625    fn object_top_right(mut self) -> Self {
3626        self.style().value(
3627            StyleKey::ObjectPosition,
3628            PropertyValue::ObjectPosition(ObjectPosition::new(
3629                PositionAxis::END,
3630                PositionAxis::START,
3631            )),
3632        );
3633        self
3634    }
3635
3636    /// Shows an image's left side (Tailwind's `object-left`).
3637    fn object_left(mut self) -> Self {
3638        self.style().value(
3639            StyleKey::ObjectPosition,
3640            PropertyValue::ObjectPosition(ObjectPosition::new(
3641                PositionAxis::START,
3642                PositionAxis::CENTER,
3643            )),
3644        );
3645        self
3646    }
3647
3648    /// Centers an image in its box (Tailwind's `object-center`, the
3649    /// default).
3650    fn object_center(mut self) -> Self {
3651        self.style().value(
3652            StyleKey::ObjectPosition,
3653            PropertyValue::ObjectPosition(ObjectPosition::new(
3654                PositionAxis::CENTER,
3655                PositionAxis::CENTER,
3656            )),
3657        );
3658        self
3659    }
3660
3661    /// Shows an image's right side (Tailwind's `object-right`).
3662    fn object_right(mut self) -> Self {
3663        self.style().value(
3664            StyleKey::ObjectPosition,
3665            PropertyValue::ObjectPosition(ObjectPosition::new(
3666                PositionAxis::END,
3667                PositionAxis::CENTER,
3668            )),
3669        );
3670        self
3671    }
3672
3673    /// Shows an image's bottom left corner (Tailwind's
3674    /// `object-bottom-left`).
3675    fn object_bottom_left(mut self) -> Self {
3676        self.style().value(
3677            StyleKey::ObjectPosition,
3678            PropertyValue::ObjectPosition(ObjectPosition::new(
3679                PositionAxis::START,
3680                PositionAxis::END,
3681            )),
3682        );
3683        self
3684    }
3685
3686    /// Shows an image's bottom (Tailwind's `object-bottom`).
3687    fn object_bottom(mut self) -> Self {
3688        self.style().value(
3689            StyleKey::ObjectPosition,
3690            PropertyValue::ObjectPosition(ObjectPosition::new(
3691                PositionAxis::CENTER,
3692                PositionAxis::END,
3693            )),
3694        );
3695        self
3696    }
3697
3698    /// Shows an image's bottom right corner (Tailwind's
3699    /// `object-bottom-right`).
3700    fn object_bottom_right(mut self) -> Self {
3701        self.style().value(
3702            StyleKey::ObjectPosition,
3703            PropertyValue::ObjectPosition(ObjectPosition::new(
3704                PositionAxis::END,
3705                PositionAxis::END,
3706            )),
3707        );
3708        self
3709    }
3710
3711    /// Invisible while its 3D rotations turn it away (a card's back).
3712    fn backface_hidden(mut self) -> Self {
3713        self.style()
3714            .value(StyleKey::BackfaceVisibility, PropertyValue::Bool(true));
3715        self
3716    }
3717
3718    /// Visible from behind too (the default).
3719    fn backface_visible(mut self) -> Self {
3720        self.style()
3721            .value(StyleKey::BackfaceVisibility, PropertyValue::Bool(false));
3722        self
3723    }
3724
3725    // Text (inherited by the texts inside).
3726
3727    /// The text color.
3728    fn text_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3729        self.style().bind_value(color, |s, color: AdaptiveColor| {
3730            s.color(&[StyleKey::Color], color);
3731        });
3732        self
3733    }
3734
3735    /// The tint color (Tailwind's `tint-*`): of template images, and of a
3736    /// page header's buttons in [`super::Screen::header_style_with`].
3737    fn tint_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3738        self.style().bind_value(color, |s, color: AdaptiveColor| {
3739            s.color(&[StyleKey::TintColor], color);
3740        });
3741        self
3742    }
3743
3744    /// The color a system control shows its state in (`accentColor`, CSS's
3745    /// `accent-color`, Tailwind's `accent-*`): the track of
3746    /// a system switch when on. Set on the control itself; it is
3747    /// not inherited.
3748    fn accent_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3749        self.style().bind_value(color, |s, color: AdaptiveColor| {
3750            s.color(&[StyleKey::AccentColor], color);
3751        });
3752        self
3753    }
3754
3755    /// What the shapes the element draws are filled with (`fill`,
3756    /// Tailwind's `fill-<color>`; the elements inside inherit it, as in
3757    /// CSS): the areas of `nsh_base::plot`.
3758    fn fill_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3759        self.style().bind_value(color, |s, color: AdaptiveColor| {
3760            s.color(&[StyleKey::Fill], color);
3761        });
3762        self
3763    }
3764
3765    /// No fill (`fill-none`).
3766    fn fill_none(mut self) -> Self {
3767        self.style().value(
3768            StyleKey::Fill,
3769            PropertyValue::Paint(Some(crate::SvgPaint::None)),
3770        );
3771        self
3772    }
3773
3774    /// The text color as the fill (`fill-current`, `currentColor`).
3775    fn fill_current(mut self) -> Self {
3776        self.style().value(
3777            StyleKey::Fill,
3778            PropertyValue::Paint(Some(crate::SvgPaint::CurrentColor)),
3779        );
3780        self
3781    }
3782
3783    /// What the outlines of the shapes the element draws are painted with
3784    /// (`stroke`, Tailwind's `stroke-<color>`; inherited, as in CSS): the
3785    /// lines and grids of `nsh_base::plot`.
3786    fn stroke_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3787        self.style().bind_value(color, |s, color: AdaptiveColor| {
3788            s.color(&[StyleKey::Stroke], color);
3789        });
3790        self
3791    }
3792
3793    /// No stroke (`stroke-none`).
3794    fn stroke_none(mut self) -> Self {
3795        self.style().value(
3796            StyleKey::Stroke,
3797            PropertyValue::Paint(Some(crate::SvgPaint::None)),
3798        );
3799        self
3800    }
3801
3802    /// The text color as the stroke (`stroke-current`, `currentColor`).
3803    fn stroke_current(mut self) -> Self {
3804        self.style().value(
3805            StyleKey::Stroke,
3806            PropertyValue::Paint(Some(crate::SvgPaint::CurrentColor)),
3807        );
3808        self
3809    }
3810
3811    /// The width of those outlines (`strokeWidth`, Tailwind's
3812    /// `stroke-<number>`; 1 by default, inherited).
3813    fn stroke_width(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
3814        self.style().bind_value(width, |s, width: AbsoluteLength| {
3815            s.number(StyleKey::StrokeWidth, points(width));
3816        });
3817        self
3818    }
3819
3820    /// The font size, in points.
3821    fn text_size(mut self, size: impl IntoReactive<Length>) -> Self {
3822        self.style().bind_value(size, |s, size: Length| {
3823            s.lengths(&[StyleKey::FontSize], size);
3824        });
3825        self
3826    }
3827
3828    /// 12pt text, 16pt lines.
3829    fn text_xs(mut self) -> Self {
3830        self.style().push(Declaration::TextPreset("xs"));
3831        self
3832    }
3833
3834    /// 14pt text, 20pt lines.
3835    fn text_sm(mut self) -> Self {
3836        self.style().push(Declaration::TextPreset("sm"));
3837        self
3838    }
3839
3840    /// 16pt text, 24pt lines.
3841    fn text_base(mut self) -> Self {
3842        self.style().push(Declaration::TextPreset("base"));
3843        self
3844    }
3845
3846    /// 18pt text, 28pt lines.
3847    fn text_lg(mut self) -> Self {
3848        self.style().push(Declaration::TextPreset("lg"));
3849        self
3850    }
3851
3852    /// 20pt text, 28pt lines.
3853    fn text_xl(mut self) -> Self {
3854        self.style().push(Declaration::TextPreset("xl"));
3855        self
3856    }
3857
3858    /// 24pt text, 32pt lines.
3859    fn text_2xl(mut self) -> Self {
3860        self.style().push(Declaration::TextPreset("2xl"));
3861        self
3862    }
3863
3864    /// 30pt text, 36pt lines.
3865    fn text_3xl(mut self) -> Self {
3866        self.style().push(Declaration::TextPreset("3xl"));
3867        self
3868    }
3869
3870    /// 36pt text, 40pt lines.
3871    fn text_4xl(mut self) -> Self {
3872        self.style().push(Declaration::TextPreset("4xl"));
3873        self
3874    }
3875
3876    /// 48pt text, 48pt lines.
3877    fn text_5xl(mut self) -> Self {
3878        self.style().push(Declaration::TextPreset("5xl"));
3879        self
3880    }
3881
3882    /// 60pt text, 60pt lines.
3883    fn text_6xl(mut self) -> Self {
3884        self.style().push(Declaration::TextPreset("6xl"));
3885        self
3886    }
3887
3888    /// 72pt text, 72pt lines.
3889    fn text_7xl(mut self) -> Self {
3890        self.style().push(Declaration::TextPreset("7xl"));
3891        self
3892    }
3893
3894    /// 96pt text, 96pt lines.
3895    fn text_8xl(mut self) -> Self {
3896        self.style().push(Declaration::TextPreset("8xl"));
3897        self
3898    }
3899
3900    /// 128pt text, 128pt lines.
3901    fn text_9xl(mut self) -> Self {
3902        self.style().push(Declaration::TextPreset("9xl"));
3903        self
3904    }
3905
3906    /// The line height: points (`px(20.0)`), or a multiple of the font
3907    /// size (`LineHeight::Multiple(1.5)`).
3908    fn line_height(mut self, height: impl IntoReactive<LineHeight>) -> Self {
3909        self.style().bind_value(height, |s, height: LineHeight| {
3910            s.value(StyleKey::LineHeight, PropertyValue::LineHeight(height));
3911        });
3912        self
3913    }
3914
3915    /// The font weight.
3916    fn font_weight(mut self, weight: FontWeight) -> Self {
3917        self.style().number(StyleKey::FontWeight, weight.0 as f32);
3918        self
3919    }
3920
3921    /// The font family (`None` style: the system font is the default).
3922    fn font_family(mut self, family: impl IntoReactive<SharedString>) -> Self {
3923        self.style().bind_value(family, |s, family: SharedString| {
3924            s.value(
3925                StyleKey::FontFamily,
3926                PropertyValue::FontFamily(Some(crate::FontFamily::new(family.trim()))),
3927            );
3928        });
3929        self
3930    }
3931
3932    /// Italic text.
3933    fn italic(mut self) -> Self {
3934        self.style()
3935            .value(StyleKey::FontStyle, PropertyValue::OptBool(Some(true)));
3936        self
3937    }
3938
3939    /// Underlined text (with [`Styled::line_through`], both lines).
3940    fn underline(mut self) -> Self {
3941        self.style().push(Declaration::Decoration(UNDERLINE));
3942        self
3943    }
3944
3945    /// Struck-through text (with [`Styled::underline`], both lines).
3946    fn line_through(mut self) -> Self {
3947        self.style().push(Declaration::Decoration(LINE_THROUGH));
3948        self
3949    }
3950
3951    /// No underline nor strike-through.
3952    fn no_underline(mut self) -> Self {
3953        self.style().push(Declaration::Decoration(0));
3954        self
3955    }
3956
3957    /// The color of the underline and strike-through (the text's by
3958    /// default).
3959    fn text_decoration_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
3960        self.style().bind_value(color, |s, color: AdaptiveColor| {
3961            s.color(&[StyleKey::TextDecorationColor], color);
3962        });
3963        self
3964    }
3965
3966    /// Solid decoration lines (the default).
3967    fn text_decoration_solid(mut self) -> Self {
3968        self.style().value(
3969            StyleKey::TextDecorationStyle,
3970            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Solid)),
3971        );
3972        self
3973    }
3974
3975    /// Double decoration lines.
3976    fn text_decoration_double(mut self) -> Self {
3977        self.style().value(
3978            StyleKey::TextDecorationStyle,
3979            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Double)),
3980        );
3981        self
3982    }
3983
3984    /// Dotted decoration lines.
3985    fn text_decoration_dotted(mut self) -> Self {
3986        self.style().value(
3987            StyleKey::TextDecorationStyle,
3988            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Dotted)),
3989        );
3990        self
3991    }
3992
3993    /// Dashed decoration lines.
3994    fn text_decoration_dashed(mut self) -> Self {
3995        self.style().value(
3996            StyleKey::TextDecorationStyle,
3997            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Dashed)),
3998        );
3999        self
4000    }
4001
4002    /// Wavy decoration lines (spelling marks).
4003    fn text_decoration_wavy(mut self) -> Self {
4004        self.style().value(
4005            StyleKey::TextDecorationStyle,
4006            PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Wavy)),
4007        );
4008        self
4009    }
4010
4011    /// The decoration lines' thickness.
4012    fn text_decoration_thickness(mut self, thickness: impl IntoReactive<Points>) -> Self {
4013        self.style().bind_value(thickness, |s, thickness: Points| {
4014            s.number(StyleKey::TextDecorationThickness, thickness.0);
4015        });
4016        self
4017    }
4018
4019    /// The underline's distance below the baseline.
4020    fn underline_offset(mut self, offset: impl IntoReactive<Points>) -> Self {
4021        self.style().bind_value(offset, |s, offset: Points| {
4022            s.number(StyleKey::TextUnderlineOffset, offset.0);
4023        });
4024        self
4025    }
4026
4027    /// Shown in capitals (the content stays as it is).
4028    fn uppercase(mut self) -> Self {
4029        self.style().value(
4030            StyleKey::TextTransform,
4031            PropertyValue::TextTransform(Some(crate::TextTransform::Uppercase)),
4032        );
4033        self
4034    }
4035
4036    /// Shown in small letters.
4037    fn lowercase(mut self) -> Self {
4038        self.style().value(
4039            StyleKey::TextTransform,
4040            PropertyValue::TextTransform(Some(crate::TextTransform::Lowercase)),
4041        );
4042        self
4043    }
4044
4045    /// Each word shown with a capital first letter.
4046    fn capitalize(mut self) -> Self {
4047        self.style().value(
4048            StyleKey::TextTransform,
4049            PropertyValue::TextTransform(Some(crate::TextTransform::Capitalize)),
4050        );
4051        self
4052    }
4053
4054    /// Shown as written (undoes an inherited case).
4055    fn normal_case(mut self) -> Self {
4056        self.style().value(
4057            StyleKey::TextTransform,
4058            PropertyValue::TextTransform(Some(crate::TextTransform::None)),
4059        );
4060        self
4061    }
4062
4063    /// Digits of one width, for columns of numbers.
4064    fn tabular_nums(self) -> Self {
4065        font_variant(
4066            self,
4067            FontVariant::TABULAR_NUMS,
4068            FontVariant::PROPORTIONAL_NUMS,
4069        )
4070    }
4071
4072    /// Digits of their own widths (the default).
4073    fn proportional_nums(self) -> Self {
4074        font_variant(
4075            self,
4076            FontVariant::PROPORTIONAL_NUMS,
4077            FontVariant::TABULAR_NUMS,
4078        )
4079    }
4080
4081    /// Old-style digits, with ascenders and descenders.
4082    fn oldstyle_nums(self) -> Self {
4083        font_variant(self, FontVariant::OLDSTYLE_NUMS, FontVariant::LINING_NUMS)
4084    }
4085
4086    /// Lining digits, all of capital height.
4087    fn lining_nums(self) -> Self {
4088        font_variant(self, FontVariant::LINING_NUMS, FontVariant::OLDSTYLE_NUMS)
4089    }
4090
4091    /// Small capitals for lower-case letters.
4092    fn small_caps(self) -> Self {
4093        font_variant(self, FontVariant::SMALL_CAPS, 0)
4094    }
4095
4096    /// The font's own number forms (undoes the number forms set before;
4097    /// `small_caps` stays).
4098    fn normal_nums(self) -> Self {
4099        font_variant(self, 0, !FontVariant::SMALL_CAPS)
4100    }
4101
4102    /// The layout direction of the view and its subtree (by default its
4103    /// parent's; the surface's follows the user's language).
4104    fn direction(mut self, direction: impl IntoReactive<LayoutDirection>) -> Self {
4105        self.style()
4106            .bind_value(direction, |s, direction: LayoutDirection| {
4107                s.value(
4108                    StyleKey::Direction,
4109                    PropertyValue::OptBool(match direction {
4110                        LayoutDirection::Inherit => None,
4111                        LayoutDirection::Ltr => Some(false),
4112                        LayoutDirection::Rtl => Some(true),
4113                    }),
4114                );
4115            });
4116        self
4117    }
4118
4119    /// At most `lines` lines (`numberOfLines`; 0: no limit), the last one cut
4120    /// as [`Styled::text_overflow`] says.
4121    fn number_of_lines(mut self, lines: impl IntoReactive<u32>) -> Self {
4122        self.style().bind_value(lines, |s, lines: u32| {
4123            s.value(
4124                StyleKey::NumberOfLines,
4125                PropertyValue::NumberOfLines(Some(lines)),
4126            );
4127        });
4128        self
4129    }
4130
4131    /// Where a clamped text is cut (`textOverflow`): its end with an
4132    /// ellipsis (`Tail`, the default), its start or middle, or clipped.
4133    fn text_overflow(mut self, mode: impl IntoReactive<crate::EllipsizeMode>) -> Self {
4134        self.style()
4135            .bind_value(mode, |s, mode: crate::EllipsizeMode| {
4136                s.value(
4137                    StyleKey::TextOverflow,
4138                    PropertyValue::TextOverflow(Some(mode)),
4139                );
4140            });
4141        self
4142    }
4143
4144    /// One line, cut with an ellipsis (Tailwind's `truncate`).
4145    fn truncate(self) -> Self {
4146        self.number_of_lines(1u32)
4147            .text_overflow(crate::EllipsizeMode::Tail)
4148    }
4149
4150    /// Its texts' lines never wrap (Tailwind's `whitespace-nowrap`). A
4151    /// view's reaches the texts in it, as CSS's `white-space` does.
4152    fn whitespace_nowrap(mut self) -> Self {
4153        self.style().push(Declaration::NoWrap(true));
4154        self
4155    }
4156
4157    /// Its texts' lines wrap (Tailwind's `whitespace-normal`): undoes a
4158    /// view's `whitespace_nowrap` or `text_pretty` around them.
4159    fn whitespace_normal(mut self) -> Self {
4160        self.style().push(Declaration::NoWrap(false));
4161        self
4162    }
4163
4164    /// Its texts' lines wrap without leaving a word or two alone on the
4165    /// last line (Tailwind's `text-pretty`): a last line shorter than a
4166    /// quarter of the box takes words from the lines above, without adding
4167    /// a line. A view's reaches the texts in it.
4168    fn text_pretty(mut self) -> Self {
4169        self.style().push(Declaration::Pretty);
4170        self
4171    }
4172
4173    /// The text's base direction (by default its content's).
4174    fn writing_direction(mut self, direction: WritingDirection) -> Self {
4175        self.style().value(
4176            StyleKey::WritingDirection,
4177            PropertyValue::OptBool(match direction {
4178                WritingDirection::Auto => None,
4179                WritingDirection::Ltr => Some(false),
4180                WritingDirection::Rtl => Some(true),
4181            }),
4182        );
4183        self
4184    }
4185
4186    /// Lines stretched to both edges.
4187    fn text_justify(mut self) -> Self {
4188        self.style().value(
4189            StyleKey::TextAlign,
4190            PropertyValue::TextAlign(Some(crate::TextAlign::Justify), false),
4191        );
4192        self
4193    }
4194
4195    /// Tailwind's `text-shadow-2xs`.
4196    fn text_shadow_2xs(mut self) -> Self {
4197        self.style().push(Declaration::TextShadow("2xs"));
4198        self
4199    }
4200
4201    /// Tailwind's `text-shadow-xs`.
4202    fn text_shadow_xs(mut self) -> Self {
4203        self.style().push(Declaration::TextShadow("xs"));
4204        self
4205    }
4206
4207    /// Tailwind's `text-shadow-sm`.
4208    fn text_shadow_sm(mut self) -> Self {
4209        self.style().push(Declaration::TextShadow("sm"));
4210        self
4211    }
4212
4213    /// Tailwind's `text-shadow-md`.
4214    fn text_shadow_md(mut self) -> Self {
4215        self.style().push(Declaration::TextShadow("md"));
4216        self
4217    }
4218
4219    /// Tailwind's `text-shadow-lg`.
4220    fn text_shadow_lg(mut self) -> Self {
4221        self.style().push(Declaration::TextShadow("lg"));
4222        self
4223    }
4224
4225    /// No text shadow from the presets.
4226    fn text_shadow_none(mut self) -> Self {
4227        self.style().push(Declaration::TextShadow("none"));
4228        self
4229    }
4230
4231    /// The text shadow's color: of a preset or of [`Styled::text_shadow`]'s
4232    /// layers (an opaque color keeps their alpha).
4233    fn text_shadow_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
4234        let color = color.into();
4235        self.style()
4236            .push(Declaration::PartColor(ColorPart::TextShadow, color));
4237        self
4238    }
4239
4240    /// Text shadows of its own (CSS's `text-shadow`: offsets, blur and
4241    /// color), instead of a preset's; drawn as the widest one.
4242    fn text_shadow(mut self, layers: impl IntoIterator<Item = crate::TextShadow>) -> Self {
4243        let layers: Arc<[crate::TextShadow]> = layers.into_iter().collect();
4244        self.style()
4245            .push(Declaration::TextShadows(TextLayers(layers)));
4246        self
4247    }
4248
4249    /// Text aligned left.
4250    fn text_left(mut self) -> Self {
4251        self.style().value(
4252            StyleKey::TextAlign,
4253            PropertyValue::TextAlign(Some(crate::TextAlign::Left), true),
4254        );
4255        self
4256    }
4257
4258    /// Text centered.
4259    fn text_center(mut self) -> Self {
4260        self.style().value(
4261            StyleKey::TextAlign,
4262            PropertyValue::TextAlign(Some(crate::TextAlign::Center), false),
4263        );
4264        self
4265    }
4266
4267    /// Text aligned right.
4268    fn text_right(mut self) -> Self {
4269        self.style().value(
4270            StyleKey::TextAlign,
4271            PropertyValue::TextAlign(Some(crate::TextAlign::Right), true),
4272        );
4273        self
4274    }
4275
4276    /// Inside a text, its bottom on the baseline (the default:
4277    /// `align-baseline`).
4278    fn align_baseline(mut self) -> Self {
4279        self.style().value(
4280            StyleKey::VerticalAlign,
4281            PropertyValue::VerticalAlign(crate::VerticalAlign::Baseline),
4282        );
4283        self
4284    }
4285
4286    /// Inside a text, its top at the top of the text's font
4287    /// (`align-text-top`).
4288    fn align_text_top(mut self) -> Self {
4289        self.style().value(
4290            StyleKey::VerticalAlign,
4291            PropertyValue::VerticalAlign(crate::VerticalAlign::TextTop),
4292        );
4293        self
4294    }
4295
4296    /// Inside a text, its bottom at the bottom of the text's font
4297    /// (`align-text-bottom`).
4298    fn align_text_bottom(mut self) -> Self {
4299        self.style().value(
4300            StyleKey::VerticalAlign,
4301            PropertyValue::VerticalAlign(crate::VerticalAlign::TextBottom),
4302        );
4303        self
4304    }
4305
4306    /// Inside a text, its middle half the font's x height above the
4307    /// baseline (`align-middle`).
4308    fn align_middle(mut self) -> Self {
4309        self.style().value(
4310            StyleKey::VerticalAlign,
4311            PropertyValue::VerticalAlign(crate::VerticalAlign::Middle),
4312        );
4313        self
4314    }
4315
4316    /// Extra space between letters.
4317    fn letter_spacing(mut self, spacing: impl IntoReactive<AbsoluteLength>) -> Self {
4318        self.style()
4319            .bind_value(spacing, |s, spacing: AbsoluteLength| {
4320                s.number(StyleKey::LetterSpacing, points(spacing));
4321            });
4322        self
4323    }
4324
4325    // Variants (native: nothing runs).
4326
4327    /// `f`'s styles while `when` holds: a value decides once, a signal or a
4328    /// closure switches them as it changes (Tailwind's classes made
4329    /// conditional; native states such as `.active` need none).
4330    fn style_when(
4331        mut self,
4332        when: impl IntoReactive<bool>,
4333        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4334    ) -> Self {
4335        let layer = f(StyleRefinement::default());
4336        match when.into_reactive() {
4337            Reactive::Static(true) => self.style().extend_as(Variant::default(), layer),
4338            Reactive::Static(false) => {}
4339            Reactive::Bound(when) => self.style().bind(move |s| {
4340                if when() {
4341                    s.extend_as(Variant::default(), layer.resolved());
4342                }
4343            }),
4344        }
4345        self
4346    }
4347
4348    /// The styles `f` makes, made again when what it reads changes (any
4349    /// style that depends on the app's state; a value that changes alone
4350    /// is better given to its method: `.w(move || px(width.get()))`).
4351    fn style_with(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
4352        self.style().bind(move |s| {
4353            let made = f(StyleRefinement::default()).resolved();
4354            s.extend_as(Variant::default(), made);
4355        });
4356        self
4357    }
4358
4359    /// Styles in dark appearance (Tailwind's `dark:`), for what is not a
4360    /// color: theme colors switch by themselves.
4361    fn dark(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4362        let s = f(StyleRefinement::default());
4363        self.style().extend_as(Variant::DARK, s);
4364        self
4365    }
4366
4367    /// Styles while selected (Tailwind's `selected:`): the element's
4368    /// accessibility state says so (a `Button`'s `selected`, a tab's).
4369    fn selected(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4370        let s = f(StyleRefinement::default());
4371        self.style().extend_as(Variant::SELECTED, s);
4372        self
4373    }
4374
4375    /// Styles while checked (Tailwind's `checked:`): the element's
4376    /// accessibility state says so, not mixed (a checkbox's, a switch's, a
4377    /// radio's), or the control it is a part of is
4378    /// (`Interactive::project_checked`: a switch's thumb).
4379    fn checked(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4380        let s = f(StyleRefinement::default());
4381        self.style().extend_as(Variant::CHECKED, s);
4382        self
4383    }
4384
4385    /// Styles while indeterminate (Tailwind's `indeterminate:`): the
4386    /// element's accessibility state says checked is mixed (a checkbox
4387    /// that is neither), or the control it is a part of is
4388    /// (`Interactive::project_indeterminate`: a checkbox's indicator).
4389    fn indeterminate(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4390        let s = f(StyleRefinement::default());
4391        self.style().extend_as(Variant::INDETERMINATE, s);
4392        self
4393    }
4394
4395    /// Styles while expanded (Tailwind's `aria-expanded:`): the element's
4396    /// accessibility state says so (a `Popover`'s or `Menu`'s trigger
4397    /// while its popup is open, a collapsible's header).
4398    fn expanded(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4399        let s = f(StyleRefinement::default());
4400        self.style().extend_as(Variant::EXPANDED, s);
4401        self
4402    }
4403
4404    /// Styles while a toggle button is on (Tailwind's `aria-pressed:`):
4405    /// the element's accessibility state says it is pressed, not mixed
4406    /// (`gpui-base`'s `Toggle` styled `pressed`). Not `.active(..)`, a
4407    /// press in progress.
4408    fn aria_pressed(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4409        let s = f(StyleRefinement::default());
4410        self.style().extend_as(Variant::ARIA_PRESSED, s);
4411        self
4412    }
4413
4414    /// Makes it a group: the `group_*` styles of the elements inside follow
4415    /// its press, hover and focus (Tailwind's `group`).
4416    fn group(mut self) -> Self {
4417        self.style().push(Declaration::Group(""));
4418        self
4419    }
4420
4421    /// Makes it the group `name` (`group/name`), for `group_*_named`
4422    /// styles inside it that skip nearer groups.
4423    fn group_named(mut self, name: &'static str) -> Self {
4424        self.style().push(Declaration::Group(name));
4425        self
4426    }
4427
4428    /// Styles while the nearest [`Styled::group`] around it is pressed
4429    /// (`group-active:`).
4430    fn group_active(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4431        in_group(self, "", state::PRESSED, f)
4432    }
4433
4434    /// Styles while the nearest group around it is hovered.
4435    fn group_hover(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4436        in_group(self, "", state::HOVERED, f)
4437    }
4438
4439    /// Styles while an input in the nearest group around it has focus
4440    /// (`group-focus-within:`).
4441    fn group_focus_within(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4442        in_group(self, "", state::FOCUS_WITHIN, f)
4443    }
4444
4445    /// Styles while the nearest group around it has the keyboard focus
4446    /// and shows it (`group-focus-visible:`).
4447    fn group_focus_visible(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
4448        in_group(self, "", state::FOCUS_VISIBLE, f)
4449    }
4450
4451    /// Styles while the group `name` around it is pressed
4452    /// (`group-active/name:`).
4453    fn group_active_named(
4454        self,
4455        name: &'static str,
4456        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4457    ) -> Self {
4458        in_group(self, name, state::PRESSED, f)
4459    }
4460
4461    /// Styles while the group `name` around it is hovered.
4462    fn group_hover_named(
4463        self,
4464        name: &'static str,
4465        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4466    ) -> Self {
4467        in_group(self, name, state::HOVERED, f)
4468    }
4469
4470    /// Styles while an input in the group `name` around it has focus.
4471    fn group_focus_within_named(
4472        self,
4473        name: &'static str,
4474        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4475    ) -> Self {
4476        in_group(self, name, state::FOCUS_WITHIN, f)
4477    }
4478
4479    /// Styles while the group `name` around it has the keyboard focus and
4480    /// shows it (`group-focus-visible/name:`).
4481    fn group_focus_visible_named(
4482        self,
4483        name: &'static str,
4484        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4485    ) -> Self {
4486        in_group(self, name, state::FOCUS_VISIBLE, f)
4487    }
4488}
4489
4490/// `s` with filter `f` by `amount` (of what is behind it when `backdrop`).
4491/// `s` with the transform step `step` makes of `value` (its kind and
4492/// operand).
4493fn transform_with<S: Styled, T: Clone + 'static>(
4494    mut s: S,
4495    value: impl IntoReactive<T>,
4496    step: impl Fn(T) -> (TransformKind, f32) + 'static,
4497) -> S {
4498    // Steps compose in order: after a bound part, a static step is
4499    // applied with the bound ones too.
4500    let style = s.style();
4501    match value.into_reactive() {
4502        Reactive::Static(value) if !style.is_bound() => {
4503            let (kind, amount) = step(value);
4504            style.push(Declaration::Transform(kind, Bits(amount)));
4505        }
4506        value => style.bind(move |st| {
4507            let (kind, amount) = step(value.get());
4508            st.push(Declaration::Transform(kind, Bits(amount)));
4509        }),
4510    }
4511    s
4512}
4513
4514/// `reset` (`transform_none()`, ...), in order with the bound steps.
4515fn transform_reset<S: Styled>(mut s: S, reset: Declaration) -> S {
4516    let style = s.style();
4517    if style.is_bound() {
4518        style.bind(move |st| st.push(reset.clone()));
4519    } else {
4520        style.push(reset);
4521    }
4522    s
4523}
4524
4525/// A translation's step: points (a rem at [`REM_SIZE`]) or a fraction of
4526/// the size.
4527fn translation(
4528    offset: DefiniteLength,
4529    points_kind: TransformKind,
4530    fraction_kind: TransformKind,
4531) -> (TransformKind, f32) {
4532    match offset {
4533        DefiniteLength::Absolute(a) => (points_kind, points(a)),
4534        DefiniteLength::Fraction(f) => (fraction_kind, f.0),
4535    }
4536}
4537
4538fn filter<S: Styled>(mut s: S, backdrop: bool, f: FilterFn, amount: f32) -> S {
4539    s.style()
4540        .push(Declaration::Filter(backdrop, f, Bits(amount)));
4541    s
4542}
4543
4544/// `s` with transitions of the [`TransitionProps`] `props`.
4545fn transition<S: Styled>(mut s: S, props: u8) -> S {
4546    s.style().push(Declaration::Transition(props));
4547    s
4548}
4549
4550/// `s` with `f`'s styles while the group `name` is in `states`.
4551fn in_group<S: Styled>(
4552    mut s: S,
4553    name: &'static str,
4554    states: u16,
4555    f: impl FnOnce(StyleRefinement) -> StyleRefinement,
4556) -> S {
4557    let styles = f(StyleRefinement::default());
4558    let style = s.style();
4559    let group = style.name(name);
4560    style.extend_as(
4561        Variant {
4562            group_states: states,
4563            group,
4564            ..Variant::default()
4565        },
4566        styles,
4567    );
4568    s
4569}
4570
4571impl Styled for StyleRefinement {
4572    fn style(&mut self) -> &mut StyleRefinement {
4573        self
4574    }
4575}
4576
4577#[cfg(test)]
4578mod tests {
4579    use super::*;
4580    use crate::{
4581        Style,
4582        color::{black, rgba},
4583        element::palette::{EMERALD, PINK, RED, SKY, VIOLET},
4584        geometry::point,
4585        tailwind::{ClassEnvironment, ClassProps, Context},
4586    };
4587
4588    /// What `list` resolves to in `dark` appearance, in [`state`] `states`,
4589    /// inside a group in `group` (as text, to compare).
4590    fn resolve(list: &ClassList, dark: bool, states: u16, group: u16) -> String {
4591        resolve_with(list, dark, states, group, &|_| {})
4592    }
4593
4594    /// [`resolve`], then `inline` on the style.
4595    fn resolve_with(
4596        list: &ClassList,
4597        dark: bool,
4598        states: u16,
4599        group: u16,
4600        inline: &dyn Fn(&mut Style),
4601    ) -> String {
4602        let cx = Context {
4603            env: ClassEnvironment {
4604                dark,
4605                ..Default::default()
4606            },
4607            window: crate::geometry::size_pt(390.0, 844.0),
4608            rtl: false,
4609            states,
4610            position: 0,
4611            group: &|_| group,
4612        };
4613        let mut style = Style::default();
4614        let mut props = ClassProps::default();
4615        list.apply(&cx, &PRESETS, &mut style, &mut props, inline);
4616        format!("{style:?} {props:?}")
4617    }
4618
4619    /// `typed` styles an element as Tailwind's `classes` do, in both
4620    /// appearances and in every state.
4621    #[track_caller]
4622    fn same(typed: StyleRefinement, classes: &str) {
4623        same_with(typed, classes, &|_| {});
4624    }
4625
4626    /// [`same`], `classes` then `inline` (what classes cannot say).
4627    #[track_caller]
4628    fn same_with(typed: StyleRefinement, classes: &str, inline: &dyn Fn(&mut Style)) {
4629        let typed = typed.lower();
4630        let parsed = tailwind::parse(&PRESETS, classes);
4631        assert!(parsed.unknown().is_empty(), "{:?}", parsed.unknown());
4632        assert_eq!(typed.deps(), parsed.deps(), "{classes}: deps");
4633        assert_eq!(typed.groups(), parsed.groups(), "{classes}: groups");
4634        for dark in [false, true] {
4635            for states in [0, state::PRESSED, state::DISABLED] {
4636                for group in [0, state::PRESSED, state::HOVERED] {
4637                    assert_eq!(
4638                        resolve(&typed, dark, states, group),
4639                        resolve_with(&parsed, dark, states, group, inline),
4640                        "{classes} (dark {dark}, states {states}, group {group})"
4641                    );
4642                }
4643            }
4644        }
4645    }
4646
4647    fn s() -> StyleRefinement {
4648        StyleRefinement::default()
4649    }
4650
4651    #[test]
4652    fn env_methods_are_the_arbitrary_classes() {
4653        let env_of = |list: &ClassList| {
4654            let cx = Context {
4655                env: ClassEnvironment::default(),
4656                window: crate::geometry::size_pt(390.0, 844.0),
4657                rtl: false,
4658                states: 0,
4659                position: 0,
4660                group: &|_| 0,
4661            };
4662            let mut style = Style::default();
4663            list.apply(
4664                &cx,
4665                &PRESETS,
4666                &mut style,
4667                &mut ClassProps::default(),
4668                |_: &mut Style| {},
4669            );
4670            style.pending.env
4671        };
4672        let sides = |p: &str| {
4673            ["top", "right", "bottom", "left"]
4674                .map(|side| format!("{p}{}-[env(safe-area-inset-{side})]", &side[..1]))
4675                .join(" ")
4676        };
4677        for (typed, classes) in [
4678            (s().p_safe_area(), sides("p")),
4679            (s().m_safe_area(), sides("m")),
4680            (
4681                s().px_safe_area(),
4682                "pr-[env(safe-area-inset-right)] pl-[env(safe-area-inset-left)]".into(),
4683            ),
4684            (
4685                s().my_safe_area(),
4686                "mt-[env(safe-area-inset-top)] mb-[env(safe-area-inset-bottom)]".into(),
4687            ),
4688            (s().pl_safe_area(), "pl-[env(safe-area-inset-left)]".into()),
4689            (
4690                s().pt_safe_area_plus(px(8.0)),
4691                "pt-[calc(env(safe-area-inset-top)+8px)]".into(),
4692            ),
4693            (s().pb_keyboard(), "pb-[env(keyboard-inset-height)]".into()),
4694            (
4695                s().mb_keyboard_plus(px(49.0)),
4696                "mb-[calc(env(keyboard-inset-height)+49px)]".into(),
4697            ),
4698        ] {
4699            same(typed.clone(), &classes);
4700            let parsed = tailwind::parse(&PRESETS, &classes);
4701            assert_eq!(env_of(&typed.lower()), env_of(&parsed), "{classes}");
4702            assert!(!env_of(&parsed).is_empty(), "{classes}");
4703        }
4704    }
4705
4706    #[test]
4707    fn svg_paint_is_tailwinds() {
4708        same(
4709            s().fill_color(RED.shade(600))
4710                .stroke_color(SKY.shade(500))
4711                .stroke_width(px(2.0)),
4712            "fill-red-600 stroke-sky-500 stroke-2",
4713        );
4714        same(s().fill_none().stroke_current(), "fill-none stroke-current");
4715        same(s().fill_current().stroke_none(), "fill-current stroke-none");
4716    }
4717
4718    #[test]
4719    fn flex_is_tailwinds_row() {
4720        // `.flex()` is a row unless a direction is set, as the class is.
4721        same(s().flex(), "flex");
4722        same(s().flex().flex_col(), "flex flex-col");
4723        same(s().flex_col().flex(), "flex-col flex");
4724        same(s().items_center(), "items-center");
4725    }
4726
4727    #[test]
4728    fn auto_minimum_sizes_are_tailwinds() {
4729        // CSS's automatic minimum, as `min-w-auto` / `min-h-auto` are.
4730        same(
4731            s().min_w(crate::geometry::auto())
4732                .min_h(crate::geometry::auto()),
4733            "min-w-auto min-h-auto",
4734        );
4735    }
4736
4737    #[test]
4738    fn borders_and_corners_are_tailwinds() {
4739        same(
4740            s().border_t(px(6.0))
4741                .border_t_color(RED.shade(600))
4742                .border_r(px(2.0))
4743                .border_b(px(4.0))
4744                .border_l(px(1.0))
4745                .border_x_color(SKY.shade(500)),
4746            "border-t-6 border-t-red-600 border-r-2 border-b-4 border-l border-x-sky-500",
4747        );
4748        same(
4749            s().border_y(px(3.0))
4750                .border_s(px(1.0))
4751                .border_e(px(2.0))
4752                .border_dashed(),
4753            "border-y-3 border-s border-e-2 border-dashed",
4754        );
4755        same(s().border_none().border(px(2.0)), "border-none border-2");
4756        same(
4757            s().border(px(3.0)).border_dotted(),
4758            "border-3 border-dotted",
4759        );
4760        same(
4761            s().rounded_tl(px(44.0))
4762                .rounded_tr(px(6.0))
4763                .rounded_br(px(28.0))
4764                .rounded_bl(px(2.0)),
4765            "rounded-tl-[44px] rounded-tr-[6px] rounded-br-[28px] rounded-bl-[2px]",
4766        );
4767        same(
4768            s().rounded_ss(px(22.0))
4769                .rounded_ee(px(8.0))
4770                .rounded_l(px(4.0)),
4771            "rounded-ss-[22px] rounded-ee-[8px] rounded-l-[4px]",
4772        );
4773        same(
4774            s().outline(px(2.0))
4775                .outline_offset(px(2.0))
4776                .outline_dashed()
4777                .outline_color(PINK.shade(500)),
4778            "outline-2 outline-offset-2 outline-dashed outline-pink-500",
4779        );
4780        same(
4781            s().outline_dotted().outline(px(2.0)),
4782            "outline-dotted outline-2",
4783        );
4784        same(s().outline_dashed(), "outline-dashed");
4785        let curved = s().border_curve(BorderCurve::Continuous).lower();
4786        let mut style = Style::default();
4787        let _ = style.set_key(StyleKey::BorderCurve, crate::StyleValue::Str("continuous"));
4788        assert_eq!(
4789            resolve(&curved, false, 0, 0),
4790            format!("{style:?} {:?}", ClassProps::default())
4791        );
4792    }
4793
4794    #[test]
4795    fn shadows_and_rings_are_tailwinds() {
4796        let emerald = EMERALD.shade(500).opacity(0.5);
4797        same(
4798            s().shadow_lg().shadow_color(emerald),
4799            "shadow-lg shadow-emerald-500/50",
4800        );
4801        same(
4802            s().shadow_xl().shadow_color(SKY.shade(500)),
4803            "shadow-xl shadow-sky-500",
4804        );
4805        same(s().inset_shadow_sm(), "inset-shadow-sm");
4806        same(
4807            s().ring(px(2.0))
4808                .ring_color(SKY.shade(500))
4809                .ring_offset(px(2.0)),
4810            "ring-2 ring-sky-500 ring-offset-2",
4811        );
4812        same(
4813            s().ring(px(1.0)).ring_color(rgba(0x0000_000d)).ring_inset(),
4814            "ring-1 ring-black/5 ring-inset",
4815        );
4816        same(s().text_shadow_md(), "text-shadow-md");
4817        // A theme color of the shadow switches with the appearance.
4818        let adaptive = s()
4819            .shadow_md()
4820            .shadow_color(AdaptiveColor::new(SKY.shade(500), PINK.shade(500)))
4821            .lower();
4822        assert_eq!(adaptive.deps(), tailwind::deps::DARK);
4823        for (dark, hue) in [(false, SKY), (true, PINK)] {
4824            let classes = format!("shadow-md shadow-{}-500", hue.name());
4825            assert_eq!(
4826                resolve(&adaptive, dark, 0, 0),
4827                resolve(&tailwind::parse(&PRESETS, &classes), dark, 0, 0)
4828            );
4829        }
4830    }
4831
4832    #[test]
4833    fn a_parts_input_colors_come_from_the_typed_style() {
4834        let list = s()
4835            .placeholder_color(RED.shade(500))
4836            .caret_color(SKY.shade(500))
4837            .selection_color(EMERALD.shade(500))
4838            .lower();
4839        let mut style = Style::default();
4840        list.apply(
4841            &Context {
4842                env: ClassEnvironment::default(),
4843                window: crate::geometry::size_pt(390.0, 844.0),
4844                rtl: false,
4845                states: 0,
4846                position: 0,
4847                group: &|_| 0,
4848            },
4849            &PRESETS,
4850            &mut style,
4851            &mut ClassProps::default(),
4852            |_| {},
4853        );
4854        assert_eq!(style.text.placeholder_color, Some(RED.shade(500).into()));
4855        assert_eq!(style.text.caret_color, Some(SKY.shade(500).into()));
4856        assert_eq!(style.text.selection_color, Some(EMERALD.shade(500).into()));
4857    }
4858
4859    #[test]
4860    fn custom_shadows_are_layers_of_their_own() {
4861        let list = s()
4862            .text_shadow([crate::TextShadow {
4863                color: rgba(0x0000_0099).into(),
4864                offset_x: px(2.0),
4865                offset_y: px(2.0),
4866                radius: px(4.0),
4867            }])
4868            .lower();
4869        let mut style = Style::default();
4870        list.apply(
4871            &Context {
4872                env: ClassEnvironment::default(),
4873                window: crate::geometry::size_pt(390.0, 844.0),
4874                rtl: false,
4875                states: 0,
4876                position: 0,
4877                group: &|_| 0,
4878            },
4879            &PRESETS,
4880            &mut style,
4881            &mut ClassProps::default(),
4882            |_| {},
4883        );
4884        assert_eq!(style.text.shadow_color, Some(rgba(0x0000_0099).into()));
4885        assert_eq!(style.text.shadow_radius, Some(px(4.0)));
4886        assert_eq!(style.text.shadow_offset, Some(point(px(2.0), px(2.0))));
4887        let layer = BoxShadow {
4888            offset_x: px(0.0),
4889            offset_y: px(2.0),
4890            blur: px(4.0),
4891            spread: px(0.0),
4892            color: rgba(0x0000_000d).into(),
4893            inset: true,
4894        };
4895        same(
4896            s().shadow([layer]),
4897            "shadow-[inset_0_2px_4px_rgb(0_0_0/0.05)]",
4898        );
4899    }
4900
4901    #[test]
4902    fn effects_are_tailwinds() {
4903        same(
4904            s().bg_linear_to_br()
4905                .gradient_from(VIOLET.shade(500))
4906                .gradient_via(PINK.shade(500))
4907                .gradient_to(RED.shade(400)),
4908            "bg-linear-to-br from-violet-500 via-pink-500 to-red-400",
4909        );
4910        same(
4911            s().bg_linear(deg(45.0))
4912                .gradient_from(SKY.shade(400))
4913                .gradient_to(VIOLET.shade(600))
4914                .gradient_to_position(percentage(0.8)),
4915            "bg-linear-45 from-sky-400 to-violet-600 to-80%",
4916        );
4917        same(
4918            s().bg_radial().gradient_from(SKY.shade(200)),
4919            "bg-radial from-sky-200",
4920        );
4921        same(
4922            s().bg_conic(deg(0.0)).gradient_from(RED.shade(500)),
4923            "bg-conic from-red-500",
4924        );
4925        same(s().grayscale(1.0).sepia(1.0), "grayscale sepia");
4926        same(s().blur(px(8.0)).brightness(0.5), "blur-sm brightness-50");
4927        same(
4928            s().saturate(1.5).hue_rotate(deg(90.0)),
4929            "saturate-150 hue-rotate-90",
4930        );
4931        same(
4932            s().backdrop_blur(px(12.0))
4933                .backdrop_saturate(1.5)
4934                .backdrop_sepia(1.0),
4935            "backdrop-blur-md backdrop-saturate-150 backdrop-sepia",
4936        );
4937        same(
4938            s().mix_blend_mode(BlendMode::Multiply),
4939            "mix-blend-multiply",
4940        );
4941        same(s().transition(), "transition");
4942        same(
4943            s().transition_colors()
4944                .duration(150.0)
4945                .ease_in_out()
4946                .delay(75.0),
4947            "transition-colors duration-150 ease-in-out delay-75",
4948        );
4949        same(
4950            s().transition_transform().duration(200.0),
4951            "transition-transform duration-200",
4952        );
4953        let spring = crate::element::Spring {
4954            stiffness: 620.0,
4955            damping: 36.0,
4956            ..crate::element::Spring::default()
4957        };
4958        same(
4959            s().transition_transform().ease_spring(spring),
4960            "transition-transform ease-spring-[620,36]",
4961        );
4962        same(
4963            s().transition_opacity()
4964                .ease_spring(crate::element::Spring {
4965                    mass: 2.0,
4966                    ..spring
4967                }),
4968            "transition-opacity ease-spring-[620,36,2]",
4969        );
4970        same(
4971            s().transition().ease_bezier(0.3, 1.25, 0.6, 1.0),
4972            "transition ease-[cubic-bezier(0.3,1.25,0.6,1)]",
4973        );
4974        for (typed, classes) in [
4975            (s().animate_spin(), "animate-spin"),
4976            (s().animate_ping(), "animate-ping"),
4977            (s().animate_pulse(), "animate-pulse"),
4978            (s().animate_bounce(), "animate-bounce"),
4979        ] {
4980            same(typed, classes);
4981        }
4982    }
4983
4984    #[test]
4985    fn mask_gradients_match_css() {
4986        let css = |value: &'static str| {
4987            move |style: &mut Style| {
4988                style
4989                    .set_key(StyleKey::MaskImage, crate::StyleValue::Str(value))
4990                    .unwrap();
4991            }
4992        };
4993        same_with(
4994            s().mask_linear(
4995                deg(90.0),
4996                [transparent_black(), black(), transparent_black()],
4997            ),
4998            "",
4999            &css("linear-gradient(to right, transparent, black, transparent)"),
5000        );
5001        same_with(
5002            s().mask_linear(
5003                deg(180.0),
5004                [
5005                    (transparent_black(), percentage(0.2)),
5006                    (black(), percentage(0.8)),
5007                ],
5008            ),
5009            "",
5010            &css("linear-gradient(to bottom, transparent 20%, black 80%)"),
5011        );
5012        same_with(
5013            s().mask_linear(
5014                deg(90.0),
5015                [(transparent_black(), px(12.0)), (black(), px(24.0))],
5016            ),
5017            "",
5018            &css("linear-gradient(to right, transparent 12px, black 24px)"),
5019        );
5020        same_with(
5021            s().mask_radial([black(), transparent_black()]),
5022            "",
5023            &css("radial-gradient(black, transparent)"),
5024        );
5025        same_with(
5026            s().mask_radial([black(), transparent_black()]).mask_none(),
5027            "",
5028            &css("none"),
5029        );
5030    }
5031
5032    #[test]
5033    fn empty_stops_clear_masks_and_radial_accepts_reactive_stops() {
5034        same_with(
5035            s().mask_linear(deg(90.0), Vec::<ColorStop>::new()),
5036            "",
5037            &|style| {
5038                style
5039                    .set_key(StyleKey::MaskImage, crate::StyleValue::Str("none"))
5040                    .unwrap();
5041            },
5042        );
5043        same_with(s().mask_radial(Vec::<ColorStop>::new()), "", &|style| {
5044            style
5045                .set_key(StyleKey::MaskImage, crate::StyleValue::Str("none"))
5046                .unwrap();
5047        });
5048        // Constructed inside a component in normal use; these static reactive
5049        // wrappers exercise the same accepted type without needing an owner.
5050        let stops = Reactive::Static(vec![ColorStop::from(black()), transparent_black().into()]);
5051        same_with(s().mask_radial(stops), "", &|style| {
5052            style
5053                .set_key(
5054                    StyleKey::MaskImage,
5055                    crate::StyleValue::Str("radial-gradient(black, transparent)"),
5056                )
5057                .unwrap();
5058        });
5059    }
5060
5061    #[test]
5062    fn masks_keep_background_stops_separate() {
5063        let typed = s()
5064            .bg_linear(deg(180.0))
5065            .gradient_from(black())
5066            .gradient_to(crate::color::white())
5067            .mask_linear(deg(90.0), [black(), transparent_black()]);
5068        same_with(typed, "bg-linear-180 from-black to-white", &|style| {
5069            style
5070                .set_key(
5071                    StyleKey::MaskImage,
5072                    crate::StyleValue::Str("linear-gradient(to right, black, transparent)"),
5073                )
5074                .unwrap();
5075        });
5076    }
5077
5078    #[test]
5079    fn keyframe_animations_take_their_own_timing() {
5080        // As TS's `animationName` and its timing keys over no animation.
5081        let timed = |name: &'static str, ms: f32, easing: &'static str| {
5082            move |style: &mut Style| {
5083                use crate::StyleValue;
5084                style
5085                    .set_key(StyleKey::AnimationName, StyleValue::Str(name))
5086                    .unwrap();
5087                style
5088                    .set_key(StyleKey::AnimationDuration, StyleValue::Number(ms))
5089                    .unwrap();
5090                style
5091                    .set_key(StyleKey::AnimationTimingFunction, StyleValue::Str(easing))
5092                    .unwrap();
5093            }
5094        };
5095        same_with(
5096            s().animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0)),
5097            "animate-none",
5098            &timed("spin", 800.0, "linear"),
5099        );
5100        same_with(
5101            s().animation(
5102                KeyframeAnimation::new(Keyframes::Pulse)
5103                    .duration(900.0)
5104                    .easing([0.42, 0.0, 0.58, 1.0]),
5105            ),
5106            "animate-none",
5107            &timed("pulse", 900.0, "ease-in-out"),
5108        );
5109        // The later declaration wins, either way round.
5110        same(
5111            s().animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0))
5112                .animate_ping(),
5113            "animate-ping",
5114        );
5115        same_with(
5116            s().animate_ping()
5117                .animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0)),
5118            "animate-none",
5119            &timed("spin", 800.0, "linear"),
5120        );
5121    }
5122
5123    #[test]
5124    fn keyframe_animations_take_their_frame_rate() {
5125        // As TS's `animationFrameRate` with the animation's other keys.
5126        let capped = |hz: f32| {
5127            move |style: &mut Style| {
5128                use crate::StyleValue;
5129                for (key, value) in [
5130                    (StyleKey::AnimationName, StyleValue::Str("spin")),
5131                    (StyleKey::AnimationDuration, StyleValue::Number(800.0)),
5132                    (StyleKey::AnimationTimingFunction, StyleValue::Str("linear")),
5133                    (StyleKey::AnimationFrameRate, StyleValue::Number(hz)),
5134                ] {
5135                    style.set_key(key, value).unwrap();
5136                }
5137            }
5138        };
5139        same_with(
5140            s().animation(
5141                KeyframeAnimation::new(Keyframes::Spin)
5142                    .duration(800.0)
5143                    .frame_rate(30.0),
5144            ),
5145            "animate-none",
5146            &capped(30.0),
5147        );
5148        let typed = s()
5149            .animation(KeyframeAnimation::new(Keyframes::Spin).frame_rate(24.0))
5150            .lower();
5151        assert!(resolve(&typed, false, 0, 0).contains("frame_rate: Some(24.0)"));
5152    }
5153
5154    #[test]
5155    fn transforms_are_tailwinds() {
5156        same(
5157            s().rotate(deg(12.0)).skew_x(deg(6.0)).scale(0.9),
5158            "rotate-12 skew-x-6 scale-90",
5159        );
5160        same(
5161            s().perspective(px(400.0))
5162                .rotate_y(deg(35.0))
5163                .rotate_x(deg(40.0)),
5164            "perspective-[400px] rotate-y-35 rotate-x-40",
5165        );
5166        same(s().scale_x(1.5).skew_y(deg(-3.0)), "scale-x-150 -skew-y-3");
5167        same(
5168            s().rotate(deg(12.0))
5169                .rotate_x(deg(40.0))
5170                .skew_x(deg(6.0))
5171                .scale(0.9)
5172                .transform_none(),
5173            "rotate-12 rotate-x-40 skew-x-6 scale-90 transform-none",
5174        );
5175        same(
5176            s().translate_x(px(8.0))
5177                .rotate(deg(12.0))
5178                .scale(0.9)
5179                .translate_none()
5180                .rotate_none()
5181                .scale_none(),
5182            "translate-x-2 rotate-12 scale-90 translate-none rotate-none scale-none",
5183        );
5184        same(
5185            s().origin_top_left().backface_hidden(),
5186            "origin-top-left backface-hidden",
5187        );
5188        same(
5189            s().transform_origin(TransformOrigin {
5190                x: px(10.0).into(),
5191                y: relative(0.25),
5192                z: Points::ZERO,
5193            }),
5194            "origin-[10px_25%]",
5195        );
5196    }
5197
5198    #[test]
5199    fn text_is_tailwinds() {
5200        same(
5201            s().underline()
5202                .text_decoration_wavy()
5203                .text_decoration_color(RED.shade(500))
5204                .text_decoration_thickness(px(2.0))
5205                .underline_offset(px(4.0)),
5206            "underline decoration-wavy decoration-red-500 decoration-2 underline-offset-4",
5207        );
5208        same(s().uppercase().tabular_nums(), "uppercase tabular-nums");
5209        same(s().small_caps().oldstyle_nums(), "small-caps oldstyle-nums");
5210        same(s().capitalize().text_justify(), "capitalize text-justify");
5211        same(s().align_baseline(), "align-baseline");
5212        same(s().align_text_top(), "align-text-top");
5213        same(s().align_text_bottom(), "align-text-bottom");
5214        same(s().align_middle(), "align-middle");
5215        same(s().text_pretty(), "text-pretty");
5216        same(s().whitespace_nowrap(), "whitespace-nowrap");
5217        same(s().whitespace_normal(), "whitespace-normal");
5218        // The last of them holds, as the classes'.
5219        same(
5220            s().text_pretty().whitespace_normal(),
5221            "text-pretty whitespace-normal",
5222        );
5223        same(
5224            s().whitespace_nowrap().text_pretty(),
5225            "whitespace-nowrap text-pretty",
5226        );
5227        // Unlike classes, the two lines add up.
5228        let both = s().underline().line_through().lower();
5229        let mut style = Style::default();
5230        let _ = style.set_key(
5231            StyleKey::TextDecorationLine,
5232            crate::StyleValue::Str("underline line-through"),
5233        );
5234        assert_eq!(
5235            resolve(&both, false, 0, 0),
5236            format!("{style:?} {:?}", ClassProps::default())
5237        );
5238        same(
5239            s().underline().line_through().no_underline(),
5240            "no-underline",
5241        );
5242        let rtl = s().writing_direction(WritingDirection::Rtl).lower();
5243        let mut style = Style::default();
5244        let _ = style.set_key(StyleKey::WritingDirection, crate::StyleValue::Str("rtl"));
5245        assert_eq!(
5246            resolve(&rtl, false, 0, 0),
5247            format!("{style:?} {:?}", ClassProps::default())
5248        );
5249    }
5250
5251    #[test]
5252    fn layout_is_tailwinds() {
5253        same(s().grid().grid_cols(3).gap_2(), "grid grid-cols-3 gap-2");
5254        same(s().col_span(2).row_span(2), "col-span-2 row-span-2");
5255        same(s().col_start(2).col_end(-1), "col-start-2 col-end-[-1]");
5256        same(s().flex_grow(2.0).flex_shrink(0.0), "grow-2 shrink-0");
5257        same(
5258            s().grid_rows(2).grid_flow_col(),
5259            "grid-rows-2 grid-flow-col",
5260        );
5261    }
5262
5263    #[test]
5264    fn variants_are_tailwinds() {
5265        same(
5266            s().group_active(|s| s.text_color(VIOLET.shade(600)).translate_x(px(4.0))),
5267            "group-active:text-violet-600 group-active:translate-x-1",
5268        );
5269        same(s().group(), "group");
5270        same(
5271            s().group_named("item")
5272                .group_hover_named("item", |s| s.opacity(0.5)),
5273            "group/item group-hover/item:opacity-50",
5274        );
5275        same(s().dark(|s| s.shadow_none()), "dark:shadow-none");
5276        let mut disabled = s();
5277        disabled.extend_as(Variant::DISABLED, s().opacity(0.4));
5278        same(disabled, "disabled:opacity-40");
5279        // Nested variants: both hold.
5280        let mut nested = s();
5281        nested.extend_as(Variant::ACTIVE, s().dark(|s| s.opacity(0.5)));
5282        same(nested, "dark:active:opacity-50");
5283    }
5284}