Skip to main content

nsh_core/element/
style.rs

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