Skip to main content

nsh_core/ui/
style.rs

1//! Typed styles of Rust components ([`Styled`]): chained methods
2//! (`.px_4()`, `.rounded_xl()`, `.bg(color)`) recording declarations that
3//! lower into the same rules Tailwind classes compile to, without strings
4//! to parse. Values follow Tailwind's default scales (4pt spacing steps),
5//! independent of the app's Tailwind theme, so a component looks the same
6//! in every app.
7//!
8//! Some changes are native, as with classes: theme colors carry a light
9//! and a dark value ([`AdaptiveColor`]), `.active(|s| …)`, `.hover(…)` and
10//! `.focus(…)` follow the view's interaction states. Others are bindings: a
11//! method given a signal or a closure (`.w(move || px(width.get()))`),
12//! `.style_when(signal, …)`, `.style_with(…)`. What is known when the view
13//! is made (a variant) is plain Rust: `.when(cond, …)`.
14
15use std::{
16    fmt,
17    hash::{Hash, Hasher},
18    rc::Rc,
19    sync::{Arc, LazyLock},
20};
21
22use super::{IntoReactive, Reactive, SharedString};
23use crate::{
24    BlendMode, BoxShadow, Cursor, FontVariant, TransformOrigin, TransitionProps,
25    color::{Hsla, Rgba, transparent_black},
26    effects::{Filter, GradientKind, GradientSize, KeyframeAnimation, Keyframes},
27    geometry::{
28        AbsoluteLength, DefiniteLength, Length, Percentage, Point, Points, REM_SIZE, Radians, Rems,
29        deg, percentage, point, px, relative,
30    },
31    style::{Color, PatchValue, StyleDecl, StyleKey},
32    tailwind::{self, ClassList, Decl, Part, Rule, rank, state},
33    transform::TransformKind,
34};
35
36/// The style value of a length.
37fn length_patch(length: Length) -> PatchValue {
38    match length {
39        Length::Definite(DefiniteLength::Absolute(a)) => {
40            PatchValue::Number(a.to_points(REM_SIZE).0)
41        }
42        Length::Definite(DefiniteLength::Fraction(f)) => {
43            PatchValue::Str(format!("{}%", f.0 * 100.0).into())
44        }
45        Length::Auto => PatchValue::Str("auto".into()),
46    }
47}
48
49/// An absolute length in points (a rem at [`REM_SIZE`]).
50fn points(length: AbsoluteLength) -> f32 {
51    length.to_points(REM_SIZE).0
52}
53
54/// A font weight (100–900).
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub struct FontWeight(pub u16);
57
58impl FontWeight {
59    /// 100.
60    pub const THIN: Self = Self(100);
61    /// 200.
62    pub const EXTRA_LIGHT: Self = Self(200);
63    /// 300.
64    pub const LIGHT: Self = Self(300);
65    /// 400.
66    pub const NORMAL: Self = Self(400);
67    /// 500.
68    pub const MEDIUM: Self = Self(500);
69    /// 600.
70    pub const SEMIBOLD: Self = Self(600);
71    /// 700.
72    pub const BOLD: Self = Self(700);
73    /// 800.
74    pub const EXTRA_BOLD: Self = Self(800);
75    /// 900.
76    pub const BLACK: Self = Self(900);
77}
78
79/// A color for each appearance: the platform switches between them
80/// with nothing running. Theme colors are adaptive; an [`Hsla`] (or anything
81/// that converts to one) is the same in both.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
83pub struct AdaptiveColor {
84    /// In light appearance.
85    pub light: Hsla,
86    /// In dark appearance.
87    pub dark: Hsla,
88}
89
90impl AdaptiveColor {
91    /// Transparent in both.
92    pub const TRANSPARENT: Self = Self {
93        light: transparent_black(),
94        dark: transparent_black(),
95    };
96
97    /// `light` and `dark`.
98    pub fn new(light: impl Into<Hsla>, dark: impl Into<Hsla>) -> Self {
99        Self {
100            light: light.into(),
101            dark: dark.into(),
102        }
103    }
104
105    /// `0xRRGGBB` in light appearance and in dark, opaque (`const`s:
106    /// `AdaptiveColor::rgb(0xffffff, 0x101113)`).
107    pub const fn rgb(light: u32, dark: u32) -> Self {
108        Self {
109            light: crate::color::rgb(light).to_hsla(),
110            dark: crate::color::rgb(dark).to_hsla(),
111        }
112    }
113
114    /// Both with their alpha multiplied by `opacity`.
115    pub fn opacity(self, opacity: f32) -> Self {
116        self.map(|c| c.opacity(opacity))
117    }
118
119    /// Both through `f` (`theme.primary.map(|c| c.darken(0.1))`).
120    pub fn map(self, f: impl Fn(Hsla) -> Hsla) -> Self {
121        Self {
122            light: f(self.light),
123            dark: f(self.dark),
124        }
125    }
126}
127
128impl From<Hsla> for AdaptiveColor {
129    fn from(c: Hsla) -> Self {
130        Self { light: c, dark: c }
131    }
132}
133
134impl From<Rgba> for AdaptiveColor {
135    fn from(c: Rgba) -> Self {
136        Hsla::from(c).into()
137    }
138}
139
140impl From<Color> for AdaptiveColor {
141    fn from(c: Color) -> Self {
142        Hsla::from(c).into()
143    }
144}
145
146/// An `f32` compared and hashed by its bits (styles are cache keys).
147#[derive(Debug, Clone, Copy)]
148pub(crate) struct Bits(f32);
149
150impl PartialEq for Bits {
151    fn eq(&self, other: &Self) -> bool {
152        self.0.to_bits() == other.0.to_bits()
153    }
154}
155
156impl Eq for Bits {}
157
158impl Hash for Bits {
159    fn hash<H: Hasher>(&self, state: &mut H) {
160        self.0.to_bits().hash(state)
161    }
162}
163
164/// When a declaration applies: always, or while the element (or an
165/// ancestor group) is in some states, or in dark appearance. Nested
166/// variants (`.dark(|s| s.group_active(..))`) all have to hold. Small:
167/// every declaration has one (a named group's name is in its
168/// [`StyleRefinement`]).
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
170pub(crate) struct Variant {
171    /// [`state`] bits of the element itself.
172    states: u8,
173    /// [`state`] bits of the nearest ancestor group (none: no group
174    /// condition).
175    group_states: u8,
176    /// That group's name: 0 unnamed, else 1 + its index in
177    /// [`StyleRefinement::names`].
178    group: u8,
179    dark: bool,
180}
181
182impl Variant {
183    /// While hovered.
184    pub(crate) const HOVER: Self = Self::states(state::HOVERED);
185    /// While focused.
186    pub(crate) const FOCUS: Self = Self::states(state::FOCUSED);
187    /// While pressed.
188    pub(crate) const ACTIVE: Self = Self::states(state::PRESSED);
189    /// While disabled.
190    pub(crate) const DISABLED: Self = Self::states(state::DISABLED);
191    /// While selected (set by the core from the accessibility state).
192    pub(crate) const SELECTED: Self = Self::states(state::SELECTED);
193    /// While checked (set by the core from the accessibility state).
194    pub(crate) const CHECKED: Self = Self::states(state::CHECKED);
195    /// While indeterminate (set by the core from the accessibility state).
196    pub(crate) const INDETERMINATE: Self = Self::states(state::INDETERMINATE);
197    /// In dark appearance.
198    const DARK: Self = Self {
199        states: 0,
200        group_states: 0,
201        group: 0,
202        dark: true,
203    };
204
205    const fn states(states: u8) -> Self {
206        Self {
207            states,
208            group_states: 0,
209            group: 0,
210            dark: false,
211        }
212    }
213
214    /// `self` inside `outer`: both must hold.
215    fn within(self, outer: Variant) -> Variant {
216        let (group, group_states) = match (outer.group_states, self.group_states) {
217            (0, _) => (self.group, self.group_states),
218            (o, i) if i != 0 && outer.group == self.group => (outer.group, o | i),
219            (o, _) => (outer.group, o),
220        };
221        Variant {
222            states: self.states | outer.states,
223            group_states,
224            group,
225            dark: self.dark || outer.dark,
226        }
227    }
228
229    /// Tailwind's variant order: the highest of its parts.
230    fn rank(self) -> u16 {
231        let mut r = 0;
232        if self.group_states != 0 {
233            r = rank::GROUP;
234        }
235        for (bit, rank) in [
236            (state::HOVERED, rank::HOVER),
237            (state::FOCUSED, rank::FOCUS),
238            (state::PRESSED, rank::ACTIVE),
239            (state::DISABLED, rank::DISABLED),
240            (state::SELECTED, rank::SELECTED),
241            (state::CHECKED, rank::CHECKED),
242            (state::INDETERMINATE, rank::INDETERMINATE),
243        ] {
244            if self.states & bit != 0 {
245                r = r.max(rank);
246            }
247        }
248        if self.dark {
249            r = r.max(rank::DARK);
250        }
251        r
252    }
253}
254
255/// A color of a property several declarations build (a shadow's, a
256/// ring's, a gradient stop's).
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
258pub(crate) enum ColorPart {
259    Shadow,
260    InsetShadow,
261    TextShadow,
262    Ring,
263    RingOffset,
264    InsetRing,
265    From,
266    Via,
267    To,
268}
269
270impl ColorPart {
271    fn part(self, c: Hsla) -> Part {
272        let c = Color::from(c);
273        // A color with its own alpha replaces the layers' alpha (as
274        // Tailwind's `shadow-black/50`); an opaque one keeps theirs.
275        let own = c.0 & 0xff != 0xff;
276        match self {
277            ColorPart::Shadow => Part::ShadowColor(c, own),
278            ColorPart::InsetShadow => Part::InsetShadowColor(c, own),
279            ColorPart::TextShadow => Part::TextShadowColor(c, own),
280            ColorPart::Ring => Part::RingColor(c),
281            ColorPart::RingOffset => Part::RingOffsetColor(c),
282            ColorPart::InsetRing => Part::InsetRingColor(c),
283            ColorPart::From => Part::From(c),
284            ColorPart::Via => Part::Via(c),
285            ColorPart::To => Part::To(c),
286        }
287    }
288}
289
290/// A gradient's geometry.
291#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
292pub(crate) enum GradientShape {
293    /// Along a line at an angle (radians, 0 up, a quarter turn right).
294    Linear(Bits),
295    /// Towards a corner.
296    Corner { right: bool, bottom: bool },
297    /// An ellipse from the center to the farthest corner.
298    Radial,
299    /// Around the center, from an angle (radians, 0 up).
300    Conic(Bits),
301}
302
303/// A filter function (`Opacity` only of backdrops: a view's own opacity
304/// is [`Styled::opacity`]).
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
306pub(crate) enum FilterFn {
307    Blur,
308    Brightness,
309    Contrast,
310    Grayscale,
311    HueRotate,
312    Invert,
313    Opacity,
314    Saturate,
315    Sepia,
316}
317
318impl FilterFn {
319    /// Its slot in the composed list (CSS's order, as Tailwind's
320    /// utilities), and the filter.
321    fn part(self, backdrop: bool, amount: f32) -> Part {
322        let (slot, filter) = match self {
323            FilterFn::Blur => (0, Filter::Blur(crate::geometry::px(amount))),
324            FilterFn::Brightness => (1, Filter::Brightness(amount)),
325            FilterFn::Contrast => (2, Filter::Contrast(amount)),
326            FilterFn::Grayscale => (3, Filter::Grayscale(amount)),
327            FilterFn::HueRotate => (4, Filter::HueRotate(crate::geometry::deg(amount))),
328            FilterFn::Invert => (5, Filter::Invert(amount)),
329            FilterFn::Opacity => (6, Filter::Opacity(amount)),
330            FilterFn::Saturate => (6 + u8::from(backdrop), Filter::Saturate(amount)),
331            FilterFn::Sepia => (7 + u8::from(backdrop), Filter::Sepia(amount)),
332        };
333        Part::Filter {
334            backdrop,
335            slot,
336            filter: Some(filter),
337        }
338    }
339}
340
341/// Layers of [`BoxShadow`]s, compared and hashed by their bits.
342#[derive(Debug, Clone)]
343pub(crate) struct Layers(Arc<[BoxShadow]>);
344
345impl Layers {
346    fn bits(&self) -> impl Iterator<Item = (u32, u32, u32, u32, u32, bool)> + '_ {
347        self.0.iter().map(|l| {
348            (
349                l.offset_x.0.to_bits(),
350                l.offset_y.0.to_bits(),
351                l.blur.0.to_bits(),
352                l.spread.0.to_bits(),
353                l.color.0,
354                l.inset,
355            )
356        })
357    }
358}
359
360impl PartialEq for Layers {
361    fn eq(&self, other: &Self) -> bool {
362        self.0.len() == other.0.len() && self.bits().eq(other.bits())
363    }
364}
365
366impl Eq for Layers {}
367
368impl Hash for Layers {
369    fn hash<H: Hasher>(&self, state: &mut H) {
370        for l in self.bits() {
371            l.hash(state);
372        }
373    }
374}
375
376/// `underline` in [`Declaration::Decoration`].
377const UNDERLINE: u8 = 1;
378/// `line-through` in [`Declaration::Decoration`].
379const LINE_THROUGH: u8 = 2;
380
381/// One typed declaration.
382#[derive(Debug, Clone, PartialEq, Eq, Hash)]
383pub(crate) enum Declaration {
384    Number(StyleKey, Bits),
385    Length(StyleKey, Length),
386    Keyword(StyleKey, &'static str),
387    Str(StyleKey, SharedString),
388    Color(StyleKey, AdaptiveColor),
389    /// Tailwind's `text-*` size and line height.
390    TextPreset(&'static str),
391    /// Tailwind's `shadow-*` (`"none"` removes it).
392    Shadow(&'static str),
393    /// Tailwind's `inset-shadow-*` (`"none"` removes it).
394    InsetShadow(&'static str),
395    /// Tailwind's `text-shadow-*` (`"none"` removes it).
396    TextShadow(&'static str),
397    /// Box shadows of the element's own.
398    Shadows(Layers),
399    PartColor(ColorPart, AdaptiveColor),
400    Ring(Bits),
401    RingOffset(Bits),
402    RingInset,
403    InsetRing(Bits),
404    /// `shadowOffset` (React Native's shadow).
405    ShadowOffset(Bits, Bits),
406    TextShadowOffset(Bits, Bits),
407    /// One step of the transform the styles compose (CSS's order:
408    /// translate, rotate, scale, then the 3D rotations and skews).
409    Transform(TransformKind, Bits),
410    TransformNone,
411    /// `transformOrigin` at points or fractions (`true`) of the size.
412    Origin([(bool, Bits); 2]),
413    Gradient(GradientShape),
414    GradientNone,
415    /// The position of the gradient's `from` (0), `via` (1) or `to` (2)
416    /// color, a fraction of its length.
417    StopPosition(u8, Bits),
418    Filter(bool, FilterFn, Bits),
419    FilterNone(bool),
420    FontVariant {
421        set: u8,
422        clear: u8,
423    },
424    /// [`UNDERLINE`] and [`LINE_THROUGH`] add up; 0 removes both.
425    Decoration(u8),
426    /// [`TransitionProps`] bits.
427    Transition(u8),
428    TransitionNone,
429    Duration(Bits),
430    Delay(Bits),
431    Ease([Bits; 4]),
432    /// Tailwind's `ease-*`.
433    EasePreset(&'static str),
434    /// A keyframe animation (`None`: none).
435    Animate(Option<u8>),
436    /// A keyframe animation with its own timing: the keyframes' index,
437    /// duration, delay, easing and iterations (`None`: forever).
438    Animation(u8, Bits, Bits, [Bits; 4], Option<u32>),
439    /// `repeat(n, minmax(0, 1fr))` tracks.
440    Tracks(StyleKey, u16),
441    /// `span n / span n`.
442    Span(StyleKey, u16),
443    /// The element is a group (`""`: unnamed): `group_*` styles inside
444    /// follow its states.
445    Group(&'static str),
446}
447
448/// Tailwind's default theme: the presets typed styles name.
449static PRESETS: LazyLock<tailwind::Theme> = LazyLock::new(tailwind::Theme::default);
450
451/// A color enters styles packed (`crate::color`'s rounding).
452fn color_patch(c: Hsla) -> PatchValue {
453    PatchValue::Str(format!("#{:08x}", Color::from(c).0).into())
454}
455
456fn shadow_preset(layers: Option<&Vec<BoxShadow>>) -> Arc<[BoxShadow]> {
457    layers.map_or_else(|| Arc::from([]), |l| Arc::from(l.as_slice()))
458}
459
460/// The keyframes of [`Declaration::Animate`].
461const KEYFRAMES: [Keyframes; 4] = [
462    Keyframes::Spin,
463    Keyframes::Ping,
464    Keyframes::Pulse,
465    Keyframes::Bounce,
466];
467
468impl Declaration {
469    fn lower(&self, out: &mut Vec<Decl>) {
470        let part = |out: &mut Vec<Decl>, p: Part| out.push(Decl::Part(p));
471        match self {
472            Declaration::Number(key, n) => out.push(Decl::Set(*key, PatchValue::Number(n.0))),
473            Declaration::Length(key, l) => out.push(Decl::Set(*key, length_patch(*l))),
474            Declaration::Keyword(key, k) => out.push(Decl::Set(*key, PatchValue::Str((*k).into()))),
475            Declaration::Str(key, s) => {
476                out.push(Decl::Set(*key, PatchValue::Str(s.as_str().into())))
477            }
478            Declaration::Color(key, c) => out.push(if c.light == c.dark {
479                Decl::Set(*key, color_patch(c.light))
480            } else {
481                Decl::Adaptive(*key, [color_patch(c.light), color_patch(c.dark)])
482            }),
483            Declaration::TextPreset(name) => {
484                if let Some(&(size, line)) = PRESETS.text.get(*name) {
485                    out.push(Decl::Set(StyleKey::FontSize, PatchValue::Number(size)));
486                    if let Some(m) = line {
487                        out.push(Decl::Set(
488                            StyleKey::LineHeight,
489                            PatchValue::Str(m.to_string().into()),
490                        ));
491                    }
492                }
493            }
494            Declaration::Shadow(name) => {
495                part(out, Part::Shadow(shadow_preset(PRESETS.shadows.get(*name))))
496            }
497            Declaration::InsetShadow(name) => part(
498                out,
499                Part::InsetShadow(shadow_preset(PRESETS.inset_shadows.get(*name))),
500            ),
501            Declaration::TextShadow(name) => {
502                let layers = PRESETS.text_shadows.get(*name);
503                part(
504                    out,
505                    Part::TextShadow(
506                        layers.map_or_else(|| Arc::from([]), |l| Arc::from(l.as_slice())),
507                    ),
508                )
509            }
510            Declaration::Shadows(layers) => part(out, Part::Shadow(layers.0.clone())),
511            Declaration::PartColor(which, c) => out.push(if c.light == c.dark {
512                Decl::Part(which.part(c.light))
513            } else {
514                Decl::AdaptivePart(Box::new([which.part(c.light), which.part(c.dark)]))
515            }),
516            Declaration::Ring(w) => part(out, Part::Ring(w.0)),
517            Declaration::RingOffset(w) => part(out, Part::RingOffset(w.0)),
518            Declaration::RingInset => part(out, Part::RingInset),
519            Declaration::InsetRing(w) => part(out, Part::InsetRing(w.0)),
520            Declaration::ShadowOffset(x, y) => out.push(Decl::Style(StyleDecl::ShadowOffset(
521                Some(point(px(x.0), px(y.0))),
522            ))),
523            Declaration::TextShadowOffset(x, y) => out.push(Decl::Style(
524                StyleDecl::TextShadowOffset(Some(point(px(x.0), px(y.0)))),
525            )),
526            Declaration::Transform(kind, v) => {
527                let v = v.0;
528                let parts: &[Part] = match kind {
529                    TransformKind::Scale => &[Part::ScaleX(v), Part::ScaleY(v)],
530                    TransformKind::ScaleX => &[Part::ScaleX(v)],
531                    TransformKind::ScaleY => &[Part::ScaleY(v)],
532                    TransformKind::TranslateX => &[Part::TranslateX(tailwind::Len::Points(v))],
533                    TransformKind::TranslateY => &[Part::TranslateY(tailwind::Len::Points(v))],
534                    TransformKind::TranslateXFraction => {
535                        &[Part::TranslateX(tailwind::Len::Fraction(v))]
536                    }
537                    TransformKind::TranslateYFraction => {
538                        &[Part::TranslateY(tailwind::Len::Fraction(v))]
539                    }
540                    TransformKind::Rotate => &[Part::Rotate(v)],
541                    TransformKind::RotateX => &[Part::RotateX(v)],
542                    TransformKind::RotateY => &[Part::RotateY(v)],
543                    TransformKind::SkewX => &[Part::SkewX(v)],
544                    TransformKind::SkewY => &[Part::SkewY(v)],
545                    TransformKind::Perspective => &[Part::Perspective(v)],
546                };
547                out.extend(parts.iter().cloned().map(Decl::Part));
548            }
549            Declaration::TransformNone => part(out, Part::TransformNone),
550            Declaration::Origin(axes) => {
551                let [x, y] = axes.map(|(fraction, v)| {
552                    if fraction {
553                        format!("{}%", v.0 * 100.0)
554                    } else {
555                        format!("{}px", v.0)
556                    }
557                });
558                out.push(Decl::Set(
559                    StyleKey::TransformOrigin,
560                    PatchValue::Str(format!("{x} {y}").into()),
561                ));
562            }
563            Declaration::Gradient(shape) => part(
564                out,
565                Part::Gradient(match *shape {
566                    GradientShape::Linear(angle) => GradientKind::Linear {
567                        angle: Radians(angle.0),
568                    },
569                    GradientShape::Corner { right, bottom } => {
570                        GradientKind::LinearCorner { right, bottom }
571                    }
572                    GradientShape::Radial => GradientKind::Radial {
573                        circle: false,
574                        size: GradientSize::FarthestCorner,
575                        x: percentage(0.5),
576                        y: percentage(0.5),
577                    },
578                    GradientShape::Conic(from) => GradientKind::Conic {
579                        from: Radians(from.0),
580                        x: percentage(0.5),
581                        y: percentage(0.5),
582                    },
583                }),
584            ),
585            Declaration::GradientNone => part(out, Part::GradientNone),
586            Declaration::StopPosition(i, at) => part(
587                out,
588                match i {
589                    0 => Part::FromPos(at.0),
590                    1 => Part::ViaPos(at.0),
591                    _ => Part::ToPos(at.0),
592                },
593            ),
594            Declaration::Filter(backdrop, f, amount) => part(out, f.part(*backdrop, amount.0)),
595            Declaration::FilterNone(backdrop) => part(
596                out,
597                Part::FilterNone {
598                    backdrop: *backdrop,
599                },
600            ),
601            Declaration::FontVariant { set, clear } => part(
602                out,
603                Part::FontVariant {
604                    set: *set,
605                    clear: *clear,
606                },
607            ),
608            Declaration::Decoration(bits) => out.push(Decl::Set(
609                StyleKey::TextDecorationLine,
610                PatchValue::Str(
611                    match *bits {
612                        0 => "none",
613                        UNDERLINE => "underline",
614                        LINE_THROUGH => "line-through",
615                        _ => "underline line-through",
616                    }
617                    .into(),
618                ),
619            )),
620            Declaration::Transition(props) => part(out, Part::TransitionProps(*props)),
621            Declaration::TransitionNone => part(out, Part::TransitionNone),
622            Declaration::Duration(ms) => part(out, Part::Duration(ms.0)),
623            Declaration::Delay(ms) => part(out, Part::Delay(ms.0)),
624            Declaration::Ease(curve) => part(out, Part::Ease(curve.map(|b| b.0))),
625            Declaration::EasePreset(name) => {
626                if let Some(curve) = PRESETS.ease.get(*name) {
627                    part(out, Part::Ease(*curve));
628                }
629            }
630            Declaration::Animate(k) => part(out, Part::Animate(k.map(|i| KEYFRAMES[i as usize]))),
631            Declaration::Animation(k, duration, delay, easing, iterations) => part(
632                out,
633                Part::Animation(KeyframeAnimation {
634                    keyframes: KEYFRAMES[*k as usize],
635                    duration: duration.0,
636                    delay: delay.0,
637                    easing: easing.map(|b| b.0),
638                    iterations: *iterations,
639                }),
640            ),
641            Declaration::Tracks(key, n) => out.push(Decl::Set(
642                *key,
643                PatchValue::Str(format!("repeat({n}, minmax(0, 1fr))").into()),
644            )),
645            Declaration::Span(key, n) => out.push(Decl::Set(
646                *key,
647                PatchValue::Str(format!("span {n} / span {n}").into()),
648            )),
649            // A property of the class list, not a declaration.
650            Declaration::Group(_) => {}
651        }
652    }
653}
654
655type Entries = Vec<(Variant, Declaration)>;
656
657crate::static_reactive!(AdaptiveColor: AdaptiveColor, Hsla, Rgba, Color);
658crate::static_reactive!(Length: Length, Points, Rems, AbsoluteLength, DefiniteLength, Percentage);
659crate::static_reactive!(DefiniteLength: Points, Rems, AbsoluteLength, DefiniteLength, Percentage);
660crate::static_reactive!(AbsoluteLength: Points, Rems, AbsoluteLength);
661crate::static_reactive!(Points: Points);
662crate::static_reactive!(Radians: Radians);
663crate::static_reactive!(Percentage: Percentage);
664crate::static_reactive!(u16: u16);
665crate::static_reactive!(i16: i16);
666
667/// A bound part of a style: it adds its declarations to a style, reading
668/// the signals it binds (run again when they change).
669pub(crate) type BoundStyle = Rc<dyn Fn(&mut StyleRefinement)>;
670
671/// An element's styles, in order (later declarations win). Built by the
672/// [`Styled`] methods; `.active(|s| …)` and the like hand a fresh one to
673/// their closure. Values given as signals or closures are bound parts,
674/// added after the static declarations ([`StyleRefinement::resolved`]).
675#[derive(Clone, Default)]
676pub struct StyleRefinement {
677    entries: Entries,
678    /// The names of the groups its variants follow ([`Variant::group`]).
679    names: Vec<&'static str>,
680    bound: Vec<BoundStyle>,
681}
682
683impl fmt::Debug for StyleRefinement {
684    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
685        f.debug_struct("StyleRefinement")
686            .field("entries", &self.entries)
687            .field("names", &self.names)
688            .field("bound", &self.bound.len())
689            .finish()
690    }
691}
692
693/// Equal static declarations and the same bound parts.
694impl PartialEq for StyleRefinement {
695    fn eq(&self, other: &Self) -> bool {
696        self.entries == other.entries
697            && self.names == other.names
698            && self.bound.len() == other.bound.len()
699            && self
700                .bound
701                .iter()
702                .zip(&other.bound)
703                .all(|(a, b)| Rc::ptr_eq(a, b))
704    }
705}
706
707impl Eq for StyleRefinement {}
708
709/// The static declarations (a resolved style, [`StyleRefinement::resolved`],
710/// has no bound parts).
711impl Hash for StyleRefinement {
712    fn hash<H: Hasher>(&self, state: &mut H) {
713        self.entries.hash(state);
714        self.names.hash(state);
715    }
716}
717
718impl StyleRefinement {
719    /// Applies `value` with `apply`: now when it is static, else as a bound
720    /// part.
721    pub(crate) fn bind_value<T: 'static>(
722        &mut self,
723        value: impl IntoReactive<T>,
724        apply: impl Fn(&mut StyleRefinement, T) + 'static,
725    ) {
726        match value.into_reactive() {
727            Reactive::Static(v) => apply(self, v),
728            Reactive::Bound(f) => self.bound.push(Rc::new(move |s| apply(s, f()))),
729        }
730    }
731
732    /// Adds a bound part.
733    pub(crate) fn bind(&mut self, part: impl Fn(&mut StyleRefinement) + 'static) {
734        self.bound.push(Rc::new(part));
735    }
736
737    /// Whether it has bound parts.
738    pub(crate) fn is_bound(&self) -> bool {
739        !self.bound.is_empty()
740    }
741
742    /// Its static declarations alone.
743    pub(crate) fn static_part(&self) -> StyleRefinement {
744        StyleRefinement {
745            entries: self.entries.clone(),
746            names: self.names.clone(),
747            bound: Vec::new(),
748        }
749    }
750
751    /// The style now: the static declarations, then the bound parts' (read
752    /// in the running computation, which subscribes to them).
753    pub(crate) fn resolved(&self) -> StyleRefinement {
754        let mut out = StyleRefinement {
755            entries: self.entries.clone(),
756            names: self.names.clone(),
757            bound: Vec::new(),
758        };
759        for part in &self.bound {
760            part(&mut out);
761        }
762        out
763    }
764
765    pub(crate) fn push(&mut self, decl: Declaration) {
766        // Elements take several declarations: no regrowth for the first.
767        if self.entries.capacity() == 0 {
768            self.entries.reserve(8);
769        }
770        self.entries.push((Variant::default(), decl));
771    }
772
773    pub(crate) fn lengths(&mut self, keys: &[StyleKey], length: impl Into<Length>) {
774        let length = length.into();
775        for key in keys {
776            self.push(Declaration::Length(*key, length));
777        }
778    }
779
780    pub(crate) fn number(&mut self, key: StyleKey, n: f32) {
781        self.push(Declaration::Number(key, Bits(n)));
782    }
783
784    pub(crate) fn numbers(&mut self, keys: &[StyleKey], n: f32) {
785        for key in keys {
786            self.number(*key, n);
787        }
788    }
789
790    pub(crate) fn keyword(&mut self, key: StyleKey, k: &'static str) {
791        self.push(Declaration::Keyword(key, k));
792    }
793
794    pub(crate) fn color(&mut self, keys: &[StyleKey], color: AdaptiveColor) {
795        for key in keys {
796            self.push(Declaration::Color(*key, color));
797        }
798    }
799
800    /// `other`'s declarations, applying while in `variant` (and in their
801    /// own).
802    pub(crate) fn extend_as(&mut self, variant: Variant, other: StyleRefinement) {
803        for (mut v, d) in other.entries {
804            if v.group != 0 {
805                v.group = self.name(other.names[v.group as usize - 1]);
806            }
807            self.entries.push((v.within(variant), d));
808        }
809        // Bound parts apply in the variant too.
810        for part in other.bound {
811            self.bound.push(Rc::new(move |s| {
812                let mut inner = StyleRefinement::default();
813                part(&mut inner);
814                s.extend_as(variant, inner);
815            }));
816        }
817    }
818
819    /// [`Variant::group`] of the group `name`.
820    fn name(&mut self, name: &'static str) -> u8 {
821        if name.is_empty() {
822            return 0;
823        }
824        let at = match self.names.iter().position(|n| *n == name) {
825            Some(at) => at,
826            None => {
827                self.names.push(name);
828                self.names.len() - 1
829            }
830        };
831        u8::try_from(at + 1).expect("fewer than 255 group names")
832    }
833
834    /// No declarations, and no bound parts.
835    pub fn is_empty(&self) -> bool {
836        self.entries.is_empty() && self.bound.is_empty()
837    }
838
839    /// The rules, as Tailwind classes compile to: one per variant, in
840    /// Tailwind's variant order.
841    pub(crate) fn lower(&self) -> ClassList {
842        let mut variants: Vec<Variant> = Vec::new();
843        let mut groups: Vec<Box<str>> = Vec::new();
844        for (v, d) in &self.entries {
845            if let Declaration::Group(name) = d {
846                if !groups.iter().any(|g| **g == **name) {
847                    groups.push((*name).into());
848                }
849            } else if !variants.contains(v) {
850                variants.push(*v);
851            }
852        }
853        let mut rules = Vec::with_capacity(variants.len());
854        for variant in variants {
855            let mut decls = Vec::new();
856            // Decorations add up within a variant (`.underline()
857            // .line_through()` draws both).
858            let mut decoration = 0;
859            for (v, d) in &self.entries {
860                if *v != variant {
861                    continue;
862                }
863                if let Declaration::Decoration(bits) = d {
864                    decoration = if *bits == 0 { 0 } else { decoration | bits };
865                    Declaration::Decoration(decoration).lower(&mut decls);
866                } else {
867                    d.lower(&mut decls);
868                }
869            }
870            if !decls.is_empty() {
871                let group = (variant.group_states != 0).then(|| {
872                    let name = match variant.group {
873                        0 => "",
874                        g => self.names[g as usize - 1],
875                    };
876                    (name, variant.group_states)
877                });
878                rules.push(Rule::with(
879                    variant.states,
880                    group,
881                    variant.dark,
882                    variant.rank(),
883                    decls,
884                ));
885            }
886        }
887        ClassList::from_rules(rules, groups)
888    }
889}
890
891/// `s` with number / letter forms `set` on and `clear` off.
892fn font_variant<S: Styled>(mut s: S, set: u8, clear: u8) -> S {
893    s.style().push(Declaration::FontVariant { set, clear });
894    s
895}
896
897/// A text's base direction (`writingDirection`).
898#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
899pub enum WritingDirection {
900    /// From the content (the default).
901    #[default]
902    Auto,
903    /// Left to right.
904    Ltr,
905    /// Right to left.
906    Rtl,
907}
908
909/// The layout direction of a view and its subtree (`direction`).
910#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
911pub enum LayoutDirection {
912    /// Its parent's (the default): the surface's follows the user's
913    /// language.
914    #[default]
915    Inherit,
916    /// Left to right.
917    Ltr,
918    /// Right to left: rows run from the right, and left / right
919    /// properties mean start and end.
920    Rtl,
921}
922crate::static_reactive!(LayoutDirection: LayoutDirection);
923
924/// The shape of rounded corners (`borderCurve`).
925#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
926pub enum BorderCurve {
927    /// Quarter circles (the default).
928    #[default]
929    Circular,
930    /// Curvature easing into the edges (iOS app icons); pills stay pills.
931    Continuous,
932}
933
934/// Styling methods, named after the utility classes they match (`.p_4()` is
935/// `p-4`). Implemented by the elements and by [`StyleRefinement`] (in
936/// `.active(|s| …)`).
937pub trait Styled: Sized {
938    /// The styles being built.
939    fn style(&mut self) -> &mut StyleRefinement;
940
941    nsh_macros::style_helpers! {
942        /// Padding on all sides
943        p => [Padding],
944        /// Horizontal padding
945        px => [PaddingHorizontal],
946        /// Vertical padding
947        py => [PaddingVertical],
948        /// Top padding
949        pt => [PaddingTop],
950        /// Right padding
951        pr => [PaddingRight],
952        /// Bottom padding
953        pb => [PaddingBottom],
954        /// Left padding
955        pl => [PaddingLeft],
956        /// Leading padding (left in left-to-right layouts)
957        ps => [PaddingStart],
958        /// Trailing padding
959        pe => [PaddingEnd],
960        /// Margin on all sides
961        m => [Margin],
962        /// Horizontal margin
963        mx => [MarginHorizontal],
964        /// Vertical margin
965        my => [MarginVertical],
966        /// Top margin
967        mt => [MarginTop],
968        /// Right margin
969        mr => [MarginRight],
970        /// Bottom margin
971        mb => [MarginBottom],
972        /// Left margin
973        ml => [MarginLeft],
974        /// Leading margin
975        ms => [MarginStart],
976        /// Trailing margin
977        me => [MarginEnd],
978        /// Space between children
979        gap => [Gap],
980        /// Space between columns
981        gap_x => [ColumnGap],
982        /// Space between rows
983        gap_y => [RowGap],
984        /// Width
985        w => [Width],
986        /// Height
987        h => [Height],
988        /// Width and height
989        size => [Width, Height],
990        /// Minimum width
991        min_w => [MinWidth],
992        /// Minimum height
993        min_h => [MinHeight],
994        /// Maximum width
995        max_w => [MaxWidth],
996        /// Maximum height
997        max_h => [MaxHeight],
998        /// Distance from the parent's top edge (absolute layout)
999        top => [Top],
1000        /// Distance from the parent's right edge
1001        right => [Right],
1002        /// Distance from the parent's bottom edge
1003        bottom => [Bottom],
1004        /// Distance from the parent's left edge
1005        left => [Left],
1006        /// Distance from every edge of the parent
1007        inset => [Top, Right, Bottom, Left],
1008        /// The flex basis
1009        basis => [FlexBasis],
1010    }
1011
1012    // Layout.
1013
1014    /// Flex layout (the default).
1015    fn flex(mut self) -> Self {
1016        self.style().keyword(StyleKey::Display, "flex");
1017        self
1018    }
1019
1020    /// Grid layout.
1021    fn grid(mut self) -> Self {
1022        self.style().keyword(StyleKey::Display, "grid");
1023        self
1024    }
1025
1026    /// `count` equal grid columns (Tailwind's `grid-cols-3`).
1027    fn grid_cols(mut self, count: impl IntoReactive<u16>) -> Self {
1028        self.style().bind_value(count, |s, count: u16| {
1029            s.push(Declaration::Tracks(StyleKey::GridTemplateColumns, count));
1030        });
1031        self
1032    }
1033
1034    /// `count` equal grid rows.
1035    fn grid_rows(mut self, count: impl IntoReactive<u16>) -> Self {
1036        self.style().bind_value(count, |s, count: u16| {
1037            s.push(Declaration::Tracks(StyleKey::GridTemplateRows, count));
1038        });
1039        self
1040    }
1041
1042    /// The grid's columns as CSS tracks (`"200px 1fr"`, `"repeat(auto-fill,
1043    /// minmax(80px, 1fr))"`, line names).
1044    fn grid_template_columns(mut self, tracks: impl IntoReactive<SharedString>) -> Self {
1045        self.style().bind_value(tracks, |s, tracks: SharedString| {
1046            s.push(Declaration::Str(StyleKey::GridTemplateColumns, tracks));
1047        });
1048        self
1049    }
1050
1051    /// The grid's rows as CSS tracks.
1052    fn grid_template_rows(mut self, tracks: impl IntoReactive<SharedString>) -> Self {
1053        self.style().bind_value(tracks, |s, tracks: SharedString| {
1054            s.push(Declaration::Str(StyleKey::GridTemplateRows, tracks));
1055        });
1056        self
1057    }
1058
1059    /// Items fill the grid column by column.
1060    fn grid_flow_col(mut self) -> Self {
1061        self.style().keyword(StyleKey::GridAutoFlow, "column");
1062        self
1063    }
1064
1065    /// Items fill the grid's holes left by larger ones.
1066    fn grid_flow_dense(mut self) -> Self {
1067        self.style().keyword(StyleKey::GridAutoFlow, "row dense");
1068        self
1069    }
1070
1071    /// In the grid, `count` columns wide.
1072    fn col_span(mut self, count: impl IntoReactive<u16>) -> Self {
1073        self.style().bind_value(count, |s, count: u16| {
1074            s.push(Declaration::Span(StyleKey::GridColumn, count));
1075        });
1076        self
1077    }
1078
1079    /// In the grid, `count` rows high.
1080    fn row_span(mut self, count: impl IntoReactive<u16>) -> Self {
1081        self.style().bind_value(count, |s, count: u16| {
1082            s.push(Declaration::Span(StyleKey::GridRow, count));
1083        });
1084        self
1085    }
1086
1087    /// Across every column of the grid.
1088    fn col_span_full(mut self) -> Self {
1089        self.style().keyword(StyleKey::GridColumn, "1 / -1");
1090        self
1091    }
1092
1093    /// Across every row of the grid.
1094    fn row_span_full(mut self) -> Self {
1095        self.style().keyword(StyleKey::GridRow, "1 / -1");
1096        self
1097    }
1098
1099    /// Starts at column line `line` (1 is the first; negative from the
1100    /// end).
1101    fn col_start(mut self, line: impl IntoReactive<i16>) -> Self {
1102        self.style().bind_value(line, |s, line: i16| {
1103            s.number(StyleKey::GridColumnStart, f32::from(line));
1104        });
1105        self
1106    }
1107
1108    /// Ends at column line `line`.
1109    fn col_end(mut self, line: impl IntoReactive<i16>) -> Self {
1110        self.style().bind_value(line, |s, line: i16| {
1111            s.number(StyleKey::GridColumnEnd, f32::from(line));
1112        });
1113        self
1114    }
1115
1116    /// Starts at row line `line`.
1117    fn row_start(mut self, line: impl IntoReactive<i16>) -> Self {
1118        self.style().bind_value(line, |s, line: i16| {
1119            s.number(StyleKey::GridRowStart, f32::from(line));
1120        });
1121        self
1122    }
1123
1124    /// Ends at row line `line`.
1125    fn row_end(mut self, line: impl IntoReactive<i16>) -> Self {
1126        self.style().bind_value(line, |s, line: i16| {
1127            s.number(StyleKey::GridRowEnd, f32::from(line));
1128        });
1129        self
1130    }
1131
1132    /// Not laid out nor shown.
1133    fn hidden(mut self) -> Self {
1134        self.style().keyword(StyleKey::Display, "none");
1135        self
1136    }
1137
1138    /// Children in a row.
1139    fn flex_row(mut self) -> Self {
1140        self.style().keyword(StyleKey::FlexDirection, "row");
1141        self
1142    }
1143
1144    /// Children in a row, last first.
1145    fn flex_row_reverse(mut self) -> Self {
1146        self.style().keyword(StyleKey::FlexDirection, "row-reverse");
1147        self
1148    }
1149
1150    /// Children in a column (the default).
1151    fn flex_col(mut self) -> Self {
1152        self.style().keyword(StyleKey::FlexDirection, "column");
1153        self
1154    }
1155
1156    /// Children in a column, last first.
1157    fn flex_col_reverse(mut self) -> Self {
1158        self.style()
1159            .keyword(StyleKey::FlexDirection, "column-reverse");
1160        self
1161    }
1162
1163    /// Children wrap onto new lines.
1164    fn flex_wrap(mut self) -> Self {
1165        self.style().keyword(StyleKey::FlexWrap, "wrap");
1166        self
1167    }
1168
1169    /// Grows and shrinks, ignoring its own size (`flex: 1 1 0`).
1170    fn flex_1(mut self) -> Self {
1171        let s = self.style();
1172        s.number(StyleKey::FlexGrow, 1.0);
1173        s.number(StyleKey::FlexShrink, 1.0);
1174        s.lengths(&[StyleKey::FlexBasis], px(0.0));
1175        self
1176    }
1177
1178    /// Grows and shrinks from its own size (`flex: 1 1 auto`).
1179    fn flex_auto(mut self) -> Self {
1180        let s = self.style();
1181        s.number(StyleKey::FlexGrow, 1.0);
1182        s.number(StyleKey::FlexShrink, 1.0);
1183        s.lengths(&[StyleKey::FlexBasis], Length::Auto);
1184        self
1185    }
1186
1187    /// Neither grows nor shrinks.
1188    fn flex_none(mut self) -> Self {
1189        let s = self.style();
1190        s.number(StyleKey::FlexGrow, 0.0);
1191        s.number(StyleKey::FlexShrink, 0.0);
1192        self
1193    }
1194
1195    /// Takes free space, `factor` times as much as a sibling growing by 1
1196    /// (`flex-grow`; Tailwind's `grow-*`).
1197    fn flex_grow(mut self, factor: impl IntoReactive<f32>) -> Self {
1198        self.style().bind_value(factor, |s, factor: f32| {
1199            s.number(StyleKey::FlexGrow, factor);
1200        });
1201        self
1202    }
1203
1204    /// Gives up space when there is too little, `factor` times as much as
1205    /// a sibling shrinking by 1 (`flex-shrink`).
1206    fn flex_shrink(mut self, factor: impl IntoReactive<f32>) -> Self {
1207        self.style().bind_value(factor, |s, factor: f32| {
1208            s.number(StyleKey::FlexShrink, factor);
1209        });
1210        self
1211    }
1212
1213    /// Never shrinks.
1214    fn flex_shrink_0(mut self) -> Self {
1215        self.style().number(StyleKey::FlexShrink, 0.0);
1216        self
1217    }
1218
1219    /// Children at the cross axis' start.
1220    fn items_start(mut self) -> Self {
1221        self.style().keyword(StyleKey::AlignItems, "flex-start");
1222        self
1223    }
1224
1225    /// Children centered on the cross axis.
1226    fn items_center(mut self) -> Self {
1227        self.style().keyword(StyleKey::AlignItems, "center");
1228        self
1229    }
1230
1231    /// Children at the cross axis' end.
1232    fn items_end(mut self) -> Self {
1233        self.style().keyword(StyleKey::AlignItems, "flex-end");
1234        self
1235    }
1236
1237    /// Children stretched across (the default).
1238    fn items_stretch(mut self) -> Self {
1239        self.style().keyword(StyleKey::AlignItems, "stretch");
1240        self
1241    }
1242
1243    /// Children aligned on their text baseline.
1244    fn items_baseline(mut self) -> Self {
1245        self.style().keyword(StyleKey::AlignItems, "baseline");
1246        self
1247    }
1248
1249    /// Children at the main axis' start (the default).
1250    fn justify_start(mut self) -> Self {
1251        self.style().keyword(StyleKey::JustifyContent, "flex-start");
1252        self
1253    }
1254
1255    /// Children centered on the main axis.
1256    fn justify_center(mut self) -> Self {
1257        self.style().keyword(StyleKey::JustifyContent, "center");
1258        self
1259    }
1260
1261    /// Children at the main axis' end.
1262    fn justify_end(mut self) -> Self {
1263        self.style().keyword(StyleKey::JustifyContent, "flex-end");
1264        self
1265    }
1266
1267    /// Free space between children.
1268    fn justify_between(mut self) -> Self {
1269        self.style()
1270            .keyword(StyleKey::JustifyContent, "space-between");
1271        self
1272    }
1273
1274    /// Free space around children.
1275    fn justify_around(mut self) -> Self {
1276        self.style()
1277            .keyword(StyleKey::JustifyContent, "space-around");
1278        self
1279    }
1280
1281    /// Free space evenly between and around children.
1282    fn justify_evenly(mut self) -> Self {
1283        self.style()
1284            .keyword(StyleKey::JustifyContent, "space-evenly");
1285        self
1286    }
1287
1288    /// Itself at the cross axis' start.
1289    fn self_start(mut self) -> Self {
1290        self.style().keyword(StyleKey::AlignSelf, "flex-start");
1291        self
1292    }
1293
1294    /// Itself centered on the cross axis.
1295    fn self_center(mut self) -> Self {
1296        self.style().keyword(StyleKey::AlignSelf, "center");
1297        self
1298    }
1299
1300    /// Itself at the cross axis' end.
1301    fn self_end(mut self) -> Self {
1302        self.style().keyword(StyleKey::AlignSelf, "flex-end");
1303        self
1304    }
1305
1306    /// Itself stretched across.
1307    fn self_stretch(mut self) -> Self {
1308        self.style().keyword(StyleKey::AlignSelf, "stretch");
1309        self
1310    }
1311
1312    /// The parent's full width.
1313    fn w_full(self) -> Self {
1314        self.w(relative(1.0))
1315    }
1316
1317    /// The parent's full height.
1318    fn h_full(self) -> Self {
1319        self.h(relative(1.0))
1320    }
1321
1322    /// The parent's full size.
1323    fn size_full(self) -> Self {
1324        self.size(relative(1.0))
1325    }
1326
1327    /// Width over height.
1328    fn aspect_ratio(mut self, ratio: impl IntoReactive<f32>) -> Self {
1329        self.style().bind_value(ratio, |s, ratio: f32| {
1330            s.number(StyleKey::AspectRatio, ratio);
1331        });
1332        self
1333    }
1334
1335    /// As wide as high.
1336    fn aspect_square(self) -> Self {
1337        self.aspect_ratio(1.0)
1338    }
1339
1340    /// Laid out in the flow (the default).
1341    fn relative(mut self) -> Self {
1342        self.style().keyword(StyleKey::Position, "relative");
1343        self
1344    }
1345
1346    /// Out of the flow, placed by `top` / `left` / ... in the parent.
1347    fn absolute(mut self) -> Self {
1348        self.style().keyword(StyleKey::Position, "absolute");
1349        self
1350    }
1351
1352    /// Clips its children.
1353    fn overflow_hidden(mut self) -> Self {
1354        self.style().keyword(StyleKey::Overflow, "hidden");
1355        self
1356    }
1357
1358    /// Stacking order among siblings.
1359    fn z_index(mut self, z: impl IntoReactive<i32>) -> Self {
1360        self.style()
1361            .bind_value(z, |s, z: i32| s.number(StyleKey::ZIndex, z as f32));
1362        self
1363    }
1364
1365    // Visuals.
1366
1367    /// The background color.
1368    fn bg(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1369        self.style().bind_value(color, |s, color: AdaptiveColor| {
1370            s.color(&[StyleKey::BackgroundColor], color);
1371        });
1372        self
1373    }
1374
1375    /// Opacity, 0 (invisible) to 1.
1376    fn opacity(mut self, opacity: impl IntoReactive<f32>) -> Self {
1377        self.style().bind_value(opacity, |s, opacity: f32| {
1378            s.number(StyleKey::Opacity, opacity.clamp(0.0, 1.0));
1379        });
1380        self
1381    }
1382
1383    /// The corner radius.
1384    fn rounded(mut self, radius: impl IntoReactive<Length>) -> Self {
1385        self.style().bind_value(radius, |s, radius: Length| {
1386            s.lengths(&[StyleKey::BorderRadius], radius);
1387        });
1388        self
1389    }
1390
1391    /// No rounded corners.
1392    fn rounded_none(self) -> Self {
1393        self.rounded(px(0.0))
1394    }
1395
1396    /// 2pt corners.
1397    fn rounded_xs(self) -> Self {
1398        self.rounded(px(2.0))
1399    }
1400
1401    /// 4pt corners.
1402    fn rounded_sm(self) -> Self {
1403        self.rounded(px(4.0))
1404    }
1405
1406    /// 6pt corners.
1407    fn rounded_md(self) -> Self {
1408        self.rounded(px(6.0))
1409    }
1410
1411    /// 8pt corners.
1412    fn rounded_lg(self) -> Self {
1413        self.rounded(px(8.0))
1414    }
1415
1416    /// 12pt corners.
1417    fn rounded_xl(self) -> Self {
1418        self.rounded(px(12.0))
1419    }
1420
1421    /// 16pt corners.
1422    fn rounded_2xl(self) -> Self {
1423        self.rounded(px(16.0))
1424    }
1425
1426    /// 24pt corners.
1427    fn rounded_3xl(self) -> Self {
1428        self.rounded(px(24.0))
1429    }
1430
1431    /// Fully round ends (pills, circles).
1432    fn rounded_full(self) -> Self {
1433        self.rounded(px(9999.0))
1434    }
1435
1436    /// The top corners' radius.
1437    fn rounded_t(mut self, radius: impl IntoReactive<Length>) -> Self {
1438        self.style().bind_value(radius, |s, radius: Length| {
1439            s.lengths(
1440                &[
1441                    StyleKey::BorderTopLeftRadius,
1442                    StyleKey::BorderTopRightRadius,
1443                ],
1444                radius,
1445            );
1446        });
1447        self
1448    }
1449
1450    /// The bottom corners' radius.
1451    fn rounded_b(mut self, radius: impl IntoReactive<Length>) -> Self {
1452        self.style().bind_value(radius, |s, radius: Length| {
1453            s.lengths(
1454                &[
1455                    StyleKey::BorderBottomLeftRadius,
1456                    StyleKey::BorderBottomRightRadius,
1457                ],
1458                radius,
1459            );
1460        });
1461        self
1462    }
1463
1464    /// The border width on all sides.
1465    fn border(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1466        self.style().bind_value(width, |s, width: AbsoluteLength| {
1467            s.number(StyleKey::BorderWidth, points(width));
1468        });
1469        self
1470    }
1471
1472    /// A 1pt border.
1473    fn border_1(self) -> Self {
1474        self.border(px(1.0))
1475    }
1476
1477    /// A 2pt border.
1478    fn border_2(self) -> Self {
1479        self.border(px(2.0))
1480    }
1481
1482    /// A 1pt top border.
1483    fn border_t_1(mut self) -> Self {
1484        self.style().number(StyleKey::BorderTopWidth, 1.0);
1485        self
1486    }
1487
1488    /// A 1pt bottom border.
1489    fn border_b_1(mut self) -> Self {
1490        self.style().number(StyleKey::BorderBottomWidth, 1.0);
1491        self
1492    }
1493
1494    /// A 1pt left border.
1495    fn border_l_1(mut self) -> Self {
1496        self.style().number(StyleKey::BorderLeftWidth, 1.0);
1497        self
1498    }
1499
1500    /// A 1pt right border.
1501    fn border_r_1(mut self) -> Self {
1502        self.style().number(StyleKey::BorderRightWidth, 1.0);
1503        self
1504    }
1505
1506    /// The border color.
1507    fn border_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1508        self.style().bind_value(color, |s, color: AdaptiveColor| {
1509            s.color(&[StyleKey::BorderColor], color);
1510        });
1511        self
1512    }
1513
1514    /// The top border's width.
1515    fn border_t(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1516        self.style().bind_value(width, |s, width: AbsoluteLength| {
1517            s.number(StyleKey::BorderTopWidth, points(width));
1518        });
1519        self
1520    }
1521
1522    /// The right border's width.
1523    fn border_r(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1524        self.style().bind_value(width, |s, width: AbsoluteLength| {
1525            s.number(StyleKey::BorderRightWidth, points(width));
1526        });
1527        self
1528    }
1529
1530    /// The bottom border's width.
1531    fn border_b(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1532        self.style().bind_value(width, |s, width: AbsoluteLength| {
1533            s.number(StyleKey::BorderBottomWidth, points(width));
1534        });
1535        self
1536    }
1537
1538    /// The left border's width.
1539    fn border_l(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1540        self.style().bind_value(width, |s, width: AbsoluteLength| {
1541            s.number(StyleKey::BorderLeftWidth, points(width));
1542        });
1543        self
1544    }
1545
1546    /// The left and right borders' width.
1547    fn border_x(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1548        self.style().bind_value(width, |s, width: AbsoluteLength| {
1549            s.numbers(
1550                &[StyleKey::BorderLeftWidth, StyleKey::BorderRightWidth],
1551                points(width),
1552            );
1553        });
1554        self
1555    }
1556
1557    /// The top and bottom borders' width.
1558    fn border_y(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1559        self.style().bind_value(width, |s, width: AbsoluteLength| {
1560            s.numbers(
1561                &[StyleKey::BorderTopWidth, StyleKey::BorderBottomWidth],
1562                points(width),
1563            );
1564        });
1565        self
1566    }
1567
1568    /// The leading border's width (left in left-to-right layouts).
1569    fn border_s(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1570        self.style().bind_value(width, |s, width: AbsoluteLength| {
1571            s.number(StyleKey::BorderStartWidth, points(width));
1572        });
1573        self
1574    }
1575
1576    /// The trailing border's width.
1577    fn border_e(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1578        self.style().bind_value(width, |s, width: AbsoluteLength| {
1579            s.number(StyleKey::BorderEndWidth, points(width));
1580        });
1581        self
1582    }
1583
1584    /// The top border's color.
1585    fn border_t_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1586        self.style().bind_value(color, |s, color: AdaptiveColor| {
1587            s.color(&[StyleKey::BorderTopColor], color);
1588        });
1589        self
1590    }
1591
1592    /// The right border's color.
1593    fn border_r_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1594        self.style().bind_value(color, |s, color: AdaptiveColor| {
1595            s.color(&[StyleKey::BorderRightColor], color);
1596        });
1597        self
1598    }
1599
1600    /// The bottom border's color.
1601    fn border_b_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1602        self.style().bind_value(color, |s, color: AdaptiveColor| {
1603            s.color(&[StyleKey::BorderBottomColor], color);
1604        });
1605        self
1606    }
1607
1608    /// The left border's color.
1609    fn border_l_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1610        self.style().bind_value(color, |s, color: AdaptiveColor| {
1611            s.color(&[StyleKey::BorderLeftColor], color);
1612        });
1613        self
1614    }
1615
1616    /// The left and right borders' color.
1617    fn border_x_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1618        self.style().bind_value(color, |s, color: AdaptiveColor| {
1619            s.color(
1620                &[StyleKey::BorderLeftColor, StyleKey::BorderRightColor],
1621                color,
1622            );
1623        });
1624        self
1625    }
1626
1627    /// The top and bottom borders' color.
1628    fn border_y_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1629        self.style().bind_value(color, |s, color: AdaptiveColor| {
1630            s.color(
1631                &[StyleKey::BorderTopColor, StyleKey::BorderBottomColor],
1632                color,
1633            );
1634        });
1635        self
1636    }
1637
1638    /// The leading border's color.
1639    fn border_s_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1640        self.style().bind_value(color, |s, color: AdaptiveColor| {
1641            s.color(&[StyleKey::BorderStartColor], color);
1642        });
1643        self
1644    }
1645
1646    /// The trailing border's color.
1647    fn border_e_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1648        self.style().bind_value(color, |s, color: AdaptiveColor| {
1649            s.color(&[StyleKey::BorderEndColor], color);
1650        });
1651        self
1652    }
1653
1654    /// Solid borders (the default).
1655    fn border_solid(mut self) -> Self {
1656        self.style().keyword(StyleKey::BorderStyle, "solid");
1657        self
1658    }
1659
1660    /// Dashed borders.
1661    fn border_dashed(mut self) -> Self {
1662        self.style().keyword(StyleKey::BorderStyle, "dashed");
1663        self
1664    }
1665
1666    /// Dotted borders.
1667    fn border_dotted(mut self) -> Self {
1668        self.style().keyword(StyleKey::BorderStyle, "dotted");
1669        self
1670    }
1671
1672    /// The shape of its rounded corners.
1673    fn border_curve(mut self, curve: BorderCurve) -> Self {
1674        self.style().keyword(
1675            StyleKey::BorderCurve,
1676            match curve {
1677                BorderCurve::Circular => "circular",
1678                BorderCurve::Continuous => "continuous",
1679            },
1680        );
1681        self
1682    }
1683
1684    /// The top left corner's radius.
1685    fn rounded_tl(mut self, radius: impl IntoReactive<Length>) -> Self {
1686        self.style().bind_value(radius, |s, radius: Length| {
1687            s.lengths(&[StyleKey::BorderTopLeftRadius], radius);
1688        });
1689        self
1690    }
1691
1692    /// The top right corner's radius.
1693    fn rounded_tr(mut self, radius: impl IntoReactive<Length>) -> Self {
1694        self.style().bind_value(radius, |s, radius: Length| {
1695            s.lengths(&[StyleKey::BorderTopRightRadius], radius);
1696        });
1697        self
1698    }
1699
1700    /// The bottom right corner's radius.
1701    fn rounded_br(mut self, radius: impl IntoReactive<Length>) -> Self {
1702        self.style().bind_value(radius, |s, radius: Length| {
1703            s.lengths(&[StyleKey::BorderBottomRightRadius], radius);
1704        });
1705        self
1706    }
1707
1708    /// The bottom left corner's radius.
1709    fn rounded_bl(mut self, radius: impl IntoReactive<Length>) -> Self {
1710        self.style().bind_value(radius, |s, radius: Length| {
1711            s.lengths(&[StyleKey::BorderBottomLeftRadius], radius);
1712        });
1713        self
1714    }
1715
1716    /// The left corners' radius.
1717    fn rounded_l(mut self, radius: impl IntoReactive<Length>) -> Self {
1718        self.style().bind_value(radius, |s, radius: Length| {
1719            s.lengths(
1720                &[
1721                    StyleKey::BorderTopLeftRadius,
1722                    StyleKey::BorderBottomLeftRadius,
1723                ],
1724                radius,
1725            );
1726        });
1727        self
1728    }
1729
1730    /// The right corners' radius.
1731    fn rounded_r(mut self, radius: impl IntoReactive<Length>) -> Self {
1732        self.style().bind_value(radius, |s, radius: Length| {
1733            s.lengths(
1734                &[
1735                    StyleKey::BorderTopRightRadius,
1736                    StyleKey::BorderBottomRightRadius,
1737                ],
1738                radius,
1739            );
1740        });
1741        self
1742    }
1743
1744    /// The top leading corner's radius (top left in left-to-right
1745    /// layouts; Tailwind's `rounded-ss`).
1746    fn rounded_ss(mut self, radius: impl IntoReactive<Length>) -> Self {
1747        self.style().bind_value(radius, |s, radius: Length| {
1748            s.lengths(&[StyleKey::BorderTopStartRadius], radius);
1749        });
1750        self
1751    }
1752
1753    /// The top trailing corner's radius (`rounded-se`).
1754    fn rounded_se(mut self, radius: impl IntoReactive<Length>) -> Self {
1755        self.style().bind_value(radius, |s, radius: Length| {
1756            s.lengths(&[StyleKey::BorderTopEndRadius], radius);
1757        });
1758        self
1759    }
1760
1761    /// The bottom trailing corner's radius (`rounded-ee`).
1762    fn rounded_ee(mut self, radius: impl IntoReactive<Length>) -> Self {
1763        self.style().bind_value(radius, |s, radius: Length| {
1764            s.lengths(&[StyleKey::BorderBottomEndRadius], radius);
1765        });
1766        self
1767    }
1768
1769    /// The bottom leading corner's radius (`rounded-es`).
1770    fn rounded_es(mut self, radius: impl IntoReactive<Length>) -> Self {
1771        self.style().bind_value(radius, |s, radius: Length| {
1772            s.lengths(&[StyleKey::BorderBottomStartRadius], radius);
1773        });
1774        self
1775    }
1776
1777    /// The leading corners' radius.
1778    fn rounded_s(mut self, radius: impl IntoReactive<Length>) -> Self {
1779        self.style().bind_value(radius, |s, radius: Length| {
1780            s.lengths(
1781                &[
1782                    StyleKey::BorderTopStartRadius,
1783                    StyleKey::BorderBottomStartRadius,
1784                ],
1785                radius,
1786            );
1787        });
1788        self
1789    }
1790
1791    /// The trailing corners' radius.
1792    fn rounded_e(mut self, radius: impl IntoReactive<Length>) -> Self {
1793        self.style().bind_value(radius, |s, radius: Length| {
1794            s.lengths(
1795                &[
1796                    StyleKey::BorderTopEndRadius,
1797                    StyleKey::BorderBottomEndRadius,
1798                ],
1799                radius,
1800            );
1801        });
1802        self
1803    }
1804
1805    /// An outline `width` wide, outside the border; it takes no space.
1806    fn outline(mut self, width: impl Into<AbsoluteLength>) -> Self {
1807        let s = self.style();
1808        s.number(StyleKey::OutlineWidth, points(width.into()));
1809        s.keyword(StyleKey::OutlineStyle, "solid");
1810        self
1811    }
1812
1813    /// The outline's color.
1814    fn outline_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1815        self.style().bind_value(color, |s, color: AdaptiveColor| {
1816            s.color(&[StyleKey::OutlineColor], color);
1817        });
1818        self
1819    }
1820
1821    /// The outline's distance from the border (negative: inside it).
1822    fn outline_offset(mut self, offset: impl IntoReactive<AbsoluteLength>) -> Self {
1823        self.style()
1824            .bind_value(offset, |s, offset: AbsoluteLength| {
1825                s.number(StyleKey::OutlineOffset, points(offset));
1826            });
1827        self
1828    }
1829
1830    /// A dashed outline.
1831    fn outline_dashed(mut self) -> Self {
1832        self.style().keyword(StyleKey::OutlineStyle, "dashed");
1833        self
1834    }
1835
1836    /// A dotted outline.
1837    fn outline_dotted(mut self) -> Self {
1838        self.style().keyword(StyleKey::OutlineStyle, "dotted");
1839        self
1840    }
1841
1842    /// No outline.
1843    fn outline_none(mut self) -> Self {
1844        self.style().keyword(StyleKey::OutlineStyle, "none");
1845        self
1846    }
1847
1848    /// No shadow.
1849    fn shadow_none(mut self) -> Self {
1850        self.style().push(Declaration::Shadow("none"));
1851        self
1852    }
1853
1854    /// Tailwind's `shadow-2xs`.
1855    fn shadow_2xs(mut self) -> Self {
1856        self.style().push(Declaration::Shadow("2xs"));
1857        self
1858    }
1859
1860    /// Tailwind's `shadow-xs`.
1861    fn shadow_xs(mut self) -> Self {
1862        self.style().push(Declaration::Shadow("xs"));
1863        self
1864    }
1865
1866    /// Tailwind's `shadow-sm`.
1867    fn shadow_sm(mut self) -> Self {
1868        self.style().push(Declaration::Shadow("sm"));
1869        self
1870    }
1871
1872    /// Tailwind's `shadow-md`.
1873    fn shadow_md(mut self) -> Self {
1874        self.style().push(Declaration::Shadow("md"));
1875        self
1876    }
1877
1878    /// Tailwind's `shadow-lg`.
1879    fn shadow_lg(mut self) -> Self {
1880        self.style().push(Declaration::Shadow("lg"));
1881        self
1882    }
1883
1884    /// Tailwind's `shadow-xl`.
1885    fn shadow_xl(mut self) -> Self {
1886        self.style().push(Declaration::Shadow("xl"));
1887        self
1888    }
1889
1890    /// Tailwind's `shadow-2xl`.
1891    fn shadow_2xl(mut self) -> Self {
1892        self.style().push(Declaration::Shadow("2xl"));
1893        self
1894    }
1895
1896    /// Box shadows of its own (CSS's `box-shadow`: offsets, blur, spread,
1897    /// color, `inset`), instead of a preset's.
1898    fn shadow(mut self, layers: impl IntoIterator<Item = BoxShadow>) -> Self {
1899        let layers: Arc<[BoxShadow]> = layers.into_iter().collect();
1900        self.style().push(Declaration::Shadows(Layers(layers)));
1901        self
1902    }
1903
1904    /// The shadow's color: of the presets' layers (an opaque color keeps
1905    /// their alpha, Tailwind's `shadow-sky-500`; one with an alpha sets it,
1906    /// `shadow-sky-500/50`), or of the shadow set with
1907    /// [`Styled::shadow_opacity`], [`Styled::shadow_radius`] and
1908    /// [`Styled::shadow_offset`].
1909    fn shadow_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
1910        let color = color.into();
1911        let s = self.style();
1912        s.color(&[StyleKey::ShadowColor], color);
1913        s.push(Declaration::PartColor(ColorPart::Shadow, color));
1914        self
1915    }
1916
1917    /// A shadow of this opacity (0 by default: none), with
1918    /// [`Styled::shadow_color`] (black by default), [`Styled::shadow_radius`]
1919    /// and [`Styled::shadow_offset`].
1920    fn shadow_opacity(mut self, opacity: impl IntoReactive<f32>) -> Self {
1921        self.style().bind_value(opacity, |s, opacity: f32| {
1922            s.number(StyleKey::ShadowOpacity, opacity.clamp(0.0, 1.0));
1923        });
1924        self
1925    }
1926
1927    /// The shadow's blur radius (3 points by default).
1928    fn shadow_radius(mut self, radius: impl IntoReactive<Points>) -> Self {
1929        self.style().bind_value(radius, |s, radius: Points| {
1930            s.number(StyleKey::ShadowRadius, radius.0);
1931        });
1932        self
1933    }
1934
1935    /// The shadow's offset (right and down; `(0, -3)` points by default).
1936    fn shadow_offset(mut self, offset: Point<Points>) -> Self {
1937        self.style().push(Declaration::ShadowOffset(
1938            Bits(offset.x.0),
1939            Bits(offset.y.0),
1940        ));
1941        self
1942    }
1943
1944    /// Tailwind's `inset-shadow-2xs`.
1945    fn inset_shadow_2xs(mut self) -> Self {
1946        self.style().push(Declaration::InsetShadow("2xs"));
1947        self
1948    }
1949
1950    /// Tailwind's `inset-shadow-xs`.
1951    fn inset_shadow_xs(mut self) -> Self {
1952        self.style().push(Declaration::InsetShadow("xs"));
1953        self
1954    }
1955
1956    /// Tailwind's `inset-shadow-sm`.
1957    fn inset_shadow_sm(mut self) -> Self {
1958        self.style().push(Declaration::InsetShadow("sm"));
1959        self
1960    }
1961
1962    /// No inset shadow.
1963    fn inset_shadow_none(mut self) -> Self {
1964        self.style().push(Declaration::InsetShadow("none"));
1965        self
1966    }
1967
1968    /// The inset shadow's color (as [`Styled::shadow_color`] for the
1969    /// presets).
1970    fn inset_shadow_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1971        self.style().bind_value(color, |s, color: AdaptiveColor| {
1972            s.push(Declaration::PartColor(ColorPart::InsetShadow, color));
1973        });
1974        self
1975    }
1976
1977    /// A ring `width` wide around the border (a solid shadow; it takes no
1978    /// space), in the text color unless [`Styled::ring_color`].
1979    fn ring(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1980        self.style().bind_value(width, |s, width: AbsoluteLength| {
1981            s.push(Declaration::Ring(Bits(points(width))));
1982        });
1983        self
1984    }
1985
1986    /// The ring's color.
1987    fn ring_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
1988        self.style().bind_value(color, |s, color: AdaptiveColor| {
1989            s.push(Declaration::PartColor(ColorPart::Ring, color));
1990        });
1991        self
1992    }
1993
1994    /// A gap of `width` between the border and the ring.
1995    fn ring_offset(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
1996        self.style().bind_value(width, |s, width: AbsoluteLength| {
1997            s.push(Declaration::RingOffset(Bits(points(width))));
1998        });
1999        self
2000    }
2001
2002    /// The gap's color (white by default).
2003    fn ring_offset_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2004        self.style().bind_value(color, |s, color: AdaptiveColor| {
2005            s.push(Declaration::PartColor(ColorPart::RingOffset, color));
2006        });
2007        self
2008    }
2009
2010    /// The ring inside the border instead.
2011    fn ring_inset(mut self) -> Self {
2012        self.style().push(Declaration::RingInset);
2013        self
2014    }
2015
2016    /// A second ring `width` wide, inside the border.
2017    fn inset_ring(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
2018        self.style().bind_value(width, |s, width: AbsoluteLength| {
2019            s.push(Declaration::InsetRing(Bits(points(width))));
2020        });
2021        self
2022    }
2023
2024    /// The inside ring's color.
2025    fn inset_ring_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2026        self.style().bind_value(color, |s, color: AdaptiveColor| {
2027            s.push(Declaration::PartColor(ColorPart::InsetRing, color));
2028        });
2029        self
2030    }
2031
2032    /// A linear gradient over the background, along `angle` (0 up,
2033    /// `deg(90.0)` right), from [`Styled::gradient_from`] through
2034    /// [`Styled::gradient_via`] to [`Styled::gradient_to`].
2035    fn bg_linear(mut self, angle: impl IntoReactive<Radians>) -> Self {
2036        self.style().bind_value(angle, |s, angle: Radians| {
2037            s.push(Declaration::Gradient(GradientShape::Linear(Bits(angle.0))));
2038        });
2039        self
2040    }
2041
2042    /// A linear gradient towards the top.
2043    fn bg_linear_to_t(self) -> Self {
2044        self.bg_linear(deg(0.0))
2045    }
2046
2047    /// A linear gradient towards the right.
2048    fn bg_linear_to_r(self) -> Self {
2049        self.bg_linear(deg(90.0))
2050    }
2051
2052    /// A linear gradient towards the bottom.
2053    fn bg_linear_to_b(self) -> Self {
2054        self.bg_linear(deg(180.0))
2055    }
2056
2057    /// A linear gradient towards the left.
2058    fn bg_linear_to_l(self) -> Self {
2059        self.bg_linear(deg(270.0))
2060    }
2061
2062    /// A linear gradient towards the top right corner.
2063    fn bg_linear_to_tr(mut self) -> Self {
2064        self.style()
2065            .push(Declaration::Gradient(GradientShape::Corner {
2066                right: true,
2067                bottom: false,
2068            }));
2069        self
2070    }
2071
2072    /// A linear gradient towards the bottom right corner.
2073    fn bg_linear_to_br(mut self) -> Self {
2074        self.style()
2075            .push(Declaration::Gradient(GradientShape::Corner {
2076                right: true,
2077                bottom: true,
2078            }));
2079        self
2080    }
2081
2082    /// A linear gradient towards the bottom left corner.
2083    fn bg_linear_to_bl(mut self) -> Self {
2084        self.style()
2085            .push(Declaration::Gradient(GradientShape::Corner {
2086                right: false,
2087                bottom: true,
2088            }));
2089        self
2090    }
2091
2092    /// A linear gradient towards the top left corner.
2093    fn bg_linear_to_tl(mut self) -> Self {
2094        self.style()
2095            .push(Declaration::Gradient(GradientShape::Corner {
2096                right: false,
2097                bottom: false,
2098            }));
2099        self
2100    }
2101
2102    /// A radial gradient from the center to the farthest corner.
2103    fn bg_radial(mut self) -> Self {
2104        self.style()
2105            .push(Declaration::Gradient(GradientShape::Radial));
2106        self
2107    }
2108
2109    /// A conic gradient around the center, starting at `angle` (0 up).
2110    fn bg_conic(mut self, angle: impl IntoReactive<Radians>) -> Self {
2111        self.style().bind_value(angle, |s, angle: Radians| {
2112            s.push(Declaration::Gradient(GradientShape::Conic(Bits(angle.0))));
2113        });
2114        self
2115    }
2116
2117    /// No gradient.
2118    fn bg_gradient_none(mut self) -> Self {
2119        self.style().push(Declaration::GradientNone);
2120        self
2121    }
2122
2123    /// The gradient's first color (transparent by default).
2124    fn gradient_from(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2125        self.style().bind_value(color, |s, color: AdaptiveColor| {
2126            s.push(Declaration::PartColor(ColorPart::From, color));
2127        });
2128        self
2129    }
2130
2131    /// A color in the middle of the gradient.
2132    fn gradient_via(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2133        self.style().bind_value(color, |s, color: AdaptiveColor| {
2134            s.push(Declaration::PartColor(ColorPart::Via, color));
2135        });
2136        self
2137    }
2138
2139    /// The gradient's last color (transparent by default).
2140    fn gradient_to(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2141        self.style().bind_value(color, |s, color: AdaptiveColor| {
2142            s.push(Declaration::PartColor(ColorPart::To, color));
2143        });
2144        self
2145    }
2146
2147    /// Where the first color is along the gradient (0% by default).
2148    fn gradient_from_position(mut self, at: impl IntoReactive<Percentage>) -> Self {
2149        self.style().bind_value(at, |s, at: Percentage| {
2150            s.push(Declaration::StopPosition(0, Bits(at.0)));
2151        });
2152        self
2153    }
2154
2155    /// Where the middle color is (50% by default).
2156    fn gradient_via_position(mut self, at: impl IntoReactive<Percentage>) -> Self {
2157        self.style().bind_value(at, |s, at: Percentage| {
2158            s.push(Declaration::StopPosition(1, Bits(at.0)));
2159        });
2160        self
2161    }
2162
2163    /// Where the last color is (100% by default).
2164    fn gradient_to_position(mut self, at: impl IntoReactive<Percentage>) -> Self {
2165        self.style().bind_value(at, |s, at: Percentage| {
2166            s.push(Declaration::StopPosition(2, Bits(at.0)));
2167        });
2168        self
2169    }
2170
2171    /// Blurs it and its content by `radius` (Tailwind's `blur-sm` is 8
2172    /// points).
2173    fn blur(self, radius: impl Into<Points>) -> Self {
2174        filter(self, false, FilterFn::Blur, radius.into().0)
2175    }
2176
2177    /// Brightens (> 1) or darkens (< 1) it.
2178    fn brightness(self, amount: f32) -> Self {
2179        filter(self, false, FilterFn::Brightness, amount)
2180    }
2181
2182    /// Raises (> 1) or lowers (< 1) its contrast.
2183    fn contrast(self, amount: f32) -> Self {
2184        filter(self, false, FilterFn::Contrast, amount)
2185    }
2186
2187    /// Turns it gray (1: fully).
2188    fn grayscale(self, amount: f32) -> Self {
2189        filter(self, false, FilterFn::Grayscale, amount)
2190    }
2191
2192    /// Turns its hues by `angle`.
2193    fn hue_rotate(self, angle: impl Into<Radians>) -> Self {
2194        filter(self, false, FilterFn::HueRotate, angle.into().to_degrees())
2195    }
2196
2197    /// Inverts its colors (1: fully).
2198    fn invert(self, amount: f32) -> Self {
2199        filter(self, false, FilterFn::Invert, amount)
2200    }
2201
2202    /// Saturates (> 1) or desaturates (< 1) it.
2203    fn saturate(self, amount: f32) -> Self {
2204        filter(self, false, FilterFn::Saturate, amount)
2205    }
2206
2207    /// Tones it sepia (1: fully).
2208    fn sepia(self, amount: f32) -> Self {
2209        filter(self, false, FilterFn::Sepia, amount)
2210    }
2211
2212    /// No filters.
2213    fn filter_none(mut self) -> Self {
2214        self.style().push(Declaration::FilterNone(false));
2215        self
2216    }
2217
2218    /// Blurs what is behind it by `radius` (frosted glass; give it a
2219    /// translucent background).
2220    fn backdrop_blur(self, radius: impl Into<Points>) -> Self {
2221        filter(self, true, FilterFn::Blur, radius.into().0)
2222    }
2223
2224    /// Brightens or darkens what is behind it.
2225    fn backdrop_brightness(self, amount: f32) -> Self {
2226        filter(self, true, FilterFn::Brightness, amount)
2227    }
2228
2229    /// Changes the contrast of what is behind it.
2230    fn backdrop_contrast(self, amount: f32) -> Self {
2231        filter(self, true, FilterFn::Contrast, amount)
2232    }
2233
2234    /// Turns what is behind it gray.
2235    fn backdrop_grayscale(self, amount: f32) -> Self {
2236        filter(self, true, FilterFn::Grayscale, amount)
2237    }
2238
2239    /// Turns the hues of what is behind it.
2240    fn backdrop_hue_rotate(self, angle: impl Into<Radians>) -> Self {
2241        filter(self, true, FilterFn::HueRotate, angle.into().to_degrees())
2242    }
2243
2244    /// Inverts what is behind it.
2245    fn backdrop_invert(self, amount: f32) -> Self {
2246        filter(self, true, FilterFn::Invert, amount)
2247    }
2248
2249    /// Fades what is behind it.
2250    fn backdrop_opacity(self, amount: f32) -> Self {
2251        filter(self, true, FilterFn::Opacity, amount)
2252    }
2253
2254    /// Saturates what is behind it.
2255    fn backdrop_saturate(self, amount: f32) -> Self {
2256        filter(self, true, FilterFn::Saturate, amount)
2257    }
2258
2259    /// Tones what is behind it sepia.
2260    fn backdrop_sepia(self, amount: f32) -> Self {
2261        filter(self, true, FilterFn::Sepia, amount)
2262    }
2263
2264    /// No backdrop filters.
2265    fn backdrop_filter_none(mut self) -> Self {
2266        self.style().push(Declaration::FilterNone(true));
2267        self
2268    }
2269
2270    /// How it blends with what is behind it.
2271    fn mix_blend_mode(mut self, mode: BlendMode) -> Self {
2272        self.style().keyword(StyleKey::MixBlendMode, mode.name());
2273        self
2274    }
2275
2276    /// The pointer's look over the element (`cursor`; desktops, and iPad
2277    /// and Android with a mouse).
2278    fn cursor(mut self, cursor: Cursor) -> Self {
2279        self.style().keyword(StyleKey::Cursor, cursor.name());
2280        self
2281    }
2282
2283    /// The pointing hand over the element: something to press (Tailwind's
2284    /// `cursor-pointer`).
2285    fn cursor_pointer(self) -> Self {
2286        self.cursor(Cursor::Pointer)
2287    }
2288
2289    /// Changes of colors, opacity, shadows and transforms animate
2290    /// (Tailwind's `transition`: 150ms, ease-in-out by default).
2291    fn transition(self) -> Self {
2292        transition(
2293            self,
2294            TransitionProps::COLORS
2295                | TransitionProps::OPACITY
2296                | TransitionProps::SHADOW
2297                | TransitionProps::TRANSFORM,
2298        )
2299    }
2300
2301    /// Changes of everything that can animate do.
2302    fn transition_all(self) -> Self {
2303        transition(self, TransitionProps::ALL)
2304    }
2305
2306    /// Changes of colors animate.
2307    fn transition_colors(self) -> Self {
2308        transition(self, TransitionProps::COLORS)
2309    }
2310
2311    /// Changes of opacity animate.
2312    fn transition_opacity(self) -> Self {
2313        transition(self, TransitionProps::OPACITY)
2314    }
2315
2316    /// Changes of shadows animate.
2317    fn transition_shadow(self) -> Self {
2318        transition(self, TransitionProps::SHADOW)
2319    }
2320
2321    /// Changes of the transform animate.
2322    fn transition_transform(self) -> Self {
2323        transition(self, TransitionProps::TRANSFORM)
2324    }
2325
2326    /// Changes jump.
2327    fn transition_none(mut self) -> Self {
2328        self.style().push(Declaration::TransitionNone);
2329        self
2330    }
2331
2332    /// Transitions last `ms` milliseconds.
2333    fn duration(mut self, ms: impl IntoReactive<f32>) -> Self {
2334        self.style().bind_value(ms, |s, ms: f32| {
2335            s.push(Declaration::Duration(Bits(ms)));
2336        });
2337        self
2338    }
2339
2340    /// Transitions start after `ms` milliseconds.
2341    fn delay(mut self, ms: impl IntoReactive<f32>) -> Self {
2342        self.style().bind_value(ms, |s, ms: f32| {
2343            s.push(Declaration::Delay(Bits(ms)));
2344        });
2345        self
2346    }
2347
2348    /// Transitions at a constant pace.
2349    fn ease_linear(mut self) -> Self {
2350        self.style().push(Declaration::EasePreset("linear"));
2351        self
2352    }
2353
2354    /// Transitions that start slowly.
2355    fn ease_in(mut self) -> Self {
2356        self.style().push(Declaration::EasePreset("in"));
2357        self
2358    }
2359
2360    /// Transitions that end slowly.
2361    fn ease_out(mut self) -> Self {
2362        self.style().push(Declaration::EasePreset("out"));
2363        self
2364    }
2365
2366    /// Transitions that start and end slowly.
2367    fn ease_in_out(mut self) -> Self {
2368        self.style().push(Declaration::EasePreset("in-out"));
2369        self
2370    }
2371
2372    /// Transitions along the cubic Bézier curve `x1, y1, x2, y2`.
2373    fn ease_bezier(mut self, x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
2374        self.style()
2375            .push(Declaration::Ease([x1, y1, x2, y2].map(Bits)));
2376        self
2377    }
2378
2379    /// Turns around, forever (Tailwind's `animate-spin`: a loader).
2380    fn animate_spin(mut self) -> Self {
2381        self.style().push(Declaration::Animate(Some(0)));
2382        self
2383    }
2384
2385    /// Scales up and fades out, forever (`animate-ping`: a badge's pulse).
2386    fn animate_ping(mut self) -> Self {
2387        self.style().push(Declaration::Animate(Some(1)));
2388        self
2389    }
2390
2391    /// Fades to half and back, forever (`animate-pulse`: a skeleton).
2392    fn animate_pulse(mut self) -> Self {
2393        self.style().push(Declaration::Animate(Some(2)));
2394        self
2395    }
2396
2397    /// Jumps and lands, forever (`animate-bounce`).
2398    fn animate_bounce(mut self) -> Self {
2399        self.style().push(Declaration::Animate(Some(3)));
2400        self
2401    }
2402
2403    /// A keyframe animation with its own timing (TS: `animationName`
2404    /// with `animationDuration`, `animationDelay`,
2405    /// `animationTimingFunction`, `animationIterationCount`):
2406    /// `.animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0))`.
2407    fn animation(mut self, animation: KeyframeAnimation) -> Self {
2408        let index = KEYFRAMES
2409            .iter()
2410            .position(|k| *k == animation.keyframes)
2411            .expect("every keyframes") as u8;
2412        self.style().push(Declaration::Animation(
2413            index,
2414            Bits(animation.duration),
2415            Bits(animation.delay),
2416            animation.easing.map(Bits),
2417            animation.iterations,
2418        ));
2419        self
2420    }
2421
2422    /// No keyframe animation.
2423    fn animate_none(mut self) -> Self {
2424        self.style().push(Declaration::Animate(None));
2425        self
2426    }
2427
2428    /// Scales from the center (1 is the natural size).
2429    fn scale(self, scale: impl IntoReactive<f32>) -> Self {
2430        self.transform_step(TransformKind::Scale, scale)
2431    }
2432
2433    /// Scales horizontally.
2434    fn scale_x(self, scale: impl IntoReactive<f32>) -> Self {
2435        self.transform_step(TransformKind::ScaleX, scale)
2436    }
2437
2438    /// Scales vertically.
2439    fn scale_y(self, scale: impl IntoReactive<f32>) -> Self {
2440        self.transform_step(TransformKind::ScaleY, scale)
2441    }
2442
2443    /// Moves horizontally by `offset` (after layout): points, or a
2444    /// fraction of its own width (`relative(-0.5)`).
2445    fn translate_x(self, offset: impl IntoReactive<DefiniteLength>) -> Self {
2446        transform_with(self, offset, |offset| {
2447            translation(
2448                offset,
2449                TransformKind::TranslateX,
2450                TransformKind::TranslateXFraction,
2451            )
2452        })
2453    }
2454
2455    /// Moves vertically by `offset` (after layout): points, or a fraction
2456    /// of its own height.
2457    fn translate_y(self, offset: impl IntoReactive<DefiniteLength>) -> Self {
2458        transform_with(self, offset, |offset| {
2459            translation(
2460                offset,
2461                TransformKind::TranslateY,
2462                TransformKind::TranslateYFraction,
2463            )
2464        })
2465    }
2466
2467    /// Rotates by `angle`, clockwise.
2468    fn rotate(self, angle: impl IntoReactive<Radians>) -> Self {
2469        transform_with(self, angle, |a: Radians| {
2470            (TransformKind::Rotate, a.to_degrees())
2471        })
2472    }
2473
2474    /// Rotates by `angle` around the horizontal axis (3D; with
2475    /// [`Styled::perspective`] it tilts towards the viewer).
2476    fn rotate_x(self, angle: impl IntoReactive<Radians>) -> Self {
2477        transform_with(self, angle, |a: Radians| {
2478            (TransformKind::RotateX, a.to_degrees())
2479        })
2480    }
2481
2482    /// Rotates by `angle` around the vertical axis (3D).
2483    fn rotate_y(self, angle: impl IntoReactive<Radians>) -> Self {
2484        transform_with(self, angle, |a: Radians| {
2485            (TransformKind::RotateY, a.to_degrees())
2486        })
2487    }
2488
2489    /// Slants vertical edges by `angle` (iOS; Android has no skew).
2490    fn skew_x(self, angle: impl IntoReactive<Radians>) -> Self {
2491        transform_with(self, angle, |a: Radians| {
2492            (TransformKind::SkewX, a.to_degrees())
2493        })
2494    }
2495
2496    /// Slants horizontal edges by `angle` (iOS).
2497    fn skew_y(self, angle: impl IntoReactive<Radians>) -> Self {
2498        transform_with(self, angle, |a: Radians| {
2499            (TransformKind::SkewY, a.to_degrees())
2500        })
2501    }
2502
2503    /// Looks at its 3D rotations from `distance` away (smaller: stronger).
2504    fn perspective(self, distance: impl IntoReactive<AbsoluteLength>) -> Self {
2505        transform_with(self, distance, |d: AbsoluteLength| {
2506            (TransformKind::Perspective, points(d))
2507        })
2508    }
2509
2510    /// The step `kind` of its transform, by `amount`. The steps compose in
2511    /// CSS's order, whatever the order of the calls: perspective,
2512    /// translate, rotate, scale, then the 3D rotations and the skews.
2513    fn transform_step(self, kind: TransformKind, amount: impl IntoReactive<f32>) -> Self {
2514        transform_with(self, amount, move |amount| (kind, amount))
2515    }
2516
2517    /// No transform (also none of the steps set before).
2518    fn transform_none(mut self) -> Self {
2519        let style = self.style();
2520        if style.is_bound() {
2521            style.bind(|s| s.push(Declaration::TransformNone));
2522        } else {
2523            style.push(Declaration::TransformNone);
2524        }
2525        self
2526    }
2527
2528    /// The point its transform turns and scales around (the center by
2529    /// default).
2530    fn transform_origin(mut self, origin: TransformOrigin) -> Self {
2531        let axis = |l: DefiniteLength| match l {
2532            DefiniteLength::Absolute(a) => (false, Bits(a.to_points(REM_SIZE).0)),
2533            DefiniteLength::Fraction(f) => (true, Bits(f.0)),
2534        };
2535        self.style()
2536            .push(Declaration::Origin([axis(origin.x), axis(origin.y)]));
2537        self
2538    }
2539
2540    /// Transforms around its top left corner.
2541    fn origin_top_left(mut self) -> Self {
2542        self.style().keyword(StyleKey::TransformOrigin, "top left");
2543        self
2544    }
2545
2546    /// Transforms around the middle of its top edge.
2547    fn origin_top(mut self) -> Self {
2548        self.style().keyword(StyleKey::TransformOrigin, "top");
2549        self
2550    }
2551
2552    /// Transforms around its top right corner.
2553    fn origin_top_right(mut self) -> Self {
2554        self.style().keyword(StyleKey::TransformOrigin, "top right");
2555        self
2556    }
2557
2558    /// Transforms around the middle of its left edge.
2559    fn origin_left(mut self) -> Self {
2560        self.style().keyword(StyleKey::TransformOrigin, "left");
2561        self
2562    }
2563
2564    /// Transforms around its center (the default).
2565    fn origin_center(mut self) -> Self {
2566        self.style().keyword(StyleKey::TransformOrigin, "center");
2567        self
2568    }
2569
2570    /// Transforms around the middle of its right edge.
2571    fn origin_right(mut self) -> Self {
2572        self.style().keyword(StyleKey::TransformOrigin, "right");
2573        self
2574    }
2575
2576    /// Transforms around its bottom left corner.
2577    fn origin_bottom_left(mut self) -> Self {
2578        self.style()
2579            .keyword(StyleKey::TransformOrigin, "bottom left");
2580        self
2581    }
2582
2583    /// Transforms around the middle of its bottom edge.
2584    fn origin_bottom(mut self) -> Self {
2585        self.style().keyword(StyleKey::TransformOrigin, "bottom");
2586        self
2587    }
2588
2589    /// Transforms around its bottom right corner.
2590    fn origin_bottom_right(mut self) -> Self {
2591        self.style()
2592            .keyword(StyleKey::TransformOrigin, "bottom right");
2593        self
2594    }
2595
2596    /// Invisible while its 3D rotations turn it away (a card's back).
2597    fn backface_hidden(mut self) -> Self {
2598        self.style().keyword(StyleKey::BackfaceVisibility, "hidden");
2599        self
2600    }
2601
2602    /// Visible from behind too (the default).
2603    fn backface_visible(mut self) -> Self {
2604        self.style()
2605            .keyword(StyleKey::BackfaceVisibility, "visible");
2606        self
2607    }
2608
2609    // Text (inherited by the texts inside).
2610
2611    /// The text color.
2612    fn text_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2613        self.style().bind_value(color, |s, color: AdaptiveColor| {
2614            s.color(&[StyleKey::Color], color);
2615        });
2616        self
2617    }
2618
2619    /// The tint color (Tailwind's `tint-*`): of template images, and of a
2620    /// page header's buttons in [`super::Screen::header_style_with`].
2621    fn tint_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2622        self.style().bind_value(color, |s, color: AdaptiveColor| {
2623            s.color(&[StyleKey::TintColor], color);
2624        });
2625        self
2626    }
2627
2628    /// The font size, in points.
2629    fn text_size(mut self, size: impl IntoReactive<Length>) -> Self {
2630        self.style().bind_value(size, |s, size: Length| {
2631            s.lengths(&[StyleKey::FontSize], size);
2632        });
2633        self
2634    }
2635
2636    /// 12pt text, 16pt lines.
2637    fn text_xs(mut self) -> Self {
2638        self.style().push(Declaration::TextPreset("xs"));
2639        self
2640    }
2641
2642    /// 14pt text, 20pt lines.
2643    fn text_sm(mut self) -> Self {
2644        self.style().push(Declaration::TextPreset("sm"));
2645        self
2646    }
2647
2648    /// 16pt text, 24pt lines.
2649    fn text_base(mut self) -> Self {
2650        self.style().push(Declaration::TextPreset("base"));
2651        self
2652    }
2653
2654    /// 18pt text, 28pt lines.
2655    fn text_lg(mut self) -> Self {
2656        self.style().push(Declaration::TextPreset("lg"));
2657        self
2658    }
2659
2660    /// 20pt text, 28pt lines.
2661    fn text_xl(mut self) -> Self {
2662        self.style().push(Declaration::TextPreset("xl"));
2663        self
2664    }
2665
2666    /// 24pt text, 32pt lines.
2667    fn text_2xl(mut self) -> Self {
2668        self.style().push(Declaration::TextPreset("2xl"));
2669        self
2670    }
2671
2672    /// 30pt text, 36pt lines.
2673    fn text_3xl(mut self) -> Self {
2674        self.style().push(Declaration::TextPreset("3xl"));
2675        self
2676    }
2677
2678    /// 36pt text, 40pt lines.
2679    fn text_4xl(mut self) -> Self {
2680        self.style().push(Declaration::TextPreset("4xl"));
2681        self
2682    }
2683
2684    /// 48pt text, 48pt lines.
2685    fn text_5xl(mut self) -> Self {
2686        self.style().push(Declaration::TextPreset("5xl"));
2687        self
2688    }
2689
2690    /// 60pt text, 60pt lines.
2691    fn text_6xl(mut self) -> Self {
2692        self.style().push(Declaration::TextPreset("6xl"));
2693        self
2694    }
2695
2696    /// 72pt text, 72pt lines.
2697    fn text_7xl(mut self) -> Self {
2698        self.style().push(Declaration::TextPreset("7xl"));
2699        self
2700    }
2701
2702    /// 96pt text, 96pt lines.
2703    fn text_8xl(mut self) -> Self {
2704        self.style().push(Declaration::TextPreset("8xl"));
2705        self
2706    }
2707
2708    /// 128pt text, 128pt lines.
2709    fn text_9xl(mut self) -> Self {
2710        self.style().push(Declaration::TextPreset("9xl"));
2711        self
2712    }
2713
2714    /// The line height, in points.
2715    fn line_height(mut self, height: impl IntoReactive<Length>) -> Self {
2716        self.style().bind_value(height, |s, height: Length| {
2717            s.lengths(&[StyleKey::LineHeight], height);
2718        });
2719        self
2720    }
2721
2722    /// The font weight.
2723    fn font_weight(mut self, weight: FontWeight) -> Self {
2724        self.style().number(StyleKey::FontWeight, weight.0 as f32);
2725        self
2726    }
2727
2728    /// The font family (`None` style: the system font is the default).
2729    fn font_family(mut self, family: impl IntoReactive<SharedString>) -> Self {
2730        self.style().bind_value(family, |s, family: SharedString| {
2731            s.push(Declaration::Str(StyleKey::FontFamily, family));
2732        });
2733        self
2734    }
2735
2736    /// Italic text.
2737    fn italic(mut self) -> Self {
2738        self.style().keyword(StyleKey::FontStyle, "italic");
2739        self
2740    }
2741
2742    /// Underlined text (with [`Styled::line_through`], both lines).
2743    fn underline(mut self) -> Self {
2744        self.style().push(Declaration::Decoration(UNDERLINE));
2745        self
2746    }
2747
2748    /// Struck-through text (with [`Styled::underline`], both lines).
2749    fn line_through(mut self) -> Self {
2750        self.style().push(Declaration::Decoration(LINE_THROUGH));
2751        self
2752    }
2753
2754    /// No underline nor strike-through.
2755    fn no_underline(mut self) -> Self {
2756        self.style().push(Declaration::Decoration(0));
2757        self
2758    }
2759
2760    /// The color of the underline and strike-through (the text's by
2761    /// default).
2762    fn text_decoration_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
2763        self.style().bind_value(color, |s, color: AdaptiveColor| {
2764            s.color(&[StyleKey::TextDecorationColor], color);
2765        });
2766        self
2767    }
2768
2769    /// Solid decoration lines (the default).
2770    fn text_decoration_solid(mut self) -> Self {
2771        self.style().keyword(StyleKey::TextDecorationStyle, "solid");
2772        self
2773    }
2774
2775    /// Double decoration lines.
2776    fn text_decoration_double(mut self) -> Self {
2777        self.style()
2778            .keyword(StyleKey::TextDecorationStyle, "double");
2779        self
2780    }
2781
2782    /// Dotted decoration lines.
2783    fn text_decoration_dotted(mut self) -> Self {
2784        self.style()
2785            .keyword(StyleKey::TextDecorationStyle, "dotted");
2786        self
2787    }
2788
2789    /// Dashed decoration lines.
2790    fn text_decoration_dashed(mut self) -> Self {
2791        self.style()
2792            .keyword(StyleKey::TextDecorationStyle, "dashed");
2793        self
2794    }
2795
2796    /// Wavy decoration lines (spelling marks).
2797    fn text_decoration_wavy(mut self) -> Self {
2798        self.style().keyword(StyleKey::TextDecorationStyle, "wavy");
2799        self
2800    }
2801
2802    /// The decoration lines' thickness.
2803    fn text_decoration_thickness(mut self, thickness: impl IntoReactive<Points>) -> Self {
2804        self.style().bind_value(thickness, |s, thickness: Points| {
2805            s.number(StyleKey::TextDecorationThickness, thickness.0);
2806        });
2807        self
2808    }
2809
2810    /// The underline's distance below the baseline.
2811    fn underline_offset(mut self, offset: impl IntoReactive<Points>) -> Self {
2812        self.style().bind_value(offset, |s, offset: Points| {
2813            s.number(StyleKey::TextUnderlineOffset, offset.0);
2814        });
2815        self
2816    }
2817
2818    /// Shown in capitals (the content stays as it is).
2819    fn uppercase(mut self) -> Self {
2820        self.style().keyword(StyleKey::TextTransform, "uppercase");
2821        self
2822    }
2823
2824    /// Shown in small letters.
2825    fn lowercase(mut self) -> Self {
2826        self.style().keyword(StyleKey::TextTransform, "lowercase");
2827        self
2828    }
2829
2830    /// Each word shown with a capital first letter.
2831    fn capitalize(mut self) -> Self {
2832        self.style().keyword(StyleKey::TextTransform, "capitalize");
2833        self
2834    }
2835
2836    /// Shown as written (undoes an inherited case).
2837    fn normal_case(mut self) -> Self {
2838        self.style().keyword(StyleKey::TextTransform, "none");
2839        self
2840    }
2841
2842    /// Digits of one width, for columns of numbers.
2843    fn tabular_nums(self) -> Self {
2844        font_variant(
2845            self,
2846            FontVariant::TABULAR_NUMS,
2847            FontVariant::PROPORTIONAL_NUMS,
2848        )
2849    }
2850
2851    /// Digits of their own widths (the default).
2852    fn proportional_nums(self) -> Self {
2853        font_variant(
2854            self,
2855            FontVariant::PROPORTIONAL_NUMS,
2856            FontVariant::TABULAR_NUMS,
2857        )
2858    }
2859
2860    /// Old-style digits, with ascenders and descenders.
2861    fn oldstyle_nums(self) -> Self {
2862        font_variant(self, FontVariant::OLDSTYLE_NUMS, FontVariant::LINING_NUMS)
2863    }
2864
2865    /// Lining digits, all of capital height.
2866    fn lining_nums(self) -> Self {
2867        font_variant(self, FontVariant::LINING_NUMS, FontVariant::OLDSTYLE_NUMS)
2868    }
2869
2870    /// Small capitals for lower-case letters.
2871    fn small_caps(self) -> Self {
2872        font_variant(self, FontVariant::SMALL_CAPS, 0)
2873    }
2874
2875    /// No number or letter forms (undoes the ones set before).
2876    fn normal_nums(self) -> Self {
2877        font_variant(self, 0, 0xff)
2878    }
2879
2880    /// The layout direction of the view and its subtree (by default its
2881    /// parent's; the surface's follows the user's language).
2882    fn direction(mut self, direction: impl IntoReactive<LayoutDirection>) -> Self {
2883        self.style()
2884            .bind_value(direction, |s, direction: LayoutDirection| {
2885                s.keyword(
2886                    StyleKey::Direction,
2887                    match direction {
2888                        LayoutDirection::Inherit => "inherit",
2889                        LayoutDirection::Ltr => "ltr",
2890                        LayoutDirection::Rtl => "rtl",
2891                    },
2892                );
2893            });
2894        self
2895    }
2896
2897    /// The text's base direction (by default its content's).
2898    fn writing_direction(mut self, direction: WritingDirection) -> Self {
2899        self.style().keyword(
2900            StyleKey::WritingDirection,
2901            match direction {
2902                WritingDirection::Auto => "auto",
2903                WritingDirection::Ltr => "ltr",
2904                WritingDirection::Rtl => "rtl",
2905            },
2906        );
2907        self
2908    }
2909
2910    /// Lines stretched to both edges.
2911    fn text_justify(mut self) -> Self {
2912        self.style().keyword(StyleKey::TextAlign, "justify");
2913        self
2914    }
2915
2916    /// Tailwind's `text-shadow-2xs`.
2917    fn text_shadow_2xs(mut self) -> Self {
2918        self.style().push(Declaration::TextShadow("2xs"));
2919        self
2920    }
2921
2922    /// Tailwind's `text-shadow-xs`.
2923    fn text_shadow_xs(mut self) -> Self {
2924        self.style().push(Declaration::TextShadow("xs"));
2925        self
2926    }
2927
2928    /// Tailwind's `text-shadow-sm`.
2929    fn text_shadow_sm(mut self) -> Self {
2930        self.style().push(Declaration::TextShadow("sm"));
2931        self
2932    }
2933
2934    /// Tailwind's `text-shadow-md`.
2935    fn text_shadow_md(mut self) -> Self {
2936        self.style().push(Declaration::TextShadow("md"));
2937        self
2938    }
2939
2940    /// Tailwind's `text-shadow-lg`.
2941    fn text_shadow_lg(mut self) -> Self {
2942        self.style().push(Declaration::TextShadow("lg"));
2943        self
2944    }
2945
2946    /// No text shadow from the presets.
2947    fn text_shadow_none(mut self) -> Self {
2948        self.style().push(Declaration::TextShadow("none"));
2949        self
2950    }
2951
2952    /// The text shadow's color: of a preset (an opaque color keeps the
2953    /// preset's alpha), or of the shadow set with
2954    /// [`Styled::text_shadow_radius`] and [`Styled::text_shadow_offset`].
2955    fn text_shadow_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
2956        let color = color.into();
2957        let s = self.style();
2958        s.color(&[StyleKey::TextShadowColor], color);
2959        s.push(Declaration::PartColor(ColorPart::TextShadow, color));
2960        self
2961    }
2962
2963    /// The text shadow's blur radius.
2964    fn text_shadow_radius(mut self, radius: impl IntoReactive<Points>) -> Self {
2965        self.style().bind_value(radius, |s, radius: Points| {
2966            s.number(StyleKey::TextShadowRadius, radius.0);
2967        });
2968        self
2969    }
2970
2971    /// The text shadow's offset (right and down).
2972    fn text_shadow_offset(mut self, offset: Point<Points>) -> Self {
2973        self.style().push(Declaration::TextShadowOffset(
2974            Bits(offset.x.0),
2975            Bits(offset.y.0),
2976        ));
2977        self
2978    }
2979
2980    /// Text aligned left.
2981    fn text_left(mut self) -> Self {
2982        self.style().keyword(StyleKey::TextAlign, "left");
2983        self
2984    }
2985
2986    /// Text centered.
2987    fn text_center(mut self) -> Self {
2988        self.style().keyword(StyleKey::TextAlign, "center");
2989        self
2990    }
2991
2992    /// Text aligned right.
2993    fn text_right(mut self) -> Self {
2994        self.style().keyword(StyleKey::TextAlign, "right");
2995        self
2996    }
2997
2998    /// Inside a text, its bottom on the baseline (the default:
2999    /// `align-baseline`).
3000    fn align_baseline(mut self) -> Self {
3001        self.style().keyword(StyleKey::VerticalAlign, "baseline");
3002        self
3003    }
3004
3005    /// Inside a text, its top at the top of the text's font
3006    /// (`align-text-top`).
3007    fn align_text_top(mut self) -> Self {
3008        self.style().keyword(StyleKey::VerticalAlign, "text-top");
3009        self
3010    }
3011
3012    /// Inside a text, its bottom at the bottom of the text's font
3013    /// (`align-text-bottom`).
3014    fn align_text_bottom(mut self) -> Self {
3015        self.style().keyword(StyleKey::VerticalAlign, "text-bottom");
3016        self
3017    }
3018
3019    /// Inside a text, its middle half the font's x height above the
3020    /// baseline (`align-middle`).
3021    fn align_middle(mut self) -> Self {
3022        self.style().keyword(StyleKey::VerticalAlign, "middle");
3023        self
3024    }
3025
3026    /// Extra space between letters.
3027    fn letter_spacing(mut self, spacing: impl IntoReactive<AbsoluteLength>) -> Self {
3028        self.style()
3029            .bind_value(spacing, |s, spacing: AbsoluteLength| {
3030                s.number(StyleKey::LetterSpacing, points(spacing));
3031            });
3032        self
3033    }
3034
3035    // Variants (native: nothing runs).
3036
3037    /// `f`'s styles while `when` holds: a value decides once, a signal or a
3038    /// closure switches them as it changes (Tailwind's classes made
3039    /// conditional; native states such as `.active` need none).
3040    fn style_when(
3041        mut self,
3042        when: impl IntoReactive<bool>,
3043        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
3044    ) -> Self {
3045        let layer = f(StyleRefinement::default());
3046        match when.into_reactive() {
3047            Reactive::Static(true) => self.style().extend_as(Variant::default(), layer),
3048            Reactive::Static(false) => {}
3049            Reactive::Bound(when) => self.style().bind(move |s| {
3050                if when() {
3051                    s.extend_as(Variant::default(), layer.resolved());
3052                }
3053            }),
3054        }
3055        self
3056    }
3057
3058    /// The styles `f` makes, made again when what it reads changes (any
3059    /// style that depends on the app's state; a value that changes alone
3060    /// is better given to its method: `.w(move || px(width.get()))`).
3061    fn style_with(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
3062        self.style().bind(move |s| {
3063            let made = f(StyleRefinement::default()).resolved();
3064            s.extend_as(Variant::default(), made);
3065        });
3066        self
3067    }
3068
3069    /// Styles in dark appearance (Tailwind's `dark:`), for what is not a
3070    /// color: theme colors switch by themselves.
3071    fn dark(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3072        let s = f(StyleRefinement::default());
3073        self.style().extend_as(Variant::DARK, s);
3074        self
3075    }
3076
3077    /// Styles while selected (Tailwind's `selected:`): the element's
3078    /// accessibility state says so (a `Button`'s `selected`, a tab's).
3079    fn selected(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3080        let s = f(StyleRefinement::default());
3081        self.style().extend_as(Variant::SELECTED, s);
3082        self
3083    }
3084
3085    /// Styles while checked (Tailwind's `checked:`): the element's
3086    /// accessibility state says so, not mixed (a checkbox's, a switch's, a
3087    /// radio's), or the control it is a part of is
3088    /// (`Interactive::project_checked`: a switch's thumb).
3089    fn checked(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3090        let s = f(StyleRefinement::default());
3091        self.style().extend_as(Variant::CHECKED, s);
3092        self
3093    }
3094
3095    /// Styles while indeterminate (Tailwind's `indeterminate:`): the
3096    /// element's accessibility state says checked is mixed (a checkbox
3097    /// that is neither), or the control it is a part of is
3098    /// (`Interactive::project_indeterminate`: a checkbox's indicator).
3099    fn indeterminate(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3100        let s = f(StyleRefinement::default());
3101        self.style().extend_as(Variant::INDETERMINATE, s);
3102        self
3103    }
3104
3105    /// Makes it a group: the `group_*` styles of the elements inside follow
3106    /// its press, hover and focus (Tailwind's `group`).
3107    fn group(mut self) -> Self {
3108        self.style().push(Declaration::Group(""));
3109        self
3110    }
3111
3112    /// Makes it the group `name` (`group/name`), for `group_*_named`
3113    /// styles inside it that skip nearer groups.
3114    fn group_named(mut self, name: &'static str) -> Self {
3115        self.style().push(Declaration::Group(name));
3116        self
3117    }
3118
3119    /// Styles while the nearest [`Styled::group`] around it is pressed
3120    /// (`group-active:`).
3121    fn group_active(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3122        in_group(self, "", state::PRESSED, f)
3123    }
3124
3125    /// Styles while the nearest group around it is hovered.
3126    fn group_hover(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3127        in_group(self, "", state::HOVERED, f)
3128    }
3129
3130    /// Styles while an input in the nearest group around it has focus
3131    /// (`group-focus-within:`).
3132    fn group_focus_within(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
3133        in_group(self, "", state::FOCUS_WITHIN, f)
3134    }
3135
3136    /// Styles while the group `name` around it is pressed
3137    /// (`group-active/name:`).
3138    fn group_active_named(
3139        self,
3140        name: &'static str,
3141        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
3142    ) -> Self {
3143        in_group(self, name, state::PRESSED, f)
3144    }
3145
3146    /// Styles while the group `name` around it is hovered.
3147    fn group_hover_named(
3148        self,
3149        name: &'static str,
3150        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
3151    ) -> Self {
3152        in_group(self, name, state::HOVERED, f)
3153    }
3154
3155    /// Styles while an input in the group `name` around it has focus.
3156    fn group_focus_within_named(
3157        self,
3158        name: &'static str,
3159        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
3160    ) -> Self {
3161        in_group(self, name, state::FOCUS_WITHIN, f)
3162    }
3163}
3164
3165/// `s` with filter `f` by `amount` (of what is behind it when `backdrop`).
3166/// `s` with the transform step `step` makes of `value` (its kind and
3167/// operand).
3168fn transform_with<S: Styled, T: Clone + 'static>(
3169    mut s: S,
3170    value: impl IntoReactive<T>,
3171    step: impl Fn(T) -> (TransformKind, f32) + 'static,
3172) -> S {
3173    // Steps compose in order: after a bound part, a static step is
3174    // applied with the bound ones too.
3175    let style = s.style();
3176    match value.into_reactive() {
3177        Reactive::Static(value) if !style.is_bound() => {
3178            let (kind, amount) = step(value);
3179            style.push(Declaration::Transform(kind, Bits(amount)));
3180        }
3181        value => style.bind(move |st| {
3182            let (kind, amount) = step(value.get());
3183            st.push(Declaration::Transform(kind, Bits(amount)));
3184        }),
3185    }
3186    s
3187}
3188
3189/// A translation's step: points (a rem at [`REM_SIZE`]) or a fraction of
3190/// the size.
3191fn translation(
3192    offset: DefiniteLength,
3193    points_kind: TransformKind,
3194    fraction_kind: TransformKind,
3195) -> (TransformKind, f32) {
3196    match offset {
3197        DefiniteLength::Absolute(a) => (points_kind, points(a)),
3198        DefiniteLength::Fraction(f) => (fraction_kind, f.0),
3199    }
3200}
3201
3202fn filter<S: Styled>(mut s: S, backdrop: bool, f: FilterFn, amount: f32) -> S {
3203    s.style()
3204        .push(Declaration::Filter(backdrop, f, Bits(amount)));
3205    s
3206}
3207
3208/// `s` with transitions of the [`TransitionProps`] `props`.
3209fn transition<S: Styled>(mut s: S, props: u8) -> S {
3210    s.style().push(Declaration::Transition(props));
3211    s
3212}
3213
3214/// `s` with `f`'s styles while the group `name` is in `states`.
3215fn in_group<S: Styled>(
3216    mut s: S,
3217    name: &'static str,
3218    states: u8,
3219    f: impl FnOnce(StyleRefinement) -> StyleRefinement,
3220) -> S {
3221    let styles = f(StyleRefinement::default());
3222    let style = s.style();
3223    let group = style.name(name);
3224    style.extend_as(
3225        Variant {
3226            group_states: states,
3227            group,
3228            ..Variant::default()
3229        },
3230        styles,
3231    );
3232    s
3233}
3234
3235impl Styled for StyleRefinement {
3236    fn style(&mut self) -> &mut StyleRefinement {
3237        self
3238    }
3239}
3240
3241#[cfg(test)]
3242mod tests {
3243    use super::*;
3244    use crate::{
3245        Style,
3246        color::{rgb, rgba},
3247        geometry::point,
3248        tailwind::{ClassEnvironment, ClassProps, Context},
3249        ui::palette::{EMERALD, PINK, RED, SKY, VIOLET},
3250    };
3251
3252    /// What `list` resolves to in `dark` appearance, in [`state`] `states`,
3253    /// inside a group in `group` (as text, to compare).
3254    fn resolve(list: &ClassList, dark: bool, states: u8, group: u8) -> String {
3255        resolve_with(list, dark, states, group, &|_| {})
3256    }
3257
3258    /// [`resolve`], then `inline` on the style.
3259    fn resolve_with(
3260        list: &ClassList,
3261        dark: bool,
3262        states: u8,
3263        group: u8,
3264        inline: &dyn Fn(&mut Style),
3265    ) -> String {
3266        let cx = Context {
3267            env: ClassEnvironment {
3268                dark,
3269                ..Default::default()
3270            },
3271            window: crate::geometry::size_pt(390.0, 844.0),
3272            rtl: false,
3273            states,
3274            position: 0,
3275            group: &|_| group,
3276        };
3277        let mut style = Style::default();
3278        let mut props = ClassProps::default();
3279        list.apply(&cx, &PRESETS, &mut style, &mut props, inline);
3280        format!("{style:?} {props:?}")
3281    }
3282
3283    /// `typed` styles an element as Tailwind's `classes` do, in both
3284    /// appearances and in every state.
3285    #[track_caller]
3286    fn same(typed: StyleRefinement, classes: &str) {
3287        same_with(typed, classes, &|_| {});
3288    }
3289
3290    /// [`same`], `classes` then `inline` (what classes cannot say).
3291    #[track_caller]
3292    fn same_with(typed: StyleRefinement, classes: &str, inline: &dyn Fn(&mut Style)) {
3293        let typed = typed.lower();
3294        let parsed = tailwind::parse(&PRESETS, classes);
3295        assert!(parsed.unknown().is_empty(), "{:?}", parsed.unknown());
3296        assert_eq!(typed.deps(), parsed.deps(), "{classes}: deps");
3297        assert_eq!(typed.groups(), parsed.groups(), "{classes}: groups");
3298        for dark in [false, true] {
3299            for states in [0, state::PRESSED, state::DISABLED] {
3300                for group in [0, state::PRESSED, state::HOVERED] {
3301                    assert_eq!(
3302                        resolve(&typed, dark, states, group),
3303                        resolve_with(&parsed, dark, states, group, inline),
3304                        "{classes} (dark {dark}, states {states}, group {group})"
3305                    );
3306                }
3307            }
3308        }
3309    }
3310
3311    fn s() -> StyleRefinement {
3312        StyleRefinement::default()
3313    }
3314
3315    #[test]
3316    fn borders_and_corners_are_tailwinds() {
3317        same(
3318            s().border_t(px(6.0))
3319                .border_t_color(RED.shade(600))
3320                .border_r(px(2.0))
3321                .border_b(px(4.0))
3322                .border_l(px(1.0))
3323                .border_x_color(SKY.shade(500)),
3324            "border-t-6 border-t-red-600 border-r-2 border-b-4 border-l border-x-sky-500",
3325        );
3326        same(
3327            s().border_y(px(3.0))
3328                .border_s(px(1.0))
3329                .border_e(px(2.0))
3330                .border_dashed(),
3331            "border-y-3 border-s border-e-2 border-dashed",
3332        );
3333        same(
3334            s().border(px(3.0)).border_dotted(),
3335            "border-3 border-dotted",
3336        );
3337        same(
3338            s().rounded_tl(px(44.0))
3339                .rounded_tr(px(6.0))
3340                .rounded_br(px(28.0))
3341                .rounded_bl(px(2.0)),
3342            "rounded-tl-[44px] rounded-tr-[6px] rounded-br-[28px] rounded-bl-[2px]",
3343        );
3344        same(
3345            s().rounded_ss(px(22.0))
3346                .rounded_ee(px(8.0))
3347                .rounded_l(px(4.0)),
3348            "rounded-ss-[22px] rounded-ee-[8px] rounded-l-[4px]",
3349        );
3350        same(
3351            s().outline(px(2.0))
3352                .outline_offset(px(2.0))
3353                .outline_dashed()
3354                .outline_color(PINK.shade(500)),
3355            "outline-2 outline-offset-2 outline-dashed outline-pink-500",
3356        );
3357        let curved = s().border_curve(BorderCurve::Continuous).lower();
3358        let mut style = Style::default();
3359        let _ = style.set_key(StyleKey::BorderCurve, crate::StyleValue::Str("continuous"));
3360        assert_eq!(
3361            resolve(&curved, false, 0, 0),
3362            format!("{style:?} {:?}", ClassProps::default())
3363        );
3364    }
3365
3366    #[test]
3367    fn shadows_and_rings_are_tailwinds() {
3368        // The color is React Native's shadow's too (invisible at its
3369        // default opacity 0).
3370        let emerald = EMERALD.shade(500).opacity(0.5);
3371        same_with(
3372            s().shadow_lg().shadow_color(emerald),
3373            "shadow-lg shadow-emerald-500/50",
3374            &|s| s.view.shadow.color = emerald.into(),
3375        );
3376        same_with(
3377            s().shadow_xl().shadow_color(SKY.shade(500)),
3378            "shadow-xl shadow-sky-500",
3379            &|s| s.view.shadow.color = SKY.shade(500).into(),
3380        );
3381        same(s().inset_shadow_sm(), "inset-shadow-sm");
3382        same(
3383            s().ring(px(2.0))
3384                .ring_color(SKY.shade(500))
3385                .ring_offset(px(2.0)),
3386            "ring-2 ring-sky-500 ring-offset-2",
3387        );
3388        same(
3389            s().ring(px(1.0)).ring_color(rgba(0x0000_000d)).ring_inset(),
3390            "ring-1 ring-black/5 ring-inset",
3391        );
3392        same(s().text_shadow_md(), "text-shadow-md");
3393        // A theme color of the shadow switches with the appearance.
3394        let adaptive = s()
3395            .shadow_md()
3396            .shadow_color(AdaptiveColor::new(SKY.shade(500), PINK.shade(500)))
3397            .lower();
3398        assert_eq!(adaptive.deps(), tailwind::deps::DARK);
3399        for (dark, hue) in [(false, SKY), (true, PINK)] {
3400            let classes = format!("shadow-md shadow-{}-500", hue.name());
3401            assert_eq!(
3402                resolve(&adaptive, dark, 0, 0),
3403                resolve_with(&tailwind::parse(&PRESETS, &classes), dark, 0, 0, &|s| {
3404                    s.view.shadow.color = hue.shade(500).into()
3405                })
3406            );
3407        }
3408    }
3409
3410    #[test]
3411    fn custom_shadows_set_react_natives_and_box_shadows() {
3412        let list = s()
3413            .shadow_color(rgb(0x0969da))
3414            .shadow_opacity(0.35)
3415            .shadow_radius(px(10.0))
3416            .shadow_offset(point(px(4.0), px(8.0)))
3417            .text_shadow_color(rgba(0x0000_0099))
3418            .text_shadow_radius(px(4.0))
3419            .text_shadow_offset(point(px(2.0), px(2.0)))
3420            .lower();
3421        let mut style = Style::default();
3422        list.apply(
3423            &Context {
3424                env: ClassEnvironment::default(),
3425                window: crate::geometry::size_pt(390.0, 844.0),
3426                rtl: false,
3427                states: 0,
3428                position: 0,
3429                group: &|_| 0,
3430            },
3431            &PRESETS,
3432            &mut style,
3433            &mut ClassProps::default(),
3434            |_| {},
3435        );
3436        assert_eq!(style.view.shadow.color, rgb(0x0969da).into());
3437        assert_eq!(style.view.shadow.opacity, 0.35);
3438        assert_eq!(style.view.shadow.radius, px(10.0));
3439        assert_eq!(
3440            (style.view.shadow.offset_x, style.view.shadow.offset_y),
3441            (px(4.0), px(8.0))
3442        );
3443        assert_eq!(style.text.shadow_color, Some(rgba(0x0000_0099).into()));
3444        assert_eq!(style.text.shadow_radius, Some(px(4.0)));
3445        assert_eq!(style.text.shadow_offset, Some(point(px(2.0), px(2.0))));
3446        let layer = BoxShadow {
3447            offset_x: px(0.0),
3448            offset_y: px(2.0),
3449            blur: px(4.0),
3450            spread: px(0.0),
3451            color: rgba(0x0000_000d).into(),
3452            inset: true,
3453        };
3454        same(
3455            s().shadow([layer]),
3456            "shadow-[inset_0_2px_4px_rgb(0_0_0/0.05)]",
3457        );
3458    }
3459
3460    #[test]
3461    fn effects_are_tailwinds() {
3462        same(
3463            s().bg_linear_to_br()
3464                .gradient_from(VIOLET.shade(500))
3465                .gradient_via(PINK.shade(500))
3466                .gradient_to(RED.shade(400)),
3467            "bg-linear-to-br from-violet-500 via-pink-500 to-red-400",
3468        );
3469        same(
3470            s().bg_linear(deg(45.0))
3471                .gradient_from(SKY.shade(400))
3472                .gradient_to(VIOLET.shade(600))
3473                .gradient_to_position(percentage(0.8)),
3474            "bg-linear-45 from-sky-400 to-violet-600 to-80%",
3475        );
3476        same(
3477            s().bg_radial().gradient_from(SKY.shade(200)),
3478            "bg-radial from-sky-200",
3479        );
3480        same(
3481            s().bg_conic(deg(0.0)).gradient_from(RED.shade(500)),
3482            "bg-conic from-red-500",
3483        );
3484        same(s().grayscale(1.0).sepia(1.0), "grayscale sepia");
3485        same(s().blur(px(8.0)).brightness(0.5), "blur-sm brightness-50");
3486        same(
3487            s().saturate(1.5).hue_rotate(deg(90.0)),
3488            "saturate-150 hue-rotate-90",
3489        );
3490        same(
3491            s().backdrop_blur(px(12.0))
3492                .backdrop_saturate(1.5)
3493                .backdrop_sepia(1.0),
3494            "backdrop-blur-md backdrop-saturate-150 backdrop-sepia",
3495        );
3496        same(
3497            s().mix_blend_mode(BlendMode::Multiply),
3498            "mix-blend-multiply",
3499        );
3500        same(s().transition(), "transition");
3501        same(
3502            s().transition_colors()
3503                .duration(150.0)
3504                .ease_in_out()
3505                .delay(75.0),
3506            "transition-colors duration-150 ease-in-out delay-75",
3507        );
3508        same(
3509            s().transition_transform().duration(200.0),
3510            "transition-transform duration-200",
3511        );
3512        for (typed, classes) in [
3513            (s().animate_spin(), "animate-spin"),
3514            (s().animate_ping(), "animate-ping"),
3515            (s().animate_pulse(), "animate-pulse"),
3516            (s().animate_bounce(), "animate-bounce"),
3517        ] {
3518            same(typed, classes);
3519        }
3520    }
3521
3522    #[test]
3523    fn keyframe_animations_take_their_own_timing() {
3524        // As TS's `animationName` and its timing keys over no animation.
3525        let timed = |name: &'static str, ms: f32, easing: &'static str| {
3526            move |style: &mut Style| {
3527                use crate::StyleValue;
3528                style
3529                    .set_key(StyleKey::AnimationName, StyleValue::Str(name))
3530                    .unwrap();
3531                style
3532                    .set_key(StyleKey::AnimationDuration, StyleValue::Number(ms))
3533                    .unwrap();
3534                style
3535                    .set_key(StyleKey::AnimationTimingFunction, StyleValue::Str(easing))
3536                    .unwrap();
3537            }
3538        };
3539        same_with(
3540            s().animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0)),
3541            "animate-none",
3542            &timed("spin", 800.0, "linear"),
3543        );
3544        same_with(
3545            s().animation(
3546                KeyframeAnimation::new(Keyframes::Pulse)
3547                    .duration(900.0)
3548                    .easing([0.42, 0.0, 0.58, 1.0]),
3549            ),
3550            "animate-none",
3551            &timed("pulse", 900.0, "ease-in-out"),
3552        );
3553        // The later declaration wins, either way round.
3554        same(
3555            s().animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0))
3556                .animate_ping(),
3557            "animate-ping",
3558        );
3559        same_with(
3560            s().animate_ping()
3561                .animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0)),
3562            "animate-none",
3563            &timed("spin", 800.0, "linear"),
3564        );
3565    }
3566
3567    #[test]
3568    fn transforms_are_tailwinds() {
3569        same(
3570            s().rotate(deg(12.0)).skew_x(deg(6.0)).scale(0.9),
3571            "rotate-12 skew-x-6 scale-90",
3572        );
3573        same(
3574            s().perspective(px(400.0))
3575                .rotate_y(deg(35.0))
3576                .rotate_x(deg(40.0)),
3577            "perspective-[400px] rotate-y-35 rotate-x-40",
3578        );
3579        same(s().scale_x(1.5).skew_y(deg(-3.0)), "scale-x-150 -skew-y-3");
3580        same(
3581            s().origin_top_left().backface_hidden(),
3582            "origin-top-left backface-hidden",
3583        );
3584        same(
3585            s().transform_origin(TransformOrigin {
3586                x: px(10.0).into(),
3587                y: relative(0.25),
3588                z: Points::ZERO,
3589            }),
3590            "origin-[10px_25%]",
3591        );
3592    }
3593
3594    #[test]
3595    fn text_is_tailwinds() {
3596        same(
3597            s().underline()
3598                .text_decoration_wavy()
3599                .text_decoration_color(RED.shade(500))
3600                .text_decoration_thickness(px(2.0))
3601                .underline_offset(px(4.0)),
3602            "underline decoration-wavy decoration-red-500 decoration-2 underline-offset-4",
3603        );
3604        same(s().uppercase().tabular_nums(), "uppercase tabular-nums");
3605        same(s().small_caps().oldstyle_nums(), "small-caps oldstyle-nums");
3606        same(s().capitalize().text_justify(), "capitalize text-justify");
3607        same(s().align_baseline(), "align-baseline");
3608        same(s().align_text_top(), "align-text-top");
3609        same(s().align_text_bottom(), "align-text-bottom");
3610        same(s().align_middle(), "align-middle");
3611        // Unlike classes, the two lines add up.
3612        let both = s().underline().line_through().lower();
3613        let mut style = Style::default();
3614        let _ = style.set_key(
3615            StyleKey::TextDecorationLine,
3616            crate::StyleValue::Str("underline line-through"),
3617        );
3618        assert_eq!(
3619            resolve(&both, false, 0, 0),
3620            format!("{style:?} {:?}", ClassProps::default())
3621        );
3622        same(
3623            s().underline().line_through().no_underline(),
3624            "no-underline",
3625        );
3626        let rtl = s().writing_direction(WritingDirection::Rtl).lower();
3627        let mut style = Style::default();
3628        let _ = style.set_key(StyleKey::WritingDirection, crate::StyleValue::Str("rtl"));
3629        assert_eq!(
3630            resolve(&rtl, false, 0, 0),
3631            format!("{style:?} {:?}", ClassProps::default())
3632        );
3633    }
3634
3635    #[test]
3636    fn layout_is_tailwinds() {
3637        same(s().grid().grid_cols(3).gap_2(), "grid grid-cols-3 gap-2");
3638        same(s().col_span(2).row_span(2), "col-span-2 row-span-2");
3639        same(s().col_start(2).col_end(-1), "col-start-2 col-end-[-1]");
3640        same(s().flex_grow(2.0).flex_shrink(0.0), "grow-2 shrink-0");
3641        same(
3642            s().grid_rows(2).grid_flow_col(),
3643            "grid-rows-2 grid-flow-col",
3644        );
3645    }
3646
3647    #[test]
3648    fn variants_are_tailwinds() {
3649        same(
3650            s().group_active(|s| s.text_color(VIOLET.shade(600)).translate_x(px(4.0))),
3651            "group-active:text-violet-600 group-active:translate-x-1",
3652        );
3653        same(s().group(), "group");
3654        same(
3655            s().group_named("item")
3656                .group_hover_named("item", |s| s.opacity(0.5)),
3657            "group/item group-hover/item:opacity-50",
3658        );
3659        same(s().dark(|s| s.shadow_none()), "dark:shadow-none");
3660        let mut disabled = s();
3661        disabled.extend_as(Variant::DISABLED, s().opacity(0.4));
3662        same(disabled, "disabled:opacity-40");
3663        // Nested variants: both hold.
3664        let mut nested = s();
3665        nested.extend_as(Variant::ACTIVE, s().dark(|s| s.opacity(0.5)));
3666        same(nested, "dark:active:opacity-50");
3667    }
3668}