use std::{
hash::{Hash, Hasher},
sync::{Arc, LazyLock},
};
use super::SharedString;
use crate::{
BlendMode, BoxShadow, FontVariant, TransformOrigin, TransitionProps,
effects::{Filter, GradientKind, GradientSize, KeyframeAnimation, Keyframes},
style::{Color, OriginLen, PatchValue, StyleDecl, StyleKey},
tailwind::{self, ClassList, Decl, Part, Rule, rank, state},
transform::TransformKind,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Length {
Points(f32),
Relative(f32),
Auto,
}
impl Eq for Length {}
impl Hash for Length {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Length::Points(p) => (0u8, p.to_bits()).hash(state),
Length::Relative(f) => (1u8, f.to_bits()).hash(state),
Length::Auto => 2u8.hash(state),
}
}
}
pub const fn px(points: f32) -> Length {
Length::Points(points)
}
pub const fn relative(fraction: f32) -> Length {
Length::Relative(fraction)
}
impl Length {
fn patch(self) -> PatchValue {
match self {
Length::Points(p) => PatchValue::Number(p),
Length::Relative(f) => PatchValue::Str(format!("{}%", f * 100.0).into()),
Length::Auto => PatchValue::Str("auto".into()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FontWeight(pub u16);
impl FontWeight {
pub const THIN: Self = Self(100);
pub const EXTRA_LIGHT: Self = Self(200);
pub const LIGHT: Self = Self(300);
pub const NORMAL: Self = Self(400);
pub const MEDIUM: Self = Self(500);
pub const SEMIBOLD: Self = Self(600);
pub const BOLD: Self = Self(700);
pub const EXTRA_BOLD: Self = Self(800);
pub const BLACK: Self = Self(900);
}
pub const fn rgb(hex: u32) -> Color {
Color(hex << 8 | 0xff)
}
pub const fn rgba(hex: u32) -> Color {
Color(hex)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct AdaptiveColor {
pub light: Color,
pub dark: Color,
}
impl AdaptiveColor {
pub const TRANSPARENT: Self = Self {
light: Color::TRANSPARENT,
dark: Color::TRANSPARENT,
};
pub const fn new(light: Color, dark: Color) -> Self {
Self { light, dark }
}
pub fn opacity(self, opacity: f32) -> Self {
let fade = |c: Color| {
let a = ((c.0 & 0xff) as f32 * opacity.clamp(0.0, 1.0)).round() as u32;
Color(c.0 & !0xff | a)
};
Self {
light: fade(self.light),
dark: fade(self.dark),
}
}
}
impl From<Color> for AdaptiveColor {
fn from(c: Color) -> Self {
Self { light: c, dark: c }
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Bits(f32);
impl PartialEq for Bits {
fn eq(&self, other: &Self) -> bool {
self.0.to_bits() == other.0.to_bits()
}
}
impl Eq for Bits {}
impl Hash for Bits {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub(crate) struct Variant {
states: u8,
group_states: u8,
group: u8,
dark: bool,
}
impl Variant {
pub(crate) const HOVER: Self = Self::states(state::HOVERED);
pub(crate) const FOCUS: Self = Self::states(state::FOCUSED);
pub(crate) const ACTIVE: Self = Self::states(state::PRESSED);
pub(crate) const DISABLED: Self = Self::states(state::DISABLED);
const DARK: Self = Self {
states: 0,
group_states: 0,
group: 0,
dark: true,
};
const fn states(states: u8) -> Self {
Self {
states,
group_states: 0,
group: 0,
dark: false,
}
}
fn within(self, outer: Variant) -> Variant {
let (group, group_states) = match (outer.group_states, self.group_states) {
(0, _) => (self.group, self.group_states),
(o, i) if i != 0 && outer.group == self.group => (outer.group, o | i),
(o, _) => (outer.group, o),
};
Variant {
states: self.states | outer.states,
group_states,
group,
dark: self.dark || outer.dark,
}
}
fn rank(self) -> u16 {
let mut r = 0;
if self.group_states != 0 {
r = rank::GROUP;
}
for (bit, rank) in [
(state::HOVERED, rank::HOVER),
(state::FOCUSED, rank::FOCUS),
(state::PRESSED, rank::ACTIVE),
(state::DISABLED, rank::DISABLED),
] {
if self.states & bit != 0 {
r = r.max(rank);
}
}
if self.dark {
r = r.max(rank::DARK);
}
r
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum ColorPart {
Shadow,
InsetShadow,
TextShadow,
Ring,
RingOffset,
InsetRing,
From,
Via,
To,
}
impl ColorPart {
fn part(self, c: Color) -> Part {
let own = c.0 & 0xff != 0xff;
match self {
ColorPart::Shadow => Part::ShadowColor(c, own),
ColorPart::InsetShadow => Part::InsetShadowColor(c, own),
ColorPart::TextShadow => Part::TextShadowColor(c, own),
ColorPart::Ring => Part::RingColor(c),
ColorPart::RingOffset => Part::RingOffsetColor(c),
ColorPart::InsetRing => Part::InsetRingColor(c),
ColorPart::From => Part::From(c),
ColorPart::Via => Part::Via(c),
ColorPart::To => Part::To(c),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum GradientShape {
Linear(Bits),
Corner { right: bool, bottom: bool },
Radial,
Conic(Bits),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum FilterFn {
Blur,
Brightness,
Contrast,
Grayscale,
HueRotate,
Invert,
Opacity,
Saturate,
Sepia,
}
impl FilterFn {
fn part(self, backdrop: bool, amount: f32) -> Part {
let (slot, filter) = match self {
FilterFn::Blur => (0, Filter::Blur(amount)),
FilterFn::Brightness => (1, Filter::Brightness(amount)),
FilterFn::Contrast => (2, Filter::Contrast(amount)),
FilterFn::Grayscale => (3, Filter::Grayscale(amount)),
FilterFn::HueRotate => (4, Filter::HueRotate(amount)),
FilterFn::Invert => (5, Filter::Invert(amount)),
FilterFn::Opacity => (6, Filter::Opacity(amount)),
FilterFn::Saturate => (6 + u8::from(backdrop), Filter::Saturate(amount)),
FilterFn::Sepia => (7 + u8::from(backdrop), Filter::Sepia(amount)),
};
Part::Filter {
backdrop,
slot,
filter: Some(filter),
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct Layers(Arc<[BoxShadow]>);
impl Layers {
fn bits(&self) -> impl Iterator<Item = (u32, u32, u32, u32, u32, bool)> + '_ {
self.0.iter().map(|l| {
(
l.offset_x.to_bits(),
l.offset_y.to_bits(),
l.blur.to_bits(),
l.spread.to_bits(),
l.color.0,
l.inset,
)
})
}
}
impl PartialEq for Layers {
fn eq(&self, other: &Self) -> bool {
self.0.len() == other.0.len() && self.bits().eq(other.bits())
}
}
impl Eq for Layers {}
impl Hash for Layers {
fn hash<H: Hasher>(&self, state: &mut H) {
for l in self.bits() {
l.hash(state);
}
}
}
const UNDERLINE: u8 = 1;
const LINE_THROUGH: u8 = 2;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Declaration {
Number(StyleKey, Bits),
Length(StyleKey, Length),
Keyword(StyleKey, &'static str),
Str(StyleKey, SharedString),
Color(StyleKey, AdaptiveColor),
TextPreset(&'static str),
Shadow(&'static str),
InsetShadow(&'static str),
TextShadow(&'static str),
Shadows(Layers),
PartColor(ColorPart, AdaptiveColor),
Ring(Bits),
RingOffset(Bits),
RingInset,
InsetRing(Bits),
ShadowOffset(Bits, Bits),
TextShadowOffset(Bits, Bits),
Transform(TransformKind, Bits),
TransformNone,
Origin([(bool, Bits); 2]),
Gradient(GradientShape),
GradientNone,
StopPosition(u8, Bits),
Filter(bool, FilterFn, Bits),
FilterNone(bool),
FontVariant {
set: u8,
clear: u8,
},
Decoration(u8),
Transition(u8),
TransitionNone,
Duration(Bits),
Delay(Bits),
Ease([Bits; 4]),
EasePreset(&'static str),
Animate(Option<u8>),
Animation(u8, Bits, Bits, [Bits; 4], Option<u32>),
Tracks(StyleKey, u16),
Span(StyleKey, u16),
Group(&'static str),
}
static PRESETS: LazyLock<tailwind::Theme> = LazyLock::new(tailwind::Theme::default);
fn color_patch(c: Color) -> PatchValue {
PatchValue::Str(format!("#{:08x}", c.0).into())
}
fn shadow_preset(layers: Option<&Vec<BoxShadow>>) -> Arc<[BoxShadow]> {
layers.map_or_else(|| Arc::from([]), |l| Arc::from(l.as_slice()))
}
const KEYFRAMES: [Keyframes; 4] = [
Keyframes::Spin,
Keyframes::Ping,
Keyframes::Pulse,
Keyframes::Bounce,
];
impl Declaration {
fn lower(&self, out: &mut Vec<Decl>) {
let part = |out: &mut Vec<Decl>, p: Part| out.push(Decl::Part(p));
match self {
Declaration::Number(key, n) => out.push(Decl::Set(*key, PatchValue::Number(n.0))),
Declaration::Length(key, l) => out.push(Decl::Set(*key, l.patch())),
Declaration::Keyword(key, k) => out.push(Decl::Set(*key, PatchValue::Str((*k).into()))),
Declaration::Str(key, s) => {
out.push(Decl::Set(*key, PatchValue::Str(s.as_str().into())))
}
Declaration::Color(key, c) => out.push(if c.light == c.dark {
Decl::Set(*key, color_patch(c.light))
} else {
Decl::Adaptive(*key, [color_patch(c.light), color_patch(c.dark)])
}),
Declaration::TextPreset(name) => {
if let Some(&(size, line)) = PRESETS.text.get(*name) {
out.push(Decl::Set(StyleKey::FontSize, PatchValue::Number(size)));
if let Some(m) = line {
out.push(Decl::Set(
StyleKey::LineHeight,
PatchValue::Str(m.to_string().into()),
));
}
}
}
Declaration::Shadow(name) => {
part(out, Part::Shadow(shadow_preset(PRESETS.shadows.get(*name))))
}
Declaration::InsetShadow(name) => part(
out,
Part::InsetShadow(shadow_preset(PRESETS.inset_shadows.get(*name))),
),
Declaration::TextShadow(name) => {
let layers = PRESETS.text_shadows.get(*name);
part(
out,
Part::TextShadow(
layers.map_or_else(|| Arc::from([]), |l| Arc::from(l.as_slice())),
),
)
}
Declaration::Shadows(layers) => part(out, Part::Shadow(layers.0.clone())),
Declaration::PartColor(which, c) => out.push(if c.light == c.dark {
Decl::Part(which.part(c.light))
} else {
Decl::AdaptivePart(Box::new([which.part(c.light), which.part(c.dark)]))
}),
Declaration::Ring(w) => part(out, Part::Ring(w.0)),
Declaration::RingOffset(w) => part(out, Part::RingOffset(w.0)),
Declaration::RingInset => part(out, Part::RingInset),
Declaration::InsetRing(w) => part(out, Part::InsetRing(w.0)),
Declaration::ShadowOffset(x, y) => {
out.push(Decl::Style(StyleDecl::ShadowOffset(Some((x.0, y.0)))))
}
Declaration::TextShadowOffset(x, y) => {
out.push(Decl::Style(StyleDecl::TextShadowOffset(Some((x.0, y.0)))))
}
Declaration::Transform(kind, v) => {
let v = v.0;
let parts: &[Part] = match kind {
TransformKind::Scale => &[Part::ScaleX(v), Part::ScaleY(v)],
TransformKind::ScaleX => &[Part::ScaleX(v)],
TransformKind::ScaleY => &[Part::ScaleY(v)],
TransformKind::TranslateX => &[Part::TranslateX(tailwind::Len::Points(v))],
TransformKind::TranslateY => &[Part::TranslateY(tailwind::Len::Points(v))],
TransformKind::TranslateXFraction => {
&[Part::TranslateX(tailwind::Len::Fraction(v))]
}
TransformKind::TranslateYFraction => {
&[Part::TranslateY(tailwind::Len::Fraction(v))]
}
TransformKind::Rotate => &[Part::Rotate(v)],
TransformKind::RotateX => &[Part::RotateX(v)],
TransformKind::RotateY => &[Part::RotateY(v)],
TransformKind::SkewX => &[Part::SkewX(v)],
TransformKind::SkewY => &[Part::SkewY(v)],
TransformKind::Perspective => &[Part::Perspective(v)],
};
out.extend(parts.iter().cloned().map(Decl::Part));
}
Declaration::TransformNone => part(out, Part::TransformNone),
Declaration::Origin(axes) => {
let [x, y] = axes.map(|(fraction, v)| {
if fraction {
format!("{}%", v.0 * 100.0)
} else {
format!("{}px", v.0)
}
});
out.push(Decl::Set(
StyleKey::TransformOrigin,
PatchValue::Str(format!("{x} {y}").into()),
));
}
Declaration::Gradient(shape) => part(
out,
Part::Gradient(match *shape {
GradientShape::Linear(angle) => GradientKind::Linear { angle: angle.0 },
GradientShape::Corner { right, bottom } => {
GradientKind::LinearCorner { right, bottom }
}
GradientShape::Radial => GradientKind::Radial {
circle: false,
size: GradientSize::FarthestCorner,
x: 0.5,
y: 0.5,
},
GradientShape::Conic(from) => GradientKind::Conic {
from: from.0,
x: 0.5,
y: 0.5,
},
}),
),
Declaration::GradientNone => part(out, Part::GradientNone),
Declaration::StopPosition(i, at) => part(
out,
match i {
0 => Part::FromPos(at.0),
1 => Part::ViaPos(at.0),
_ => Part::ToPos(at.0),
},
),
Declaration::Filter(backdrop, f, amount) => part(out, f.part(*backdrop, amount.0)),
Declaration::FilterNone(backdrop) => part(
out,
Part::FilterNone {
backdrop: *backdrop,
},
),
Declaration::FontVariant { set, clear } => part(
out,
Part::FontVariant {
set: *set,
clear: *clear,
},
),
Declaration::Decoration(bits) => out.push(Decl::Set(
StyleKey::TextDecorationLine,
PatchValue::Str(
match *bits {
0 => "none",
UNDERLINE => "underline",
LINE_THROUGH => "line-through",
_ => "underline line-through",
}
.into(),
),
)),
Declaration::Transition(props) => part(out, Part::TransitionProps(*props)),
Declaration::TransitionNone => part(out, Part::TransitionNone),
Declaration::Duration(ms) => part(out, Part::Duration(ms.0)),
Declaration::Delay(ms) => part(out, Part::Delay(ms.0)),
Declaration::Ease(curve) => part(out, Part::Ease(curve.map(|b| b.0))),
Declaration::EasePreset(name) => {
if let Some(curve) = PRESETS.ease.get(*name) {
part(out, Part::Ease(*curve));
}
}
Declaration::Animate(k) => part(out, Part::Animate(k.map(|i| KEYFRAMES[i as usize]))),
Declaration::Animation(k, duration, delay, easing, iterations) => part(
out,
Part::Animation(KeyframeAnimation {
keyframes: KEYFRAMES[*k as usize],
duration: duration.0,
delay: delay.0,
easing: easing.map(|b| b.0),
iterations: *iterations,
}),
),
Declaration::Tracks(key, n) => out.push(Decl::Set(
*key,
PatchValue::Str(format!("repeat({n}, minmax(0, 1fr))").into()),
)),
Declaration::Span(key, n) => out.push(Decl::Set(
*key,
PatchValue::Str(format!("span {n} / span {n}").into()),
)),
Declaration::Group(_) => {}
}
}
}
type Entries = Vec<(Variant, Declaration)>;
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct StyleRefinement {
entries: Entries,
names: Vec<&'static str>,
}
impl StyleRefinement {
pub(crate) fn push(&mut self, decl: Declaration) {
if self.entries.capacity() == 0 {
self.entries.reserve(8);
}
self.entries.push((Variant::default(), decl));
}
pub(crate) fn lengths(&mut self, keys: &[StyleKey], length: Length) {
for key in keys {
self.push(Declaration::Length(*key, length));
}
}
pub(crate) fn number(&mut self, key: StyleKey, n: f32) {
self.push(Declaration::Number(key, Bits(n)));
}
pub(crate) fn numbers(&mut self, keys: &[StyleKey], n: f32) {
for key in keys {
self.number(*key, n);
}
}
pub(crate) fn keyword(&mut self, key: StyleKey, k: &'static str) {
self.push(Declaration::Keyword(key, k));
}
pub(crate) fn color(&mut self, keys: &[StyleKey], color: AdaptiveColor) {
for key in keys {
self.push(Declaration::Color(*key, color));
}
}
pub(crate) fn extend_as(&mut self, variant: Variant, other: StyleRefinement) {
for (mut v, d) in other.entries {
if v.group != 0 {
v.group = self.name(other.names[v.group as usize - 1]);
}
self.entries.push((v.within(variant), d));
}
}
fn name(&mut self, name: &'static str) -> u8 {
if name.is_empty() {
return 0;
}
let at = match self.names.iter().position(|n| *n == name) {
Some(at) => at,
None => {
self.names.push(name);
self.names.len() - 1
}
};
u8::try_from(at + 1).expect("fewer than 255 group names")
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub(crate) fn lower(&self) -> ClassList {
let mut variants: Vec<Variant> = Vec::new();
let mut groups: Vec<Box<str>> = Vec::new();
for (v, d) in &self.entries {
if let Declaration::Group(name) = d {
if !groups.iter().any(|g| **g == **name) {
groups.push((*name).into());
}
} else if !variants.contains(v) {
variants.push(*v);
}
}
let mut rules = Vec::with_capacity(variants.len());
for variant in variants {
let mut decls = Vec::new();
let mut decoration = 0;
for (v, d) in &self.entries {
if *v != variant {
continue;
}
if let Declaration::Decoration(bits) = d {
decoration = if *bits == 0 { 0 } else { decoration | bits };
Declaration::Decoration(decoration).lower(&mut decls);
} else {
d.lower(&mut decls);
}
}
if !decls.is_empty() {
let group = (variant.group_states != 0).then(|| {
let name = match variant.group {
0 => "",
g => self.names[g as usize - 1],
};
(name, variant.group_states)
});
rules.push(Rule::with(
variant.states,
group,
variant.dark,
variant.rank(),
decls,
));
}
}
ClassList::from_rules(rules, groups)
}
}
fn font_variant<S: Styled>(mut s: S, set: u8, clear: u8) -> S {
s.style().push(Declaration::FontVariant { set, clear });
s
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum WritingDirection {
#[default]
Auto,
Ltr,
Rtl,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum BorderCurve {
#[default]
Circular,
Continuous,
}
pub trait Styled: Sized {
fn style(&mut self) -> &mut StyleRefinement;
nsh_macros::style_helpers! {
p => [Padding],
px => [PaddingHorizontal],
py => [PaddingVertical],
pt => [PaddingTop],
pr => [PaddingRight],
pb => [PaddingBottom],
pl => [PaddingLeft],
ps => [PaddingStart],
pe => [PaddingEnd],
m => [Margin],
mx => [MarginHorizontal],
my => [MarginVertical],
mt => [MarginTop],
mr => [MarginRight],
mb => [MarginBottom],
ml => [MarginLeft],
ms => [MarginStart],
me => [MarginEnd],
gap => [Gap],
gap_x => [ColumnGap],
gap_y => [RowGap],
w => [Width],
h => [Height],
size => [Width, Height],
min_w => [MinWidth],
min_h => [MinHeight],
max_w => [MaxWidth],
max_h => [MaxHeight],
top => [Top],
right => [Right],
bottom => [Bottom],
left => [Left],
inset => [Top, Right, Bottom, Left],
basis => [FlexBasis],
}
fn flex(mut self) -> Self {
self.style().keyword(StyleKey::Display, "flex");
self
}
fn grid(mut self) -> Self {
self.style().keyword(StyleKey::Display, "grid");
self
}
fn grid_cols(mut self, count: u16) -> Self {
self.style()
.push(Declaration::Tracks(StyleKey::GridTemplateColumns, count));
self
}
fn grid_rows(mut self, count: u16) -> Self {
self.style()
.push(Declaration::Tracks(StyleKey::GridTemplateRows, count));
self
}
fn grid_template_columns(mut self, tracks: impl Into<SharedString>) -> Self {
self.style().push(Declaration::Str(
StyleKey::GridTemplateColumns,
tracks.into(),
));
self
}
fn grid_template_rows(mut self, tracks: impl Into<SharedString>) -> Self {
self.style()
.push(Declaration::Str(StyleKey::GridTemplateRows, tracks.into()));
self
}
fn grid_flow_col(mut self) -> Self {
self.style().keyword(StyleKey::GridAutoFlow, "column");
self
}
fn grid_flow_dense(mut self) -> Self {
self.style().keyword(StyleKey::GridAutoFlow, "row dense");
self
}
fn col_span(mut self, count: u16) -> Self {
self.style()
.push(Declaration::Span(StyleKey::GridColumn, count));
self
}
fn row_span(mut self, count: u16) -> Self {
self.style()
.push(Declaration::Span(StyleKey::GridRow, count));
self
}
fn col_span_full(mut self) -> Self {
self.style().keyword(StyleKey::GridColumn, "1 / -1");
self
}
fn row_span_full(mut self) -> Self {
self.style().keyword(StyleKey::GridRow, "1 / -1");
self
}
fn col_start(mut self, line: i16) -> Self {
self.style()
.number(StyleKey::GridColumnStart, f32::from(line));
self
}
fn col_end(mut self, line: i16) -> Self {
self.style()
.number(StyleKey::GridColumnEnd, f32::from(line));
self
}
fn row_start(mut self, line: i16) -> Self {
self.style().number(StyleKey::GridRowStart, f32::from(line));
self
}
fn row_end(mut self, line: i16) -> Self {
self.style().number(StyleKey::GridRowEnd, f32::from(line));
self
}
fn hidden(mut self) -> Self {
self.style().keyword(StyleKey::Display, "none");
self
}
fn flex_row(mut self) -> Self {
self.style().keyword(StyleKey::FlexDirection, "row");
self
}
fn flex_row_reverse(mut self) -> Self {
self.style().keyword(StyleKey::FlexDirection, "row-reverse");
self
}
fn flex_col(mut self) -> Self {
self.style().keyword(StyleKey::FlexDirection, "column");
self
}
fn flex_col_reverse(mut self) -> Self {
self.style()
.keyword(StyleKey::FlexDirection, "column-reverse");
self
}
fn flex_wrap(mut self) -> Self {
self.style().keyword(StyleKey::FlexWrap, "wrap");
self
}
fn flex_1(mut self) -> Self {
let s = self.style();
s.number(StyleKey::FlexGrow, 1.0);
s.number(StyleKey::FlexShrink, 1.0);
s.lengths(&[StyleKey::FlexBasis], px(0.0));
self
}
fn flex_auto(mut self) -> Self {
let s = self.style();
s.number(StyleKey::FlexGrow, 1.0);
s.number(StyleKey::FlexShrink, 1.0);
s.lengths(&[StyleKey::FlexBasis], Length::Auto);
self
}
fn flex_none(mut self) -> Self {
let s = self.style();
s.number(StyleKey::FlexGrow, 0.0);
s.number(StyleKey::FlexShrink, 0.0);
self
}
fn flex_grow(mut self, factor: f32) -> Self {
self.style().number(StyleKey::FlexGrow, factor);
self
}
fn flex_shrink(mut self, factor: f32) -> Self {
self.style().number(StyleKey::FlexShrink, factor);
self
}
fn flex_shrink_0(mut self) -> Self {
self.style().number(StyleKey::FlexShrink, 0.0);
self
}
fn items_start(mut self) -> Self {
self.style().keyword(StyleKey::AlignItems, "flex-start");
self
}
fn items_center(mut self) -> Self {
self.style().keyword(StyleKey::AlignItems, "center");
self
}
fn items_end(mut self) -> Self {
self.style().keyword(StyleKey::AlignItems, "flex-end");
self
}
fn items_stretch(mut self) -> Self {
self.style().keyword(StyleKey::AlignItems, "stretch");
self
}
fn items_baseline(mut self) -> Self {
self.style().keyword(StyleKey::AlignItems, "baseline");
self
}
fn justify_start(mut self) -> Self {
self.style().keyword(StyleKey::JustifyContent, "flex-start");
self
}
fn justify_center(mut self) -> Self {
self.style().keyword(StyleKey::JustifyContent, "center");
self
}
fn justify_end(mut self) -> Self {
self.style().keyword(StyleKey::JustifyContent, "flex-end");
self
}
fn justify_between(mut self) -> Self {
self.style()
.keyword(StyleKey::JustifyContent, "space-between");
self
}
fn justify_around(mut self) -> Self {
self.style()
.keyword(StyleKey::JustifyContent, "space-around");
self
}
fn justify_evenly(mut self) -> Self {
self.style()
.keyword(StyleKey::JustifyContent, "space-evenly");
self
}
fn self_start(mut self) -> Self {
self.style().keyword(StyleKey::AlignSelf, "flex-start");
self
}
fn self_center(mut self) -> Self {
self.style().keyword(StyleKey::AlignSelf, "center");
self
}
fn self_end(mut self) -> Self {
self.style().keyword(StyleKey::AlignSelf, "flex-end");
self
}
fn self_stretch(mut self) -> Self {
self.style().keyword(StyleKey::AlignSelf, "stretch");
self
}
fn w_full(self) -> Self {
self.w(relative(1.0))
}
fn h_full(self) -> Self {
self.h(relative(1.0))
}
fn size_full(self) -> Self {
self.size(relative(1.0))
}
fn aspect_ratio(mut self, ratio: f32) -> Self {
self.style().number(StyleKey::AspectRatio, ratio);
self
}
fn aspect_square(self) -> Self {
self.aspect_ratio(1.0)
}
fn relative(mut self) -> Self {
self.style().keyword(StyleKey::Position, "relative");
self
}
fn absolute(mut self) -> Self {
self.style().keyword(StyleKey::Position, "absolute");
self
}
fn overflow_hidden(mut self) -> Self {
self.style().keyword(StyleKey::Overflow, "hidden");
self
}
fn z_index(mut self, z: i32) -> Self {
self.style().number(StyleKey::ZIndex, z as f32);
self
}
fn bg(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.color(&[StyleKey::BackgroundColor], color.into());
self
}
fn opacity(mut self, opacity: f32) -> Self {
self.style()
.number(StyleKey::Opacity, opacity.clamp(0.0, 1.0));
self
}
fn rounded(mut self, radius: impl Into<Length>) -> Self {
self.style()
.lengths(&[StyleKey::BorderRadius], radius.into());
self
}
fn rounded_none(self) -> Self {
self.rounded(px(0.0))
}
fn rounded_xs(self) -> Self {
self.rounded(px(2.0))
}
fn rounded_sm(self) -> Self {
self.rounded(px(4.0))
}
fn rounded_md(self) -> Self {
self.rounded(px(6.0))
}
fn rounded_lg(self) -> Self {
self.rounded(px(8.0))
}
fn rounded_xl(self) -> Self {
self.rounded(px(12.0))
}
fn rounded_2xl(self) -> Self {
self.rounded(px(16.0))
}
fn rounded_3xl(self) -> Self {
self.rounded(px(24.0))
}
fn rounded_full(self) -> Self {
self.rounded(px(9999.0))
}
fn rounded_t(mut self, radius: impl Into<Length>) -> Self {
self.style().lengths(
&[
StyleKey::BorderTopLeftRadius,
StyleKey::BorderTopRightRadius,
],
radius.into(),
);
self
}
fn rounded_b(mut self, radius: impl Into<Length>) -> Self {
self.style().lengths(
&[
StyleKey::BorderBottomLeftRadius,
StyleKey::BorderBottomRightRadius,
],
radius.into(),
);
self
}
fn border(mut self, width: f32) -> Self {
self.style().number(StyleKey::BorderWidth, width);
self
}
fn border_1(self) -> Self {
self.border(1.0)
}
fn border_2(self) -> Self {
self.border(2.0)
}
fn border_t_1(mut self) -> Self {
self.style().number(StyleKey::BorderTopWidth, 1.0);
self
}
fn border_b_1(mut self) -> Self {
self.style().number(StyleKey::BorderBottomWidth, 1.0);
self
}
fn border_l_1(mut self) -> Self {
self.style().number(StyleKey::BorderLeftWidth, 1.0);
self
}
fn border_r_1(mut self) -> Self {
self.style().number(StyleKey::BorderRightWidth, 1.0);
self
}
fn border_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style().color(&[StyleKey::BorderColor], color.into());
self
}
fn border_t(mut self, width: f32) -> Self {
self.style().number(StyleKey::BorderTopWidth, width);
self
}
fn border_r(mut self, width: f32) -> Self {
self.style().number(StyleKey::BorderRightWidth, width);
self
}
fn border_b(mut self, width: f32) -> Self {
self.style().number(StyleKey::BorderBottomWidth, width);
self
}
fn border_l(mut self, width: f32) -> Self {
self.style().number(StyleKey::BorderLeftWidth, width);
self
}
fn border_x(mut self, width: f32) -> Self {
self.style().numbers(
&[StyleKey::BorderLeftWidth, StyleKey::BorderRightWidth],
width,
);
self
}
fn border_y(mut self, width: f32) -> Self {
self.style().numbers(
&[StyleKey::BorderTopWidth, StyleKey::BorderBottomWidth],
width,
);
self
}
fn border_s(mut self, width: f32) -> Self {
self.style().number(StyleKey::BorderStartWidth, width);
self
}
fn border_e(mut self, width: f32) -> Self {
self.style().number(StyleKey::BorderEndWidth, width);
self
}
fn border_t_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.color(&[StyleKey::BorderTopColor], color.into());
self
}
fn border_r_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.color(&[StyleKey::BorderRightColor], color.into());
self
}
fn border_b_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.color(&[StyleKey::BorderBottomColor], color.into());
self
}
fn border_l_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.color(&[StyleKey::BorderLeftColor], color.into());
self
}
fn border_x_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style().color(
&[StyleKey::BorderLeftColor, StyleKey::BorderRightColor],
color.into(),
);
self
}
fn border_y_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style().color(
&[StyleKey::BorderTopColor, StyleKey::BorderBottomColor],
color.into(),
);
self
}
fn border_s_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.color(&[StyleKey::BorderStartColor], color.into());
self
}
fn border_e_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.color(&[StyleKey::BorderEndColor], color.into());
self
}
fn border_solid(mut self) -> Self {
self.style().keyword(StyleKey::BorderStyle, "solid");
self
}
fn border_dashed(mut self) -> Self {
self.style().keyword(StyleKey::BorderStyle, "dashed");
self
}
fn border_dotted(mut self) -> Self {
self.style().keyword(StyleKey::BorderStyle, "dotted");
self
}
fn border_curve(mut self, curve: BorderCurve) -> Self {
self.style().keyword(
StyleKey::BorderCurve,
match curve {
BorderCurve::Circular => "circular",
BorderCurve::Continuous => "continuous",
},
);
self
}
fn rounded_tl(mut self, radius: impl Into<Length>) -> Self {
self.style()
.lengths(&[StyleKey::BorderTopLeftRadius], radius.into());
self
}
fn rounded_tr(mut self, radius: impl Into<Length>) -> Self {
self.style()
.lengths(&[StyleKey::BorderTopRightRadius], radius.into());
self
}
fn rounded_br(mut self, radius: impl Into<Length>) -> Self {
self.style()
.lengths(&[StyleKey::BorderBottomRightRadius], radius.into());
self
}
fn rounded_bl(mut self, radius: impl Into<Length>) -> Self {
self.style()
.lengths(&[StyleKey::BorderBottomLeftRadius], radius.into());
self
}
fn rounded_l(mut self, radius: impl Into<Length>) -> Self {
self.style().lengths(
&[
StyleKey::BorderTopLeftRadius,
StyleKey::BorderBottomLeftRadius,
],
radius.into(),
);
self
}
fn rounded_r(mut self, radius: impl Into<Length>) -> Self {
self.style().lengths(
&[
StyleKey::BorderTopRightRadius,
StyleKey::BorderBottomRightRadius,
],
radius.into(),
);
self
}
fn rounded_ss(mut self, radius: impl Into<Length>) -> Self {
self.style()
.lengths(&[StyleKey::BorderTopStartRadius], radius.into());
self
}
fn rounded_se(mut self, radius: impl Into<Length>) -> Self {
self.style()
.lengths(&[StyleKey::BorderTopEndRadius], radius.into());
self
}
fn rounded_ee(mut self, radius: impl Into<Length>) -> Self {
self.style()
.lengths(&[StyleKey::BorderBottomEndRadius], radius.into());
self
}
fn rounded_es(mut self, radius: impl Into<Length>) -> Self {
self.style()
.lengths(&[StyleKey::BorderBottomStartRadius], radius.into());
self
}
fn rounded_s(mut self, radius: impl Into<Length>) -> Self {
self.style().lengths(
&[
StyleKey::BorderTopStartRadius,
StyleKey::BorderBottomStartRadius,
],
radius.into(),
);
self
}
fn rounded_e(mut self, radius: impl Into<Length>) -> Self {
self.style().lengths(
&[
StyleKey::BorderTopEndRadius,
StyleKey::BorderBottomEndRadius,
],
radius.into(),
);
self
}
fn outline(mut self, width: f32) -> Self {
let s = self.style();
s.number(StyleKey::OutlineWidth, width);
s.keyword(StyleKey::OutlineStyle, "solid");
self
}
fn outline_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style().color(&[StyleKey::OutlineColor], color.into());
self
}
fn outline_offset(mut self, points: f32) -> Self {
self.style().number(StyleKey::OutlineOffset, points);
self
}
fn outline_dashed(mut self) -> Self {
self.style().keyword(StyleKey::OutlineStyle, "dashed");
self
}
fn outline_dotted(mut self) -> Self {
self.style().keyword(StyleKey::OutlineStyle, "dotted");
self
}
fn outline_none(mut self) -> Self {
self.style().keyword(StyleKey::OutlineStyle, "none");
self
}
fn shadow_none(mut self) -> Self {
self.style().push(Declaration::Shadow("none"));
self
}
fn shadow_2xs(mut self) -> Self {
self.style().push(Declaration::Shadow("2xs"));
self
}
fn shadow_xs(mut self) -> Self {
self.style().push(Declaration::Shadow("xs"));
self
}
fn shadow_sm(mut self) -> Self {
self.style().push(Declaration::Shadow("sm"));
self
}
fn shadow_md(mut self) -> Self {
self.style().push(Declaration::Shadow("md"));
self
}
fn shadow_lg(mut self) -> Self {
self.style().push(Declaration::Shadow("lg"));
self
}
fn shadow_xl(mut self) -> Self {
self.style().push(Declaration::Shadow("xl"));
self
}
fn shadow_2xl(mut self) -> Self {
self.style().push(Declaration::Shadow("2xl"));
self
}
fn shadow(mut self, layers: impl IntoIterator<Item = BoxShadow>) -> Self {
let layers: Arc<[BoxShadow]> = layers.into_iter().collect();
self.style().push(Declaration::Shadows(Layers(layers)));
self
}
fn shadow_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
let color = color.into();
let s = self.style();
s.color(&[StyleKey::ShadowColor], color);
s.push(Declaration::PartColor(ColorPart::Shadow, color));
self
}
fn shadow_opacity(mut self, opacity: f32) -> Self {
self.style()
.number(StyleKey::ShadowOpacity, opacity.clamp(0.0, 1.0));
self
}
fn shadow_radius(mut self, radius: f32) -> Self {
self.style().number(StyleKey::ShadowRadius, radius);
self
}
fn shadow_offset(mut self, x: f32, y: f32) -> Self {
self.style()
.push(Declaration::ShadowOffset(Bits(x), Bits(y)));
self
}
fn inset_shadow_2xs(mut self) -> Self {
self.style().push(Declaration::InsetShadow("2xs"));
self
}
fn inset_shadow_xs(mut self) -> Self {
self.style().push(Declaration::InsetShadow("xs"));
self
}
fn inset_shadow_sm(mut self) -> Self {
self.style().push(Declaration::InsetShadow("sm"));
self
}
fn inset_shadow_none(mut self) -> Self {
self.style().push(Declaration::InsetShadow("none"));
self
}
fn inset_shadow_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.push(Declaration::PartColor(ColorPart::InsetShadow, color.into()));
self
}
fn ring(mut self, width: f32) -> Self {
self.style().push(Declaration::Ring(Bits(width)));
self
}
fn ring_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.push(Declaration::PartColor(ColorPart::Ring, color.into()));
self
}
fn ring_offset(mut self, width: f32) -> Self {
self.style().push(Declaration::RingOffset(Bits(width)));
self
}
fn ring_offset_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.push(Declaration::PartColor(ColorPart::RingOffset, color.into()));
self
}
fn ring_inset(mut self) -> Self {
self.style().push(Declaration::RingInset);
self
}
fn inset_ring(mut self, width: f32) -> Self {
self.style().push(Declaration::InsetRing(Bits(width)));
self
}
fn inset_ring_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.push(Declaration::PartColor(ColorPart::InsetRing, color.into()));
self
}
fn bg_linear(mut self, degrees: f32) -> Self {
self.style()
.push(Declaration::Gradient(GradientShape::Linear(Bits(degrees))));
self
}
fn bg_linear_to_t(self) -> Self {
self.bg_linear(0.0)
}
fn bg_linear_to_r(self) -> Self {
self.bg_linear(90.0)
}
fn bg_linear_to_b(self) -> Self {
self.bg_linear(180.0)
}
fn bg_linear_to_l(self) -> Self {
self.bg_linear(270.0)
}
fn bg_linear_to_tr(mut self) -> Self {
self.style()
.push(Declaration::Gradient(GradientShape::Corner {
right: true,
bottom: false,
}));
self
}
fn bg_linear_to_br(mut self) -> Self {
self.style()
.push(Declaration::Gradient(GradientShape::Corner {
right: true,
bottom: true,
}));
self
}
fn bg_linear_to_bl(mut self) -> Self {
self.style()
.push(Declaration::Gradient(GradientShape::Corner {
right: false,
bottom: true,
}));
self
}
fn bg_linear_to_tl(mut self) -> Self {
self.style()
.push(Declaration::Gradient(GradientShape::Corner {
right: false,
bottom: false,
}));
self
}
fn bg_radial(mut self) -> Self {
self.style()
.push(Declaration::Gradient(GradientShape::Radial));
self
}
fn bg_conic(mut self, degrees: f32) -> Self {
self.style()
.push(Declaration::Gradient(GradientShape::Conic(Bits(degrees))));
self
}
fn bg_gradient_none(mut self) -> Self {
self.style().push(Declaration::GradientNone);
self
}
fn gradient_from(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.push(Declaration::PartColor(ColorPart::From, color.into()));
self
}
fn gradient_via(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.push(Declaration::PartColor(ColorPart::Via, color.into()));
self
}
fn gradient_to(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.push(Declaration::PartColor(ColorPart::To, color.into()));
self
}
fn gradient_from_position(mut self, at: f32) -> Self {
self.style().push(Declaration::StopPosition(0, Bits(at)));
self
}
fn gradient_via_position(mut self, at: f32) -> Self {
self.style().push(Declaration::StopPosition(1, Bits(at)));
self
}
fn gradient_to_position(mut self, at: f32) -> Self {
self.style().push(Declaration::StopPosition(2, Bits(at)));
self
}
fn blur(self, radius: f32) -> Self {
filter(self, false, FilterFn::Blur, radius)
}
fn brightness(self, amount: f32) -> Self {
filter(self, false, FilterFn::Brightness, amount)
}
fn contrast(self, amount: f32) -> Self {
filter(self, false, FilterFn::Contrast, amount)
}
fn grayscale(self, amount: f32) -> Self {
filter(self, false, FilterFn::Grayscale, amount)
}
fn hue_rotate(self, degrees: f32) -> Self {
filter(self, false, FilterFn::HueRotate, degrees)
}
fn invert(self, amount: f32) -> Self {
filter(self, false, FilterFn::Invert, amount)
}
fn saturate(self, amount: f32) -> Self {
filter(self, false, FilterFn::Saturate, amount)
}
fn sepia(self, amount: f32) -> Self {
filter(self, false, FilterFn::Sepia, amount)
}
fn filter_none(mut self) -> Self {
self.style().push(Declaration::FilterNone(false));
self
}
fn backdrop_blur(self, radius: f32) -> Self {
filter(self, true, FilterFn::Blur, radius)
}
fn backdrop_brightness(self, amount: f32) -> Self {
filter(self, true, FilterFn::Brightness, amount)
}
fn backdrop_contrast(self, amount: f32) -> Self {
filter(self, true, FilterFn::Contrast, amount)
}
fn backdrop_grayscale(self, amount: f32) -> Self {
filter(self, true, FilterFn::Grayscale, amount)
}
fn backdrop_hue_rotate(self, degrees: f32) -> Self {
filter(self, true, FilterFn::HueRotate, degrees)
}
fn backdrop_invert(self, amount: f32) -> Self {
filter(self, true, FilterFn::Invert, amount)
}
fn backdrop_opacity(self, amount: f32) -> Self {
filter(self, true, FilterFn::Opacity, amount)
}
fn backdrop_saturate(self, amount: f32) -> Self {
filter(self, true, FilterFn::Saturate, amount)
}
fn backdrop_sepia(self, amount: f32) -> Self {
filter(self, true, FilterFn::Sepia, amount)
}
fn backdrop_filter_none(mut self) -> Self {
self.style().push(Declaration::FilterNone(true));
self
}
fn mix_blend_mode(mut self, mode: BlendMode) -> Self {
self.style().keyword(StyleKey::MixBlendMode, mode.name());
self
}
fn transition(self) -> Self {
transition(
self,
TransitionProps::COLORS
| TransitionProps::OPACITY
| TransitionProps::SHADOW
| TransitionProps::TRANSFORM,
)
}
fn transition_all(self) -> Self {
transition(self, TransitionProps::ALL)
}
fn transition_colors(self) -> Self {
transition(self, TransitionProps::COLORS)
}
fn transition_opacity(self) -> Self {
transition(self, TransitionProps::OPACITY)
}
fn transition_shadow(self) -> Self {
transition(self, TransitionProps::SHADOW)
}
fn transition_transform(self) -> Self {
transition(self, TransitionProps::TRANSFORM)
}
fn transition_none(mut self) -> Self {
self.style().push(Declaration::TransitionNone);
self
}
fn duration(mut self, ms: f32) -> Self {
self.style().push(Declaration::Duration(Bits(ms)));
self
}
fn delay(mut self, ms: f32) -> Self {
self.style().push(Declaration::Delay(Bits(ms)));
self
}
fn ease_linear(mut self) -> Self {
self.style().push(Declaration::EasePreset("linear"));
self
}
fn ease_in(mut self) -> Self {
self.style().push(Declaration::EasePreset("in"));
self
}
fn ease_out(mut self) -> Self {
self.style().push(Declaration::EasePreset("out"));
self
}
fn ease_in_out(mut self) -> Self {
self.style().push(Declaration::EasePreset("in-out"));
self
}
fn ease_bezier(mut self, x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
self.style()
.push(Declaration::Ease([x1, y1, x2, y2].map(Bits)));
self
}
fn animate_spin(mut self) -> Self {
self.style().push(Declaration::Animate(Some(0)));
self
}
fn animate_ping(mut self) -> Self {
self.style().push(Declaration::Animate(Some(1)));
self
}
fn animate_pulse(mut self) -> Self {
self.style().push(Declaration::Animate(Some(2)));
self
}
fn animate_bounce(mut self) -> Self {
self.style().push(Declaration::Animate(Some(3)));
self
}
fn animation(mut self, animation: KeyframeAnimation) -> Self {
let index = KEYFRAMES
.iter()
.position(|k| *k == animation.keyframes)
.expect("every keyframes") as u8;
self.style().push(Declaration::Animation(
index,
Bits(animation.duration),
Bits(animation.delay),
animation.easing.map(Bits),
animation.iterations,
));
self
}
fn animate_none(mut self) -> Self {
self.style().push(Declaration::Animate(None));
self
}
fn scale(self, scale: f32) -> Self {
self.transform_step(TransformKind::Scale, scale)
}
fn scale_x(self, scale: f32) -> Self {
self.transform_step(TransformKind::ScaleX, scale)
}
fn scale_y(self, scale: f32) -> Self {
self.transform_step(TransformKind::ScaleY, scale)
}
fn translate_x(self, points: f32) -> Self {
self.transform_step(TransformKind::TranslateX, points)
}
fn translate_y(self, points: f32) -> Self {
self.transform_step(TransformKind::TranslateY, points)
}
fn rotate(self, degrees: f32) -> Self {
self.transform_step(TransformKind::Rotate, degrees)
}
fn rotate_x(self, degrees: f32) -> Self {
self.transform_step(TransformKind::RotateX, degrees)
}
fn rotate_y(self, degrees: f32) -> Self {
self.transform_step(TransformKind::RotateY, degrees)
}
fn skew_x(self, degrees: f32) -> Self {
self.transform_step(TransformKind::SkewX, degrees)
}
fn skew_y(self, degrees: f32) -> Self {
self.transform_step(TransformKind::SkewY, degrees)
}
fn perspective(self, points: f32) -> Self {
self.transform_step(TransformKind::Perspective, points)
}
fn transform_step(mut self, kind: TransformKind, amount: f32) -> Self {
self.style()
.push(Declaration::Transform(kind, Bits(amount)));
self
}
fn transform_none(mut self) -> Self {
self.style().push(Declaration::TransformNone);
self
}
fn transform_origin(mut self, origin: TransformOrigin) -> Self {
let axis = |l: OriginLen| match l {
OriginLen::Px(p) => (false, Bits(p)),
OriginLen::Fraction(f) => (true, Bits(f)),
};
self.style()
.push(Declaration::Origin([axis(origin.x), axis(origin.y)]));
self
}
fn origin_top_left(mut self) -> Self {
self.style().keyword(StyleKey::TransformOrigin, "top left");
self
}
fn origin_top(mut self) -> Self {
self.style().keyword(StyleKey::TransformOrigin, "top");
self
}
fn origin_top_right(mut self) -> Self {
self.style().keyword(StyleKey::TransformOrigin, "top right");
self
}
fn origin_left(mut self) -> Self {
self.style().keyword(StyleKey::TransformOrigin, "left");
self
}
fn origin_center(mut self) -> Self {
self.style().keyword(StyleKey::TransformOrigin, "center");
self
}
fn origin_right(mut self) -> Self {
self.style().keyword(StyleKey::TransformOrigin, "right");
self
}
fn origin_bottom_left(mut self) -> Self {
self.style()
.keyword(StyleKey::TransformOrigin, "bottom left");
self
}
fn origin_bottom(mut self) -> Self {
self.style().keyword(StyleKey::TransformOrigin, "bottom");
self
}
fn origin_bottom_right(mut self) -> Self {
self.style()
.keyword(StyleKey::TransformOrigin, "bottom right");
self
}
fn backface_hidden(mut self) -> Self {
self.style().keyword(StyleKey::BackfaceVisibility, "hidden");
self
}
fn backface_visible(mut self) -> Self {
self.style()
.keyword(StyleKey::BackfaceVisibility, "visible");
self
}
fn text_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style().color(&[StyleKey::Color], color.into());
self
}
fn text_size(mut self, size: impl Into<Length>) -> Self {
self.style().lengths(&[StyleKey::FontSize], size.into());
self
}
fn text_xs(mut self) -> Self {
self.style().push(Declaration::TextPreset("xs"));
self
}
fn text_sm(mut self) -> Self {
self.style().push(Declaration::TextPreset("sm"));
self
}
fn text_base(mut self) -> Self {
self.style().push(Declaration::TextPreset("base"));
self
}
fn text_lg(mut self) -> Self {
self.style().push(Declaration::TextPreset("lg"));
self
}
fn text_xl(mut self) -> Self {
self.style().push(Declaration::TextPreset("xl"));
self
}
fn text_2xl(mut self) -> Self {
self.style().push(Declaration::TextPreset("2xl"));
self
}
fn text_3xl(mut self) -> Self {
self.style().push(Declaration::TextPreset("3xl"));
self
}
fn text_4xl(mut self) -> Self {
self.style().push(Declaration::TextPreset("4xl"));
self
}
fn text_5xl(mut self) -> Self {
self.style().push(Declaration::TextPreset("5xl"));
self
}
fn text_6xl(mut self) -> Self {
self.style().push(Declaration::TextPreset("6xl"));
self
}
fn text_7xl(mut self) -> Self {
self.style().push(Declaration::TextPreset("7xl"));
self
}
fn text_8xl(mut self) -> Self {
self.style().push(Declaration::TextPreset("8xl"));
self
}
fn text_9xl(mut self) -> Self {
self.style().push(Declaration::TextPreset("9xl"));
self
}
fn line_height(mut self, height: impl Into<Length>) -> Self {
self.style().lengths(&[StyleKey::LineHeight], height.into());
self
}
fn font_weight(mut self, weight: FontWeight) -> Self {
self.style().number(StyleKey::FontWeight, weight.0 as f32);
self
}
fn font_family(mut self, family: impl Into<SharedString>) -> Self {
self.style()
.push(Declaration::Str(StyleKey::FontFamily, family.into()));
self
}
fn italic(mut self) -> Self {
self.style().keyword(StyleKey::FontStyle, "italic");
self
}
fn underline(mut self) -> Self {
self.style().push(Declaration::Decoration(UNDERLINE));
self
}
fn line_through(mut self) -> Self {
self.style().push(Declaration::Decoration(LINE_THROUGH));
self
}
fn no_underline(mut self) -> Self {
self.style().push(Declaration::Decoration(0));
self
}
fn text_decoration_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
self.style()
.color(&[StyleKey::TextDecorationColor], color.into());
self
}
fn text_decoration_solid(mut self) -> Self {
self.style().keyword(StyleKey::TextDecorationStyle, "solid");
self
}
fn text_decoration_double(mut self) -> Self {
self.style()
.keyword(StyleKey::TextDecorationStyle, "double");
self
}
fn text_decoration_dotted(mut self) -> Self {
self.style()
.keyword(StyleKey::TextDecorationStyle, "dotted");
self
}
fn text_decoration_dashed(mut self) -> Self {
self.style()
.keyword(StyleKey::TextDecorationStyle, "dashed");
self
}
fn text_decoration_wavy(mut self) -> Self {
self.style().keyword(StyleKey::TextDecorationStyle, "wavy");
self
}
fn text_decoration_thickness(mut self, points: f32) -> Self {
self.style()
.number(StyleKey::TextDecorationThickness, points);
self
}
fn underline_offset(mut self, points: f32) -> Self {
self.style().number(StyleKey::TextUnderlineOffset, points);
self
}
fn uppercase(mut self) -> Self {
self.style().keyword(StyleKey::TextTransform, "uppercase");
self
}
fn lowercase(mut self) -> Self {
self.style().keyword(StyleKey::TextTransform, "lowercase");
self
}
fn capitalize(mut self) -> Self {
self.style().keyword(StyleKey::TextTransform, "capitalize");
self
}
fn normal_case(mut self) -> Self {
self.style().keyword(StyleKey::TextTransform, "none");
self
}
fn tabular_nums(self) -> Self {
font_variant(
self,
FontVariant::TABULAR_NUMS,
FontVariant::PROPORTIONAL_NUMS,
)
}
fn proportional_nums(self) -> Self {
font_variant(
self,
FontVariant::PROPORTIONAL_NUMS,
FontVariant::TABULAR_NUMS,
)
}
fn oldstyle_nums(self) -> Self {
font_variant(self, FontVariant::OLDSTYLE_NUMS, FontVariant::LINING_NUMS)
}
fn lining_nums(self) -> Self {
font_variant(self, FontVariant::LINING_NUMS, FontVariant::OLDSTYLE_NUMS)
}
fn small_caps(self) -> Self {
font_variant(self, FontVariant::SMALL_CAPS, 0)
}
fn normal_nums(self) -> Self {
font_variant(self, 0, 0xff)
}
fn writing_direction(mut self, direction: WritingDirection) -> Self {
self.style().keyword(
StyleKey::WritingDirection,
match direction {
WritingDirection::Auto => "auto",
WritingDirection::Ltr => "ltr",
WritingDirection::Rtl => "rtl",
},
);
self
}
fn text_justify(mut self) -> Self {
self.style().keyword(StyleKey::TextAlign, "justify");
self
}
fn text_shadow_2xs(mut self) -> Self {
self.style().push(Declaration::TextShadow("2xs"));
self
}
fn text_shadow_xs(mut self) -> Self {
self.style().push(Declaration::TextShadow("xs"));
self
}
fn text_shadow_sm(mut self) -> Self {
self.style().push(Declaration::TextShadow("sm"));
self
}
fn text_shadow_md(mut self) -> Self {
self.style().push(Declaration::TextShadow("md"));
self
}
fn text_shadow_lg(mut self) -> Self {
self.style().push(Declaration::TextShadow("lg"));
self
}
fn text_shadow_none(mut self) -> Self {
self.style().push(Declaration::TextShadow("none"));
self
}
fn text_shadow_color(mut self, color: impl Into<AdaptiveColor>) -> Self {
let color = color.into();
let s = self.style();
s.color(&[StyleKey::TextShadowColor], color);
s.push(Declaration::PartColor(ColorPart::TextShadow, color));
self
}
fn text_shadow_radius(mut self, radius: f32) -> Self {
self.style().number(StyleKey::TextShadowRadius, radius);
self
}
fn text_shadow_offset(mut self, x: f32, y: f32) -> Self {
self.style()
.push(Declaration::TextShadowOffset(Bits(x), Bits(y)));
self
}
fn text_left(mut self) -> Self {
self.style().keyword(StyleKey::TextAlign, "left");
self
}
fn text_center(mut self) -> Self {
self.style().keyword(StyleKey::TextAlign, "center");
self
}
fn text_right(mut self) -> Self {
self.style().keyword(StyleKey::TextAlign, "right");
self
}
fn letter_spacing(mut self, points: f32) -> Self {
self.style().number(StyleKey::LetterSpacing, points);
self
}
fn dark(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
let s = f(StyleRefinement::default());
self.style().extend_as(Variant::DARK, s);
self
}
fn group(mut self) -> Self {
self.style().push(Declaration::Group(""));
self
}
fn group_named(mut self, name: &'static str) -> Self {
self.style().push(Declaration::Group(name));
self
}
fn group_active(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
in_group(self, "", state::PRESSED, f)
}
fn group_hover(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
in_group(self, "", state::HOVERED, f)
}
fn group_focus_within(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
in_group(self, "", state::FOCUS_WITHIN, f)
}
fn group_active_named(
self,
name: &'static str,
f: impl FnOnce(StyleRefinement) -> StyleRefinement,
) -> Self {
in_group(self, name, state::PRESSED, f)
}
fn group_hover_named(
self,
name: &'static str,
f: impl FnOnce(StyleRefinement) -> StyleRefinement,
) -> Self {
in_group(self, name, state::HOVERED, f)
}
fn group_focus_within_named(
self,
name: &'static str,
f: impl FnOnce(StyleRefinement) -> StyleRefinement,
) -> Self {
in_group(self, name, state::FOCUS_WITHIN, f)
}
}
fn filter<S: Styled>(mut s: S, backdrop: bool, f: FilterFn, amount: f32) -> S {
s.style()
.push(Declaration::Filter(backdrop, f, Bits(amount)));
s
}
fn transition<S: Styled>(mut s: S, props: u8) -> S {
s.style().push(Declaration::Transition(props));
s
}
fn in_group<S: Styled>(
mut s: S,
name: &'static str,
states: u8,
f: impl FnOnce(StyleRefinement) -> StyleRefinement,
) -> S {
let styles = f(StyleRefinement::default());
let style = s.style();
let group = style.name(name);
style.extend_as(
Variant {
group_states: states,
group,
..Variant::default()
},
styles,
);
s
}
impl Styled for StyleRefinement {
fn style(&mut self) -> &mut StyleRefinement {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
Style,
tailwind::{ClassEnvironment, ClassProps, Context},
ui::palette::{EMERALD, PINK, RED, SKY, VIOLET},
};
fn resolve(list: &ClassList, dark: bool, states: u8, group: u8) -> String {
resolve_with(list, dark, states, group, &|_| {})
}
fn resolve_with(
list: &ClassList,
dark: bool,
states: u8,
group: u8,
inline: &dyn Fn(&mut Style),
) -> String {
let cx = Context {
env: ClassEnvironment {
dark,
..Default::default()
},
window: (390.0, 844.0),
rtl: false,
states,
position: 0,
group: &|_| group,
};
let mut style = Style::default();
let mut props = ClassProps::default();
list.apply(&cx, &PRESETS, &mut style, &mut props, inline);
format!("{style:?} {props:?}")
}
#[track_caller]
fn same(typed: StyleRefinement, classes: &str) {
same_with(typed, classes, &|_| {});
}
#[track_caller]
fn same_with(typed: StyleRefinement, classes: &str, inline: &dyn Fn(&mut Style)) {
let typed = typed.lower();
let parsed = tailwind::parse(&PRESETS, classes);
assert!(parsed.unknown().is_empty(), "{:?}", parsed.unknown());
assert_eq!(typed.deps(), parsed.deps(), "{classes}: deps");
assert_eq!(typed.groups(), parsed.groups(), "{classes}: groups");
for dark in [false, true] {
for states in [0, state::PRESSED, state::DISABLED] {
for group in [0, state::PRESSED, state::HOVERED] {
assert_eq!(
resolve(&typed, dark, states, group),
resolve_with(&parsed, dark, states, group, inline),
"{classes} (dark {dark}, states {states}, group {group})"
);
}
}
}
}
fn s() -> StyleRefinement {
StyleRefinement::default()
}
#[test]
fn borders_and_corners_are_tailwinds() {
same(
s().border_t(6.0)
.border_t_color(RED.shade(600))
.border_r(2.0)
.border_b(4.0)
.border_l(1.0)
.border_x_color(SKY.shade(500)),
"border-t-6 border-t-red-600 border-r-2 border-b-4 border-l border-x-sky-500",
);
same(
s().border_y(3.0)
.border_s(1.0)
.border_e(2.0)
.border_dashed(),
"border-y-3 border-s border-e-2 border-dashed",
);
same(s().border(3.0).border_dotted(), "border-3 border-dotted");
same(
s().rounded_tl(px(44.0))
.rounded_tr(px(6.0))
.rounded_br(px(28.0))
.rounded_bl(px(2.0)),
"rounded-tl-[44px] rounded-tr-[6px] rounded-br-[28px] rounded-bl-[2px]",
);
same(
s().rounded_ss(px(22.0))
.rounded_ee(px(8.0))
.rounded_l(px(4.0)),
"rounded-ss-[22px] rounded-ee-[8px] rounded-l-[4px]",
);
same(
s().outline(2.0)
.outline_offset(2.0)
.outline_dashed()
.outline_color(PINK.shade(500)),
"outline-2 outline-offset-2 outline-dashed outline-pink-500",
);
let curved = s().border_curve(BorderCurve::Continuous).lower();
let mut style = Style::default();
let _ = style.set_key(StyleKey::BorderCurve, crate::StyleValue::Str("continuous"));
assert_eq!(
resolve(&curved, false, 0, 0),
format!("{style:?} {:?}", ClassProps::default())
);
}
#[test]
fn shadows_and_rings_are_tailwinds() {
let emerald = EMERALD.shade(500).with_alpha(0.5);
same_with(
s().shadow_lg().shadow_color(emerald),
"shadow-lg shadow-emerald-500/50",
&|s| s.view.shadow.color = emerald,
);
same_with(
s().shadow_xl().shadow_color(SKY.shade(500)),
"shadow-xl shadow-sky-500",
&|s| s.view.shadow.color = SKY.shade(500),
);
same(s().inset_shadow_sm(), "inset-shadow-sm");
same(
s().ring(2.0).ring_color(SKY.shade(500)).ring_offset(2.0),
"ring-2 ring-sky-500 ring-offset-2",
);
same(
s().ring(1.0).ring_color(rgba(0x0000_000d)).ring_inset(),
"ring-1 ring-black/5 ring-inset",
);
same(s().text_shadow_md(), "text-shadow-md");
let adaptive = s()
.shadow_md()
.shadow_color(AdaptiveColor::new(SKY.shade(500), PINK.shade(500)))
.lower();
assert_eq!(adaptive.deps(), tailwind::deps::DARK);
for (dark, hue) in [(false, SKY), (true, PINK)] {
let classes = format!("shadow-md shadow-{}-500", hue.name());
assert_eq!(
resolve(&adaptive, dark, 0, 0),
resolve_with(&tailwind::parse(&PRESETS, &classes), dark, 0, 0, &|s| {
s.view.shadow.color = hue.shade(500)
})
);
}
}
#[test]
fn custom_shadows_set_react_natives_and_box_shadows() {
let list = s()
.shadow_color(rgb(0x0969da))
.shadow_opacity(0.35)
.shadow_radius(10.0)
.shadow_offset(4.0, 8.0)
.text_shadow_color(rgba(0x0000_0099))
.text_shadow_radius(4.0)
.text_shadow_offset(2.0, 2.0)
.lower();
let mut style = Style::default();
list.apply(
&Context {
env: ClassEnvironment::default(),
window: (390.0, 844.0),
rtl: false,
states: 0,
position: 0,
group: &|_| 0,
},
&PRESETS,
&mut style,
&mut ClassProps::default(),
|_| {},
);
assert_eq!(style.view.shadow.color, rgb(0x0969da));
assert_eq!(style.view.shadow.opacity, 0.35);
assert_eq!(style.view.shadow.radius, 10.0);
assert_eq!(
(style.view.shadow.offset_x, style.view.shadow.offset_y),
(4.0, 8.0)
);
assert_eq!(style.text.shadow_color, Some(rgba(0x0000_0099)));
assert_eq!(style.text.shadow_radius, Some(4.0));
assert_eq!(style.text.shadow_offset, Some((2.0, 2.0)));
let layer = BoxShadow {
offset_x: 0.0,
offset_y: 2.0,
blur: 4.0,
spread: 0.0,
color: rgba(0x0000_000d),
inset: true,
};
same(
s().shadow([layer]),
"shadow-[inset_0_2px_4px_rgb(0_0_0/0.05)]",
);
}
#[test]
fn effects_are_tailwinds() {
same(
s().bg_linear_to_br()
.gradient_from(VIOLET.shade(500))
.gradient_via(PINK.shade(500))
.gradient_to(RED.shade(400)),
"bg-linear-to-br from-violet-500 via-pink-500 to-red-400",
);
same(
s().bg_linear(45.0)
.gradient_from(SKY.shade(400))
.gradient_to(VIOLET.shade(600))
.gradient_to_position(0.8),
"bg-linear-45 from-sky-400 to-violet-600 to-80%",
);
same(
s().bg_radial().gradient_from(SKY.shade(200)),
"bg-radial from-sky-200",
);
same(
s().bg_conic(0.0).gradient_from(RED.shade(500)),
"bg-conic from-red-500",
);
same(s().grayscale(1.0).sepia(1.0), "grayscale sepia");
same(s().blur(8.0).brightness(0.5), "blur-sm brightness-50");
same(
s().saturate(1.5).hue_rotate(90.0),
"saturate-150 hue-rotate-90",
);
same(
s().backdrop_blur(12.0)
.backdrop_saturate(1.5)
.backdrop_sepia(1.0),
"backdrop-blur-md backdrop-saturate-150 backdrop-sepia",
);
same(
s().mix_blend_mode(BlendMode::Multiply),
"mix-blend-multiply",
);
same(s().transition(), "transition");
same(
s().transition_colors()
.duration(150.0)
.ease_in_out()
.delay(75.0),
"transition-colors duration-150 ease-in-out delay-75",
);
same(
s().transition_transform().duration(200.0),
"transition-transform duration-200",
);
for (typed, classes) in [
(s().animate_spin(), "animate-spin"),
(s().animate_ping(), "animate-ping"),
(s().animate_pulse(), "animate-pulse"),
(s().animate_bounce(), "animate-bounce"),
] {
same(typed, classes);
}
}
#[test]
fn keyframe_animations_take_their_own_timing() {
let timed = |name: &'static str, ms: f32, easing: &'static str| {
move |style: &mut Style| {
use crate::StyleValue;
style
.set_key(StyleKey::AnimationName, StyleValue::Str(name))
.unwrap();
style
.set_key(StyleKey::AnimationDuration, StyleValue::Number(ms))
.unwrap();
style
.set_key(StyleKey::AnimationTimingFunction, StyleValue::Str(easing))
.unwrap();
}
};
same_with(
s().animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0)),
"animate-none",
&timed("spin", 800.0, "linear"),
);
same_with(
s().animation(
KeyframeAnimation::new(Keyframes::Pulse)
.duration(900.0)
.easing([0.42, 0.0, 0.58, 1.0]),
),
"animate-none",
&timed("pulse", 900.0, "ease-in-out"),
);
same(
s().animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0))
.animate_ping(),
"animate-ping",
);
same_with(
s().animate_ping()
.animation(KeyframeAnimation::new(Keyframes::Spin).duration(800.0)),
"animate-none",
&timed("spin", 800.0, "linear"),
);
}
#[test]
fn transforms_are_tailwinds() {
same(
s().rotate(12.0).skew_x(6.0).scale(0.9),
"rotate-12 skew-x-6 scale-90",
);
same(
s().perspective(400.0).rotate_y(35.0).rotate_x(40.0),
"perspective-[400px] rotate-y-35 rotate-x-40",
);
same(s().scale_x(1.5).skew_y(-3.0), "scale-x-150 -skew-y-3");
same(
s().origin_top_left().backface_hidden(),
"origin-top-left backface-hidden",
);
same(
s().transform_origin(TransformOrigin {
x: OriginLen::Px(10.0),
y: OriginLen::Fraction(0.25),
z: 0.0,
}),
"origin-[10px_25%]",
);
}
#[test]
fn text_is_tailwinds() {
same(
s().underline()
.text_decoration_wavy()
.text_decoration_color(RED.shade(500))
.text_decoration_thickness(2.0)
.underline_offset(4.0),
"underline decoration-wavy decoration-red-500 decoration-2 underline-offset-4",
);
same(s().uppercase().tabular_nums(), "uppercase tabular-nums");
same(s().small_caps().oldstyle_nums(), "small-caps oldstyle-nums");
same(s().capitalize().text_justify(), "capitalize text-justify");
let both = s().underline().line_through().lower();
let mut style = Style::default();
let _ = style.set_key(
StyleKey::TextDecorationLine,
crate::StyleValue::Str("underline line-through"),
);
assert_eq!(
resolve(&both, false, 0, 0),
format!("{style:?} {:?}", ClassProps::default())
);
same(
s().underline().line_through().no_underline(),
"no-underline",
);
let rtl = s().writing_direction(WritingDirection::Rtl).lower();
let mut style = Style::default();
let _ = style.set_key(StyleKey::WritingDirection, crate::StyleValue::Str("rtl"));
assert_eq!(
resolve(&rtl, false, 0, 0),
format!("{style:?} {:?}", ClassProps::default())
);
}
#[test]
fn layout_is_tailwinds() {
same(s().grid().grid_cols(3).gap_2(), "grid grid-cols-3 gap-2");
same(s().col_span(2).row_span(2), "col-span-2 row-span-2");
same(s().col_start(2).col_end(-1), "col-start-2 col-end-[-1]");
same(s().flex_grow(2.0).flex_shrink(0.0), "grow-2 shrink-0");
same(
s().grid_rows(2).grid_flow_col(),
"grid-rows-2 grid-flow-col",
);
}
#[test]
fn variants_are_tailwinds() {
same(
s().group_active(|s| s.text_color(VIOLET.shade(600)).translate_x(4.0)),
"group-active:text-violet-600 group-active:translate-x-1",
);
same(s().group(), "group");
same(
s().group_named("item")
.group_hover_named("item", |s| s.opacity(0.5)),
"group/item group-hover/item:opacity-50",
);
same(s().dark(|s| s.shadow_none()), "dark:shadow-none");
let mut disabled = s();
disabled.extend_as(Variant::DISABLED, s().opacity(0.4));
same(disabled, "disabled:opacity-40");
let mut nested = s();
nested.extend_as(Variant::ACTIVE, s().dark(|s| s.opacity(0.5)));
same(nested, "dark:active:opacity-50");
}
}