use std::{
fmt,
hash::{Hash, Hasher},
rc::Rc,
sync::{Arc, LazyLock},
};
use super::{IntoReactive, Reactive, SharedString};
use crate::{
BlendMode, BoxShadow, Cursor, FontVariant, ObjectPosition, TransformOrigin, TransitionProps,
color::{Hsla, Rgba, transparent_black},
effects::{Filter, GradientKind, GradientSize, KeyframeAnimation, Keyframes},
geometry::{
AbsoluteLength, DefiniteLength, Length, Percentage, Points, REM_SIZE, Radians, Rems, deg,
percentage, px, relative,
},
style::{Color, LineHeight, PositionAxis, PropertyValue, StyleKey},
tailwind::{self, ClassList, Decl, Part, Rank, Rule, rank, state},
transform::TransformKind,
};
fn points(length: AbsoluteLength) -> f32 {
length.to_points(REM_SIZE).0
}
#[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);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct AdaptiveColor {
pub light: Hsla,
pub dark: Hsla,
}
impl AdaptiveColor {
pub const TRANSPARENT: Self = Self {
light: transparent_black(),
dark: transparent_black(),
};
pub fn new(light: impl Into<Hsla>, dark: impl Into<Hsla>) -> Self {
Self {
light: light.into(),
dark: dark.into(),
}
}
pub const fn rgb(light: u32, dark: u32) -> Self {
Self {
light: crate::color::rgb(light).to_hsla(),
dark: crate::color::rgb(dark).to_hsla(),
}
}
pub fn opacity(self, opacity: f32) -> Self {
self.map(|c| c.opacity(opacity))
}
pub fn map(self, f: impl Fn(Hsla) -> Hsla) -> Self {
Self {
light: f(self.light),
dark: f(self.dark),
}
}
}
impl From<Hsla> for AdaptiveColor {
fn from(c: Hsla) -> Self {
Self { light: c, dark: c }
}
}
impl From<Rgba> for AdaptiveColor {
fn from(c: Rgba) -> Self {
Hsla::from(c).into()
}
}
impl From<Color> for AdaptiveColor {
fn from(c: Color) -> Self {
Hsla::from(c).into()
}
}
#[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: u16,
group_states: u16,
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 FOCUS_VISIBLE: Self = Self::states(state::FOCUS_VISIBLE);
pub(crate) const FOCUS_WITHIN: Self = Self::states(state::FOCUS_WITHIN);
pub(crate) const ACTIVE: Self = Self::states(state::PRESSED);
pub(crate) const DISABLED: Self = Self::states(state::DISABLED);
pub(crate) const SELECTED: Self = Self::states(state::SELECTED);
pub(crate) const CHECKED: Self = Self::states(state::CHECKED);
pub(crate) const INDETERMINATE: Self = Self::states(state::INDETERMINATE);
pub(crate) const EXPANDED: Self = Self::states(state::EXPANDED);
pub(crate) const ARIA_PRESSED: Self = Self::states(state::ARIA_PRESSED);
const DARK: Self = Self {
states: 0,
group_states: 0,
group: 0,
dark: true,
};
const fn states(states: u16) -> 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, group: &str) -> Rank {
let mut r = Rank::default();
let keys = [
(state::HOVERED, rank::HOVER),
(state::FOCUSED, rank::FOCUS),
(state::FOCUS_VISIBLE, rank::FOCUS_VISIBLE),
(state::FOCUS_WITHIN, rank::FOCUS_WITHIN),
(state::PRESSED, rank::ACTIVE),
(state::DISABLED, rank::DISABLED),
(state::SELECTED, rank::SELECTED),
(state::CHECKED, rank::CHECKED),
(state::INDETERMINATE, rank::INDETERMINATE),
(state::EXPANDED, rank::EXPANDED),
(state::ARIA_PRESSED, rank::ARIA_PRESSED),
(state::BUSY, rank::ARIA_BUSY),
];
for (bit, key) in keys {
if self.group_states & bit != 0 {
r.add_group(&key, group);
}
if self.states & bit != 0 {
r.add(key);
}
}
if self.dark {
r.add(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: Hsla) -> Part {
let c = Color::from(c);
match self {
ColorPart::Shadow => Part::ShadowColor(c),
ColorPart::InsetShadow => Part::InsetShadowColor(c),
ColorPart::TextShadow => Part::TextShadowColor(c),
ColorPart::Ring => Part::RingColor(c),
ColorPart::RingOffset => Part::RingOffsetColor(c),
ColorPart::InsetRing => Part::InsetRingColor(c),
ColorPart::From => Part::From(c, false),
ColorPart::Via => Part::Via(c, false),
ColorPart::To => Part::To(c, false),
}
}
}
#[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(crate::geometry::px(amount))),
FilterFn::Brightness => (1, Filter::Brightness(amount)),
FilterFn::Contrast => (2, Filter::Contrast(amount)),
FilterFn::Grayscale => (3, Filter::Grayscale(amount)),
FilterFn::HueRotate => (4, Filter::HueRotate(crate::geometry::deg(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.0.to_bits(),
l.offset_y.0.to_bits(),
l.blur.0.to_bits(),
l.spread.0.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);
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct TextLayers(Arc<[crate::TextShadow]>);
impl TextLayers {
fn bits(&self) -> impl Iterator<Item = (u32, u32, u32, u32)> + '_ {
self.0.iter().map(|l| {
(
l.offset_x.0.to_bits(),
l.offset_y.0.to_bits(),
l.radius.0.to_bits(),
l.color.0,
)
})
}
}
impl PartialEq for TextLayers {
fn eq(&self, other: &Self) -> bool {
self.0.len() == other.0.len() && self.bits().eq(other.bits())
}
}
impl Eq for TextLayers {}
impl Hash for TextLayers {
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 {
Value(StyleKey, PropertyValue),
Default(StyleKey, PropertyValue),
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),
TextShadows(TextLayers),
Transform(TransformKind, Bits),
TransformNone,
TranslateNone,
ScaleNone,
RotateNone,
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>, Option<Bits>),
Tracks(StyleKey, u16),
Span(StyleKey, u16),
Group(&'static str),
}
static PRESETS: LazyLock<tailwind::Theme> = LazyLock::new(tailwind::Theme::default);
fn color_value(key: StyleKey, c: Hsla) -> PropertyValue {
let c = Color::from(c);
match key {
StyleKey::Fill | StyleKey::Stroke => PropertyValue::Paint(Some(crate::SvgPaint::Color(c))),
_ => PropertyValue::Color(Some(c)),
}
}
fn origin(x: f32, y: f32) -> TransformOrigin {
TransformOrigin {
x: DefiniteLength::Fraction(Percentage(x)),
y: DefiniteLength::Fraction(Percentage(y)),
z: Points::ZERO,
}
}
fn full_line() -> taffy::Line<taffy::GridPlacement<String>> {
taffy::Line {
start: crate::grid::line_number(1),
end: crate::grid::line_number(-1),
}
}
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::Value(key, value) => {
out.push(Decl::Set(*key, value.clone()));
match key {
StyleKey::BorderWidth
| StyleKey::BorderTopWidth
| StyleKey::BorderRightWidth
| StyleKey::BorderBottomWidth
| StyleKey::BorderLeftWidth
| StyleKey::BorderStartWidth
| StyleKey::BorderEndWidth => {
out.push(Decl::CurrentColor(StyleKey::BorderColor))
}
StyleKey::OutlineWidth => out.push(Decl::CurrentColor(StyleKey::OutlineColor)),
_ => {}
}
}
Declaration::Default(key, value) => {
out.push(Decl::Default(*key, value.clone()));
if *key == StyleKey::OutlineWidth {
out.push(Decl::CurrentColor(StyleKey::OutlineColor));
}
}
Declaration::Color(key, c) => out.push(if c.light == c.dark {
Decl::Set(*key, color_value(*key, c.light))
} else {
Decl::Adaptive(
*key,
[color_value(*key, c.light), color_value(*key, c.dark)],
)
}),
Declaration::TextPreset(name) => {
if let Some(&(size, line)) = PRESETS.text.get(*name) {
out.push(Decl::Set(
StyleKey::FontSize,
PropertyValue::OptPoints(Some(px(size))),
));
if let Some(m) = line {
out.push(Decl::Default(
StyleKey::LineHeight,
PropertyValue::LineHeight(LineHeight::Multiple(m)),
));
}
}
}
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::TextShadows(layers) => part(out, Part::TextShadow(layers.0.clone())),
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(Some(v))],
};
out.extend(parts.iter().cloned().map(Decl::Part));
}
Declaration::TransformNone => part(out, Part::TransformNone),
Declaration::TranslateNone => part(out, Part::TranslateNone),
Declaration::ScaleNone => part(out, Part::ScaleNone),
Declaration::RotateNone => part(out, Part::RotateNone),
Declaration::Origin(axes) => {
let [x, y] = axes.map(|(fraction, v)| {
if fraction {
DefiniteLength::Fraction(Percentage(v.0))
} else {
DefiniteLength::Absolute(AbsoluteLength::Points(px(v.0)))
}
});
out.push(Decl::Set(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(TransformOrigin {
x,
y,
z: Points::ZERO,
}),
));
}
Declaration::Gradient(shape) => part(
out,
Part::Gradient(match *shape {
GradientShape::Linear(angle) => GradientKind::Linear {
angle: Radians(angle.0),
},
GradientShape::Corner { right, bottom } => {
GradientKind::LinearCorner { right, bottom }
}
GradientShape::Radial => GradientKind::Radial {
circle: false,
size: GradientSize::FarthestCorner,
x: percentage(0.5),
y: percentage(0.5),
},
GradientShape::Conic(from) => GradientKind::Conic {
from: Radians(from.0),
x: percentage(0.5),
y: percentage(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,
PropertyValue::TextDecoration(Some(crate::TextDecoration {
underline: bits & UNDERLINE != 0,
line_through: bits & LINE_THROUGH != 0,
})),
)),
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, frame_rate) => part(
out,
Part::Animation(KeyframeAnimation {
keyframes: KEYFRAMES[*k as usize],
duration: duration.0,
delay: delay.0,
easing: easing.map(|b| b.0),
iterations: *iterations,
frame_rate: frame_rate.map(|b| b.0),
}),
),
Declaration::Tracks(key, n) => out.push(Decl::Set(
*key,
PropertyValue::grid_template(crate::grid::equal_tracks(*n)),
)),
Declaration::Span(key, n) => out.push(Decl::Set(
*key,
PropertyValue::GridLine(crate::grid::span(*n)),
)),
Declaration::Group(_) => {}
}
}
}
#[derive(Clone, Default)]
struct Entries(Option<Rc<Vec<(Variant, Declaration)>>>);
impl Entries {
fn with_capacity(capacity: usize) -> Self {
Self(Some(Rc::new(Vec::with_capacity(capacity))))
}
fn as_slice(&self) -> &[(Variant, Declaration)] {
self.0.as_deref().map_or(&[], Vec::as_slice)
}
fn capacity(&self) -> usize {
self.0.as_ref().map_or(0, |v| v.capacity())
}
fn reserve(&mut self, additional: usize) {
self.vec().reserve(additional);
}
fn push(&mut self, entry: (Variant, Declaration)) {
self.vec().push(entry);
}
fn extend_from_slice(&mut self, entries: &[(Variant, Declaration)]) {
self.vec().extend_from_slice(entries);
}
fn vec(&mut self) -> &mut Vec<(Variant, Declaration)> {
Rc::make_mut(self.0.get_or_insert_default())
}
fn into_vec(self) -> Vec<(Variant, Declaration)> {
self.0.map(Rc::unwrap_or_clone).unwrap_or_default()
}
}
impl std::ops::Deref for Entries {
type Target = [(Variant, Declaration)];
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl PartialEq for Entries {
fn eq(&self, other: &Self) -> bool {
match (&self.0, &other.0) {
(Some(a), Some(b)) if Rc::ptr_eq(a, b) => true,
_ => self.as_slice() == other.as_slice(),
}
}
}
impl Eq for Entries {}
impl Hash for Entries {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_slice().hash(state);
}
}
impl fmt::Debug for Entries {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.as_slice().fmt(f)
}
}
crate::static_reactive!(AdaptiveColor: AdaptiveColor, Hsla, Rgba, Color);
macro_rules! optional_reactive_colors {
($($source:ty),*) => {$(
impl IntoReactive<Option<AdaptiveColor>> for $source {
fn into_reactive(self) -> Reactive<Option<AdaptiveColor>> {
Reactive::Static(Some(self.into()))
}
}
)*};
}
optional_reactive_colors!(AdaptiveColor, Hsla, Rgba, Color);
crate::static_reactive!(Length: Length, Points, Rems, AbsoluteLength, DefiniteLength, Percentage);
crate::static_reactive!(DefiniteLength: Points, Rems, AbsoluteLength, DefiniteLength, Percentage);
crate::static_reactive!(AbsoluteLength: Points, Rems, AbsoluteLength);
crate::static_reactive!(Points: Points);
crate::static_reactive!(LineHeight: LineHeight, Points, Rems, AbsoluteLength);
crate::static_reactive!(Radians: Radians);
crate::static_reactive!(Percentage: Percentage);
crate::static_reactive!(u16: u16);
crate::static_reactive!(i16: i16);
pub(crate) type BoundStyle = Rc<dyn Fn(&mut StyleRefinement)>;
#[derive(Clone, Default)]
pub struct StyleRefinement {
entries: Entries,
names: Vec<&'static str>,
bound: Vec<BoundStyle>,
}
impl fmt::Debug for StyleRefinement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StyleRefinement")
.field("entries", &self.entries)
.field("names", &self.names)
.field("bound", &self.bound.len())
.finish()
}
}
impl PartialEq for StyleRefinement {
fn eq(&self, other: &Self) -> bool {
self.entries == other.entries
&& self.names == other.names
&& self.bound.len() == other.bound.len()
&& self
.bound
.iter()
.zip(&other.bound)
.all(|(a, b)| Rc::ptr_eq(a, b))
}
}
impl Eq for StyleRefinement {}
impl Hash for StyleRefinement {
fn hash<H: Hasher>(&self, state: &mut H) {
self.entries.hash(state);
self.names.hash(state);
}
}
impl StyleRefinement {
pub(crate) fn bind_value<T: 'static>(
&mut self,
value: impl IntoReactive<T>,
apply: impl Fn(&mut StyleRefinement, T) + 'static,
) {
match value.into_reactive() {
Reactive::Static(v) => apply(self, v),
Reactive::Bound(f) => self.bound.push(Rc::new(move |s| apply(s, f()))),
}
}
pub(crate) fn bind(&mut self, part: impl Fn(&mut StyleRefinement) + 'static) {
self.bound.push(Rc::new(part));
}
pub(crate) fn is_bound(&self) -> bool {
!self.bound.is_empty()
}
pub(crate) fn static_part(&self) -> StyleRefinement {
StyleRefinement {
entries: self.entries.clone(),
names: self.names.clone(),
bound: Vec::new(),
}
}
pub(crate) fn resolved(&self) -> StyleRefinement {
let entries = if self.bound.is_empty() {
self.entries.clone()
} else {
let mut entries = Entries::with_capacity(self.entries.len() + self.bound.len());
entries.extend_from_slice(&self.entries);
entries
};
let mut out = StyleRefinement {
entries,
names: self.names.clone(),
bound: Vec::new(),
};
for part in &self.bound {
part(&mut out);
}
out
}
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: impl Into<Length>) {
let length = length.into();
for key in keys {
self.checked(*key, key.length_value(length));
}
}
pub(crate) fn number(&mut self, key: StyleKey, n: f32) {
self.checked(key, key.number_value(n));
}
pub(crate) fn numbers(&mut self, keys: &[StyleKey], n: f32) {
for key in keys {
self.number(*key, n);
}
}
pub(crate) fn env_plus(&mut self, key: StyleKey, name: &str, extra: AbsoluteLength) {
match crate::style::EnvVar::parse(name) {
Some(var) => self.value(key, PropertyValue::EnvLength(px(points(extra)), var)),
None => debug_assert!(false, "no environment variable `{name}`"),
}
}
pub(crate) fn env(&mut self, key: StyleKey, var: crate::style::EnvVar) {
self.value(key, PropertyValue::EnvLength(Points::ZERO, var));
}
pub(crate) fn value(&mut self, key: StyleKey, value: PropertyValue) {
self.push(Declaration::Value(key, value));
}
fn checked(&mut self, key: StyleKey, value: Result<PropertyValue, crate::StyleError>) {
match value {
Ok(value) => self.value(key, value),
Err(_) => debug_assert!(false, "an invalid typed value of `{}`", key.name()),
}
}
fn css(&mut self, key: StyleKey, value: &str) {
match key.parse_value(crate::StyleValue::Str(value)) {
Ok(value) => self.value(key, value),
Err(_) => log::warn!("invalid value for style `{}`: {value}", key.name()),
}
}
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.into_vec() {
if v.group != 0 {
v.group = self.name(other.names[v.group as usize - 1]);
}
self.entries.push((v.within(variant), d));
}
for part in other.bound {
self.bound.push(Rc::new(move |s| {
let mut inner = StyleRefinement::default();
part(&mut inner);
s.extend_as(variant, inner);
}));
}
}
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(crate) fn static_color(&self, key: StyleKey) -> Option<AdaptiveColor> {
self.entries.iter().rev().find_map(|(variant, d)| {
if *variant != Variant::default() {
return None;
}
match d {
Declaration::Color(k, color) if *k == key => Some(Some(*color)),
Declaration::Value(k, PropertyValue::Color(color)) if *k == key => {
Some(color.map(AdaptiveColor::from))
}
_ => None,
}
})?
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty() && self.bound.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.iter() {
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.iter() {
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 name = match variant.group {
0 => "",
g => self.names[g as usize - 1],
};
let group = (variant.group_states != 0).then_some((name, variant.group_states));
rules.push(Rule::with(
variant.states,
group,
variant.dark,
variant.rank(name),
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 LayoutDirection {
#[default]
Inherit,
Ltr,
Rtl,
}
crate::static_reactive!(LayoutDirection: LayoutDirection);
#[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 p_safe_area(mut self) -> Self {
let s = self.style();
s.env(StyleKey::PaddingTop, crate::style::EnvVar::SafeAreaInsetTop);
s.env(
StyleKey::PaddingRight,
crate::style::EnvVar::SafeAreaInsetRight,
);
s.env(
StyleKey::PaddingBottom,
crate::style::EnvVar::SafeAreaInsetBottom,
);
s.env(
StyleKey::PaddingLeft,
crate::style::EnvVar::SafeAreaInsetLeft,
);
self
}
fn px_safe_area(mut self) -> Self {
let s = self.style();
s.env(
StyleKey::PaddingRight,
crate::style::EnvVar::SafeAreaInsetRight,
);
s.env(
StyleKey::PaddingLeft,
crate::style::EnvVar::SafeAreaInsetLeft,
);
self
}
fn py_safe_area(mut self) -> Self {
let s = self.style();
s.env(StyleKey::PaddingTop, crate::style::EnvVar::SafeAreaInsetTop);
s.env(
StyleKey::PaddingBottom,
crate::style::EnvVar::SafeAreaInsetBottom,
);
self
}
fn pt_safe_area(mut self) -> Self {
self.style()
.env(StyleKey::PaddingTop, crate::style::EnvVar::SafeAreaInsetTop);
self
}
fn pt_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style()
.env_plus(StyleKey::PaddingTop, "safe-area-inset-top", extra.into());
self
}
fn pr_safe_area(mut self) -> Self {
self.style().env(
StyleKey::PaddingRight,
crate::style::EnvVar::SafeAreaInsetRight,
);
self
}
fn pr_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style().env_plus(
StyleKey::PaddingRight,
"safe-area-inset-right",
extra.into(),
);
self
}
fn pb_safe_area(mut self) -> Self {
self.style().env(
StyleKey::PaddingBottom,
crate::style::EnvVar::SafeAreaInsetBottom,
);
self
}
fn pb_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style().env_plus(
StyleKey::PaddingBottom,
"safe-area-inset-bottom",
extra.into(),
);
self
}
fn pl_safe_area(mut self) -> Self {
self.style().env(
StyleKey::PaddingLeft,
crate::style::EnvVar::SafeAreaInsetLeft,
);
self
}
fn pl_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style()
.env_plus(StyleKey::PaddingLeft, "safe-area-inset-left", extra.into());
self
}
fn pb_keyboard(mut self) -> Self {
self.style().env(
StyleKey::PaddingBottom,
crate::style::EnvVar::KeyboardInsetHeight,
);
self
}
fn pb_keyboard_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style().env_plus(
StyleKey::PaddingBottom,
"keyboard-inset-height",
extra.into(),
);
self
}
fn m_safe_area(mut self) -> Self {
let s = self.style();
s.env(StyleKey::MarginTop, crate::style::EnvVar::SafeAreaInsetTop);
s.env(
StyleKey::MarginRight,
crate::style::EnvVar::SafeAreaInsetRight,
);
s.env(
StyleKey::MarginBottom,
crate::style::EnvVar::SafeAreaInsetBottom,
);
s.env(
StyleKey::MarginLeft,
crate::style::EnvVar::SafeAreaInsetLeft,
);
self
}
fn mx_safe_area(mut self) -> Self {
let s = self.style();
s.env(
StyleKey::MarginRight,
crate::style::EnvVar::SafeAreaInsetRight,
);
s.env(
StyleKey::MarginLeft,
crate::style::EnvVar::SafeAreaInsetLeft,
);
self
}
fn my_safe_area(mut self) -> Self {
let s = self.style();
s.env(StyleKey::MarginTop, crate::style::EnvVar::SafeAreaInsetTop);
s.env(
StyleKey::MarginBottom,
crate::style::EnvVar::SafeAreaInsetBottom,
);
self
}
fn mt_safe_area(mut self) -> Self {
self.style()
.env(StyleKey::MarginTop, crate::style::EnvVar::SafeAreaInsetTop);
self
}
fn mt_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style()
.env_plus(StyleKey::MarginTop, "safe-area-inset-top", extra.into());
self
}
fn mr_safe_area(mut self) -> Self {
self.style().env(
StyleKey::MarginRight,
crate::style::EnvVar::SafeAreaInsetRight,
);
self
}
fn mr_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style()
.env_plus(StyleKey::MarginRight, "safe-area-inset-right", extra.into());
self
}
fn mb_safe_area(mut self) -> Self {
self.style().env(
StyleKey::MarginBottom,
crate::style::EnvVar::SafeAreaInsetBottom,
);
self
}
fn mb_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style().env_plus(
StyleKey::MarginBottom,
"safe-area-inset-bottom",
extra.into(),
);
self
}
fn ml_safe_area(mut self) -> Self {
self.style().env(
StyleKey::MarginLeft,
crate::style::EnvVar::SafeAreaInsetLeft,
);
self
}
fn ml_safe_area_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style()
.env_plus(StyleKey::MarginLeft, "safe-area-inset-left", extra.into());
self
}
fn mb_keyboard(mut self) -> Self {
self.style().env(
StyleKey::MarginBottom,
crate::style::EnvVar::KeyboardInsetHeight,
);
self
}
fn mb_keyboard_plus(mut self, extra: impl Into<AbsoluteLength>) -> Self {
self.style().env_plus(
StyleKey::MarginBottom,
"keyboard-inset-height",
extra.into(),
);
self
}
fn flex(mut self) -> Self {
let s = self.style();
s.value(
StyleKey::Display,
PropertyValue::Display(taffy::Display::Flex),
);
s.push(Declaration::Default(
StyleKey::FlexDirection,
PropertyValue::FlexDirection(taffy::FlexDirection::Row),
));
self
}
fn grid(mut self) -> Self {
self.style().value(
StyleKey::Display,
PropertyValue::Display(taffy::Display::Grid),
);
self
}
fn grid_cols(mut self, count: impl IntoReactive<u16>) -> Self {
self.style().bind_value(count, |s, count: u16| {
s.push(Declaration::Tracks(StyleKey::GridTemplateColumns, count));
});
self
}
fn grid_rows(mut self, count: impl IntoReactive<u16>) -> Self {
self.style().bind_value(count, |s, count: u16| {
s.push(Declaration::Tracks(StyleKey::GridTemplateRows, count));
});
self
}
fn grid_template_columns(mut self, tracks: impl IntoReactive<SharedString>) -> Self {
self.style().bind_value(tracks, |s, tracks: SharedString| {
s.css(StyleKey::GridTemplateColumns, &tracks);
});
self
}
fn grid_template_rows(mut self, tracks: impl IntoReactive<SharedString>) -> Self {
self.style().bind_value(tracks, |s, tracks: SharedString| {
s.css(StyleKey::GridTemplateRows, &tracks);
});
self
}
fn grid_flow_col(mut self) -> Self {
self.style().value(
StyleKey::GridAutoFlow,
PropertyValue::GridAutoFlow(taffy::GridAutoFlow::Column),
);
self
}
fn grid_flow_dense(mut self) -> Self {
self.style().value(
StyleKey::GridAutoFlow,
PropertyValue::GridAutoFlow(taffy::GridAutoFlow::RowDense),
);
self
}
fn col_span(mut self, count: impl IntoReactive<u16>) -> Self {
self.style().bind_value(count, |s, count: u16| {
s.push(Declaration::Span(StyleKey::GridColumn, count));
});
self
}
fn row_span(mut self, count: impl IntoReactive<u16>) -> Self {
self.style().bind_value(count, |s, count: u16| {
s.push(Declaration::Span(StyleKey::GridRow, count));
});
self
}
fn col_span_full(mut self) -> Self {
self.style()
.value(StyleKey::GridColumn, PropertyValue::GridLine(full_line()));
self
}
fn row_span_full(mut self) -> Self {
self.style()
.value(StyleKey::GridRow, PropertyValue::GridLine(full_line()));
self
}
fn col_start(mut self, line: impl IntoReactive<i16>) -> Self {
self.style().bind_value(line, |s, line: i16| {
s.number(StyleKey::GridColumnStart, f32::from(line));
});
self
}
fn col_end(mut self, line: impl IntoReactive<i16>) -> Self {
self.style().bind_value(line, |s, line: i16| {
s.number(StyleKey::GridColumnEnd, f32::from(line));
});
self
}
fn row_start(mut self, line: impl IntoReactive<i16>) -> Self {
self.style().bind_value(line, |s, line: i16| {
s.number(StyleKey::GridRowStart, f32::from(line));
});
self
}
fn row_end(mut self, line: impl IntoReactive<i16>) -> Self {
self.style().bind_value(line, |s, line: i16| {
s.number(StyleKey::GridRowEnd, f32::from(line));
});
self
}
fn hidden(mut self) -> Self {
self.style().value(
StyleKey::Display,
PropertyValue::Display(taffy::Display::None),
);
self
}
fn invisible(mut self) -> Self {
self.style()
.value(StyleKey::Visibility, PropertyValue::Bool(true));
self
}
fn flex_row(mut self) -> Self {
self.style().value(
StyleKey::FlexDirection,
PropertyValue::FlexDirection(taffy::FlexDirection::Row),
);
self
}
fn flex_row_reverse(mut self) -> Self {
self.style().value(
StyleKey::FlexDirection,
PropertyValue::FlexDirection(taffy::FlexDirection::RowReverse),
);
self
}
fn flex_col(mut self) -> Self {
self.style().value(
StyleKey::FlexDirection,
PropertyValue::FlexDirection(taffy::FlexDirection::Column),
);
self
}
fn flex_col_reverse(mut self) -> Self {
self.style().value(
StyleKey::FlexDirection,
PropertyValue::FlexDirection(taffy::FlexDirection::ColumnReverse),
);
self
}
fn flex_wrap(mut self) -> Self {
self.style().value(
StyleKey::FlexWrap,
PropertyValue::FlexWrap(taffy::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: impl IntoReactive<f32>) -> Self {
self.style().bind_value(factor, |s, factor: f32| {
s.number(StyleKey::FlexGrow, factor);
});
self
}
fn flex_shrink(mut self, factor: impl IntoReactive<f32>) -> Self {
self.style().bind_value(factor, |s, factor: f32| {
s.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().value(
StyleKey::AlignItems,
PropertyValue::AlignItems(Some(taffy::AlignItems::FLEX_START)),
);
self
}
fn items_center(mut self) -> Self {
self.style().value(
StyleKey::AlignItems,
PropertyValue::AlignItems(Some(taffy::AlignItems::CENTER)),
);
self
}
fn items_end(mut self) -> Self {
self.style().value(
StyleKey::AlignItems,
PropertyValue::AlignItems(Some(taffy::AlignItems::FLEX_END)),
);
self
}
fn items_stretch(mut self) -> Self {
self.style().value(
StyleKey::AlignItems,
PropertyValue::AlignItems(Some(taffy::AlignItems::STRETCH)),
);
self
}
fn items_baseline(mut self) -> Self {
self.style().value(
StyleKey::AlignItems,
PropertyValue::AlignItems(Some(taffy::AlignItems::BASELINE)),
);
self
}
fn justify_start(mut self) -> Self {
self.style().value(
StyleKey::JustifyContent,
PropertyValue::AlignContent(taffy::AlignContent::FLEX_START),
);
self
}
fn justify_center(mut self) -> Self {
self.style().value(
StyleKey::JustifyContent,
PropertyValue::AlignContent(taffy::AlignContent::CENTER),
);
self
}
fn justify_end(mut self) -> Self {
self.style().value(
StyleKey::JustifyContent,
PropertyValue::AlignContent(taffy::AlignContent::FLEX_END),
);
self
}
fn justify_between(mut self) -> Self {
self.style().value(
StyleKey::JustifyContent,
PropertyValue::AlignContent(taffy::AlignContent::SPACE_BETWEEN),
);
self
}
fn justify_around(mut self) -> Self {
self.style().value(
StyleKey::JustifyContent,
PropertyValue::AlignContent(taffy::AlignContent::SPACE_AROUND),
);
self
}
fn justify_evenly(mut self) -> Self {
self.style().value(
StyleKey::JustifyContent,
PropertyValue::AlignContent(taffy::AlignContent::SPACE_EVENLY),
);
self
}
fn content_start(mut self) -> Self {
self.style().value(
StyleKey::AlignContent,
PropertyValue::AlignContent(taffy::AlignContent::FLEX_START),
);
self
}
fn content_center(mut self) -> Self {
self.style().value(
StyleKey::AlignContent,
PropertyValue::AlignContent(taffy::AlignContent::CENTER),
);
self
}
fn content_end(mut self) -> Self {
self.style().value(
StyleKey::AlignContent,
PropertyValue::AlignContent(taffy::AlignContent::FLEX_END),
);
self
}
fn content_between(mut self) -> Self {
self.style().value(
StyleKey::AlignContent,
PropertyValue::AlignContent(taffy::AlignContent::SPACE_BETWEEN),
);
self
}
fn content_around(mut self) -> Self {
self.style().value(
StyleKey::AlignContent,
PropertyValue::AlignContent(taffy::AlignContent::SPACE_AROUND),
);
self
}
fn content_evenly(mut self) -> Self {
self.style().value(
StyleKey::AlignContent,
PropertyValue::AlignContent(taffy::AlignContent::SPACE_EVENLY),
);
self
}
fn content_stretch(mut self) -> Self {
self.style().value(
StyleKey::AlignContent,
PropertyValue::AlignContent(taffy::AlignContent::STRETCH),
);
self
}
fn self_start(mut self) -> Self {
self.style().value(
StyleKey::AlignSelf,
PropertyValue::AlignItems(Some(taffy::AlignItems::FLEX_START)),
);
self
}
fn self_center(mut self) -> Self {
self.style().value(
StyleKey::AlignSelf,
PropertyValue::AlignItems(Some(taffy::AlignItems::CENTER)),
);
self
}
fn self_end(mut self) -> Self {
self.style().value(
StyleKey::AlignSelf,
PropertyValue::AlignItems(Some(taffy::AlignItems::FLEX_END)),
);
self
}
fn self_stretch(mut self) -> Self {
self.style().value(
StyleKey::AlignSelf,
PropertyValue::AlignItems(Some(taffy::AlignItems::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: impl IntoReactive<f32>) -> Self {
self.style().bind_value(ratio, |s, ratio: f32| {
s.number(StyleKey::AspectRatio, ratio);
});
self
}
fn aspect_square(self) -> Self {
self.aspect_ratio(1.0)
}
fn relative(mut self) -> Self {
self.style().value(
StyleKey::Position,
PropertyValue::Position(taffy::Position::Relative, false, false),
);
self
}
fn absolute(mut self) -> Self {
self.style().value(
StyleKey::Position,
PropertyValue::Position(taffy::Position::Absolute, false, false),
);
self
}
fn sticky(mut self) -> Self {
self.style().value(
StyleKey::Position,
PropertyValue::Position(taffy::Position::Relative, false, true),
);
self
}
fn overflow_hidden(mut self) -> Self {
self.style()
.value(StyleKey::Overflow, PropertyValue::Bool(true));
self
}
fn z_index(mut self, z: impl IntoReactive<i32>) -> Self {
self.style()
.bind_value(z, |s, z: i32| s.number(StyleKey::ZIndex, z as f32));
self
}
fn bg(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::BackgroundColor], color);
});
self
}
fn opacity(mut self, opacity: impl IntoReactive<f32>) -> Self {
self.style().bind_value(opacity, |s, opacity: f32| {
s.number(StyleKey::Opacity, opacity.clamp(0.0, 1.0));
});
self
}
fn rounded(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(&[StyleKey::BorderRadius], radius);
});
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 IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(
&[
StyleKey::BorderTopLeftRadius,
StyleKey::BorderTopRightRadius,
],
radius,
);
});
self
}
fn rounded_b(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(
&[
StyleKey::BorderBottomLeftRadius,
StyleKey::BorderBottomRightRadius,
],
radius,
);
});
self
}
fn border(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.number(StyleKey::BorderWidth, points(width));
});
self
}
fn border_1(self) -> Self {
self.border(px(1.0))
}
fn border_2(self) -> Self {
self.border(px(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 IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::BorderColor], color);
});
self
}
fn border_t(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.number(StyleKey::BorderTopWidth, points(width));
});
self
}
fn border_r(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.number(StyleKey::BorderRightWidth, points(width));
});
self
}
fn border_b(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.number(StyleKey::BorderBottomWidth, points(width));
});
self
}
fn border_l(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.number(StyleKey::BorderLeftWidth, points(width));
});
self
}
fn border_x(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.numbers(
&[StyleKey::BorderLeftWidth, StyleKey::BorderRightWidth],
points(width),
);
});
self
}
fn border_y(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.numbers(
&[StyleKey::BorderTopWidth, StyleKey::BorderBottomWidth],
points(width),
);
});
self
}
fn border_s(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.number(StyleKey::BorderStartWidth, points(width));
});
self
}
fn border_e(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.number(StyleKey::BorderEndWidth, points(width));
});
self
}
fn border_t_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::BorderTopColor], color);
});
self
}
fn border_r_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::BorderRightColor], color);
});
self
}
fn border_b_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::BorderBottomColor], color);
});
self
}
fn border_l_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::BorderLeftColor], color);
});
self
}
fn border_x_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(
&[StyleKey::BorderLeftColor, StyleKey::BorderRightColor],
color,
);
});
self
}
fn border_y_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(
&[StyleKey::BorderTopColor, StyleKey::BorderBottomColor],
color,
);
});
self
}
fn border_s_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::BorderStartColor], color);
});
self
}
fn border_e_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::BorderEndColor], color);
});
self
}
fn border_solid(mut self) -> Self {
self.style().value(
StyleKey::BorderStyle,
PropertyValue::BorderStyle(crate::BorderStyle::Solid, false),
);
self
}
fn border_dashed(mut self) -> Self {
self.style().value(
StyleKey::BorderStyle,
PropertyValue::BorderStyle(crate::BorderStyle::Dashed, false),
);
self
}
fn border_dotted(mut self) -> Self {
self.style().value(
StyleKey::BorderStyle,
PropertyValue::BorderStyle(crate::BorderStyle::Dotted, false),
);
self
}
fn border_none(mut self) -> Self {
self.style().value(
StyleKey::BorderStyle,
PropertyValue::BorderStyle(crate::BorderStyle::Solid, true),
);
self
}
fn border_curve(mut self, curve: BorderCurve) -> Self {
self.style().value(
StyleKey::BorderCurve,
PropertyValue::Bool(matches!(curve, BorderCurve::Continuous)),
);
self
}
fn rounded_tl(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(&[StyleKey::BorderTopLeftRadius], radius);
});
self
}
fn rounded_tr(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(&[StyleKey::BorderTopRightRadius], radius);
});
self
}
fn rounded_br(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(&[StyleKey::BorderBottomRightRadius], radius);
});
self
}
fn rounded_bl(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(&[StyleKey::BorderBottomLeftRadius], radius);
});
self
}
fn rounded_l(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(
&[
StyleKey::BorderTopLeftRadius,
StyleKey::BorderBottomLeftRadius,
],
radius,
);
});
self
}
fn rounded_r(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(
&[
StyleKey::BorderTopRightRadius,
StyleKey::BorderBottomRightRadius,
],
radius,
);
});
self
}
fn rounded_ss(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(&[StyleKey::BorderTopStartRadius], radius);
});
self
}
fn rounded_se(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(&[StyleKey::BorderTopEndRadius], radius);
});
self
}
fn rounded_ee(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(&[StyleKey::BorderBottomEndRadius], radius);
});
self
}
fn rounded_es(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(&[StyleKey::BorderBottomStartRadius], radius);
});
self
}
fn rounded_s(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(
&[
StyleKey::BorderTopStartRadius,
StyleKey::BorderBottomStartRadius,
],
radius,
);
});
self
}
fn rounded_e(mut self, radius: impl IntoReactive<Length>) -> Self {
self.style().bind_value(radius, |s, radius: Length| {
s.lengths(
&[
StyleKey::BorderTopEndRadius,
StyleKey::BorderBottomEndRadius,
],
radius,
);
});
self
}
fn outline(mut self, width: impl Into<AbsoluteLength>) -> Self {
let s = self.style();
s.number(StyleKey::OutlineWidth, points(width.into()));
s.push(Declaration::Default(
StyleKey::OutlineStyle,
PropertyValue::BorderStyle(crate::BorderStyle::Solid, false),
));
self
}
fn outline_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::OutlineColor], color);
});
self
}
fn outline_offset(mut self, offset: impl IntoReactive<AbsoluteLength>) -> Self {
self.style()
.bind_value(offset, |s, offset: AbsoluteLength| {
s.number(StyleKey::OutlineOffset, points(offset));
});
self
}
fn outline_dashed(mut self) -> Self {
let s = self.style();
s.value(
StyleKey::OutlineStyle,
PropertyValue::BorderStyle(crate::BorderStyle::Dashed, false),
);
s.push(Declaration::Default(
StyleKey::OutlineWidth,
PropertyValue::Points(px(3.0)),
));
self
}
fn outline_dotted(mut self) -> Self {
let s = self.style();
s.value(
StyleKey::OutlineStyle,
PropertyValue::BorderStyle(crate::BorderStyle::Dotted, false),
);
s.push(Declaration::Default(
StyleKey::OutlineWidth,
PropertyValue::Points(px(3.0)),
));
self
}
fn outline_none(mut self) -> Self {
self.style().value(
StyleKey::OutlineStyle,
PropertyValue::BorderStyle(crate::BorderStyle::Solid, true),
);
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();
self.style()
.push(Declaration::PartColor(ColorPart::Shadow, color));
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 IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.push(Declaration::PartColor(ColorPart::InsetShadow, color));
});
self
}
fn ring(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.push(Declaration::Ring(Bits(points(width))));
});
self
}
fn ring_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.push(Declaration::PartColor(ColorPart::Ring, color));
});
self
}
fn ring_offset(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.push(Declaration::RingOffset(Bits(points(width))));
});
self
}
fn ring_offset_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.push(Declaration::PartColor(ColorPart::RingOffset, color));
});
self
}
fn ring_inset(mut self) -> Self {
self.style().push(Declaration::RingInset);
self
}
fn inset_ring(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.push(Declaration::InsetRing(Bits(points(width))));
});
self
}
fn inset_ring_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.push(Declaration::PartColor(ColorPart::InsetRing, color));
});
self
}
fn bg_linear(mut self, angle: impl IntoReactive<Radians>) -> Self {
self.style().bind_value(angle, |s, angle: Radians| {
s.push(Declaration::Gradient(GradientShape::Linear(Bits(angle.0))));
});
self
}
fn bg_linear_to_t(self) -> Self {
self.bg_linear(deg(0.0))
}
fn bg_linear_to_r(self) -> Self {
self.bg_linear(deg(90.0))
}
fn bg_linear_to_b(self) -> Self {
self.bg_linear(deg(180.0))
}
fn bg_linear_to_l(self) -> Self {
self.bg_linear(deg(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, angle: impl IntoReactive<Radians>) -> Self {
self.style().bind_value(angle, |s, angle: Radians| {
s.push(Declaration::Gradient(GradientShape::Conic(Bits(angle.0))));
});
self
}
fn bg_gradient_none(mut self) -> Self {
self.style().push(Declaration::GradientNone);
self
}
fn gradient_from(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.push(Declaration::PartColor(ColorPart::From, color));
});
self
}
fn gradient_via(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.push(Declaration::PartColor(ColorPart::Via, color));
});
self
}
fn gradient_to(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.push(Declaration::PartColor(ColorPart::To, color));
});
self
}
fn gradient_from_position(mut self, at: impl IntoReactive<Percentage>) -> Self {
self.style().bind_value(at, |s, at: Percentage| {
s.push(Declaration::StopPosition(0, Bits(at.0)));
});
self
}
fn gradient_via_position(mut self, at: impl IntoReactive<Percentage>) -> Self {
self.style().bind_value(at, |s, at: Percentage| {
s.push(Declaration::StopPosition(1, Bits(at.0)));
});
self
}
fn gradient_to_position(mut self, at: impl IntoReactive<Percentage>) -> Self {
self.style().bind_value(at, |s, at: Percentage| {
s.push(Declaration::StopPosition(2, Bits(at.0)));
});
self
}
fn blur(self, radius: impl Into<Points>) -> Self {
filter(self, false, FilterFn::Blur, radius.into().0)
}
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, angle: impl Into<Radians>) -> Self {
filter(self, false, FilterFn::HueRotate, angle.into().to_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: impl Into<Points>) -> Self {
filter(self, true, FilterFn::Blur, radius.into().0)
}
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, angle: impl Into<Radians>) -> Self {
filter(self, true, FilterFn::HueRotate, angle.into().to_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()
.value(StyleKey::MixBlendMode, PropertyValue::BlendMode(mode));
self
}
fn pointer_events(mut self, pointer_events: impl IntoReactive<crate::PointerEvents>) -> Self {
self.style()
.bind_value(pointer_events, |s, p: crate::PointerEvents| {
s.value(
StyleKey::PointerEvents,
PropertyValue::PointerEvents(Some(p)),
);
});
self
}
fn select_text(mut self) -> Self {
self.style()
.value(StyleKey::UserSelect, PropertyValue::OptBool(Some(true)));
self
}
fn select_none(mut self) -> Self {
self.style()
.value(StyleKey::UserSelect, PropertyValue::OptBool(Some(false)));
self
}
fn glass_effect(mut self, glass: crate::GlassEffect) -> Self {
self.style()
.value(StyleKey::GlassEffect, PropertyValue::GlassEffect(glass));
self
}
fn glass_tint_color(mut self, color: impl IntoReactive<Option<AdaptiveColor>>) -> Self {
self.style()
.bind_value(color, |s, color: Option<AdaptiveColor>| match color {
Some(color) => s.color(&[StyleKey::GlassTintColor], color),
None => s.value(StyleKey::GlassTintColor, PropertyValue::Color(None)),
});
self
}
fn cursor(mut self, cursor: Cursor) -> Self {
self.style()
.value(StyleKey::Cursor, PropertyValue::Cursor(cursor));
self
}
fn cursor_pointer(self) -> Self {
self.cursor(Cursor::Pointer)
}
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: impl IntoReactive<f32>) -> Self {
self.style().bind_value(ms, |s, ms: f32| {
s.push(Declaration::Duration(Bits(ms)));
});
self
}
fn delay(mut self, ms: impl IntoReactive<f32>) -> Self {
self.style().bind_value(ms, |s, ms: f32| {
s.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,
crate::style::frame_rate(animation.frame_rate).map(Bits),
));
self
}
fn animate_none(mut self) -> Self {
self.style().push(Declaration::Animate(None));
self
}
fn scale(self, scale: impl IntoReactive<f32>) -> Self {
self.transform_step(TransformKind::Scale, scale)
}
fn scale_x(self, scale: impl IntoReactive<f32>) -> Self {
self.transform_step(TransformKind::ScaleX, scale)
}
fn scale_y(self, scale: impl IntoReactive<f32>) -> Self {
self.transform_step(TransformKind::ScaleY, scale)
}
fn translate_x(self, offset: impl IntoReactive<DefiniteLength>) -> Self {
transform_with(self, offset, |offset| {
translation(
offset,
TransformKind::TranslateX,
TransformKind::TranslateXFraction,
)
})
}
fn translate_y(self, offset: impl IntoReactive<DefiniteLength>) -> Self {
transform_with(self, offset, |offset| {
translation(
offset,
TransformKind::TranslateY,
TransformKind::TranslateYFraction,
)
})
}
fn rotate(self, angle: impl IntoReactive<Radians>) -> Self {
transform_with(self, angle, |a: Radians| {
(TransformKind::Rotate, a.to_degrees())
})
}
fn rotate_x(self, angle: impl IntoReactive<Radians>) -> Self {
transform_with(self, angle, |a: Radians| {
(TransformKind::RotateX, a.to_degrees())
})
}
fn rotate_y(self, angle: impl IntoReactive<Radians>) -> Self {
transform_with(self, angle, |a: Radians| {
(TransformKind::RotateY, a.to_degrees())
})
}
fn skew_x(self, angle: impl IntoReactive<Radians>) -> Self {
transform_with(self, angle, |a: Radians| {
(TransformKind::SkewX, a.to_degrees())
})
}
fn skew_y(self, angle: impl IntoReactive<Radians>) -> Self {
transform_with(self, angle, |a: Radians| {
(TransformKind::SkewY, a.to_degrees())
})
}
fn perspective(self, distance: impl IntoReactive<AbsoluteLength>) -> Self {
transform_with(self, distance, |d: AbsoluteLength| {
(TransformKind::Perspective, points(d))
})
}
fn transform_step(self, kind: TransformKind, amount: impl IntoReactive<f32>) -> Self {
transform_with(self, amount, move |amount| (kind, amount))
}
fn transform_none(self) -> Self {
transform_reset(self, Declaration::TransformNone)
}
fn translate_none(self) -> Self {
transform_reset(self, Declaration::TranslateNone)
}
fn scale_none(self) -> Self {
transform_reset(self, Declaration::ScaleNone)
}
fn rotate_none(self) -> Self {
transform_reset(self, Declaration::RotateNone)
}
fn transform_origin(mut self, origin: TransformOrigin) -> Self {
let axis = |l: DefiniteLength| match l {
DefiniteLength::Absolute(a) => (false, Bits(a.to_points(REM_SIZE).0)),
DefiniteLength::Fraction(f) => (true, Bits(f.0)),
};
self.style()
.push(Declaration::Origin([axis(origin.x), axis(origin.y)]));
self
}
fn origin_top_left(mut self) -> Self {
self.style().value(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(origin(0.0, 0.0)),
);
self
}
fn origin_top(mut self) -> Self {
self.style().value(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(origin(0.5, 0.0)),
);
self
}
fn origin_top_right(mut self) -> Self {
self.style().value(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(origin(1.0, 0.0)),
);
self
}
fn origin_left(mut self) -> Self {
self.style().value(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(origin(0.0, 0.5)),
);
self
}
fn origin_center(mut self) -> Self {
self.style().value(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(origin(0.5, 0.5)),
);
self
}
fn origin_right(mut self) -> Self {
self.style().value(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(origin(1.0, 0.5)),
);
self
}
fn origin_bottom_left(mut self) -> Self {
self.style().value(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(origin(0.0, 1.0)),
);
self
}
fn origin_bottom(mut self) -> Self {
self.style().value(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(origin(0.5, 1.0)),
);
self
}
fn origin_bottom_right(mut self) -> Self {
self.style().value(
StyleKey::TransformOrigin,
PropertyValue::TransformOrigin(origin(1.0, 1.0)),
);
self
}
fn object_fit(mut self, fit: impl IntoReactive<crate::ResizeMode>) -> Self {
self.style().bind_value(fit, |s, fit: crate::ResizeMode| {
s.value(StyleKey::ObjectFit, PropertyValue::ObjectFit(Some(fit)));
});
self
}
fn object_position(mut self, position: ObjectPosition) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(position),
);
self
}
fn object_top_left(mut self) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(ObjectPosition::new(
PositionAxis::START,
PositionAxis::START,
)),
);
self
}
fn object_top(mut self) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(ObjectPosition::new(
PositionAxis::CENTER,
PositionAxis::START,
)),
);
self
}
fn object_top_right(mut self) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(ObjectPosition::new(
PositionAxis::END,
PositionAxis::START,
)),
);
self
}
fn object_left(mut self) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(ObjectPosition::new(
PositionAxis::START,
PositionAxis::CENTER,
)),
);
self
}
fn object_center(mut self) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(ObjectPosition::new(
PositionAxis::CENTER,
PositionAxis::CENTER,
)),
);
self
}
fn object_right(mut self) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(ObjectPosition::new(
PositionAxis::END,
PositionAxis::CENTER,
)),
);
self
}
fn object_bottom_left(mut self) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(ObjectPosition::new(
PositionAxis::START,
PositionAxis::END,
)),
);
self
}
fn object_bottom(mut self) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(ObjectPosition::new(
PositionAxis::CENTER,
PositionAxis::END,
)),
);
self
}
fn object_bottom_right(mut self) -> Self {
self.style().value(
StyleKey::ObjectPosition,
PropertyValue::ObjectPosition(ObjectPosition::new(
PositionAxis::END,
PositionAxis::END,
)),
);
self
}
fn backface_hidden(mut self) -> Self {
self.style()
.value(StyleKey::BackfaceVisibility, PropertyValue::Bool(true));
self
}
fn backface_visible(mut self) -> Self {
self.style()
.value(StyleKey::BackfaceVisibility, PropertyValue::Bool(false));
self
}
fn text_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::Color], color);
});
self
}
fn tint_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::TintColor], color);
});
self
}
fn fill_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::Fill], color);
});
self
}
fn fill_none(mut self) -> Self {
self.style().value(
StyleKey::Fill,
PropertyValue::Paint(Some(crate::SvgPaint::None)),
);
self
}
fn fill_current(mut self) -> Self {
self.style().value(
StyleKey::Fill,
PropertyValue::Paint(Some(crate::SvgPaint::CurrentColor)),
);
self
}
fn stroke_color(mut self, color: impl IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::Stroke], color);
});
self
}
fn stroke_none(mut self) -> Self {
self.style().value(
StyleKey::Stroke,
PropertyValue::Paint(Some(crate::SvgPaint::None)),
);
self
}
fn stroke_current(mut self) -> Self {
self.style().value(
StyleKey::Stroke,
PropertyValue::Paint(Some(crate::SvgPaint::CurrentColor)),
);
self
}
fn stroke_width(mut self, width: impl IntoReactive<AbsoluteLength>) -> Self {
self.style().bind_value(width, |s, width: AbsoluteLength| {
s.number(StyleKey::StrokeWidth, points(width));
});
self
}
fn text_size(mut self, size: impl IntoReactive<Length>) -> Self {
self.style().bind_value(size, |s, size: Length| {
s.lengths(&[StyleKey::FontSize], size);
});
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 IntoReactive<LineHeight>) -> Self {
self.style().bind_value(height, |s, height: LineHeight| {
s.value(StyleKey::LineHeight, PropertyValue::LineHeight(height));
});
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 IntoReactive<SharedString>) -> Self {
self.style().bind_value(family, |s, family: SharedString| {
s.value(
StyleKey::FontFamily,
PropertyValue::FontFamily(Some(crate::FontFamily::new(family.trim()))),
);
});
self
}
fn italic(mut self) -> Self {
self.style()
.value(StyleKey::FontStyle, PropertyValue::OptBool(Some(true)));
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 IntoReactive<AdaptiveColor>) -> Self {
self.style().bind_value(color, |s, color: AdaptiveColor| {
s.color(&[StyleKey::TextDecorationColor], color);
});
self
}
fn text_decoration_solid(mut self) -> Self {
self.style().value(
StyleKey::TextDecorationStyle,
PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Solid)),
);
self
}
fn text_decoration_double(mut self) -> Self {
self.style().value(
StyleKey::TextDecorationStyle,
PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Double)),
);
self
}
fn text_decoration_dotted(mut self) -> Self {
self.style().value(
StyleKey::TextDecorationStyle,
PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Dotted)),
);
self
}
fn text_decoration_dashed(mut self) -> Self {
self.style().value(
StyleKey::TextDecorationStyle,
PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Dashed)),
);
self
}
fn text_decoration_wavy(mut self) -> Self {
self.style().value(
StyleKey::TextDecorationStyle,
PropertyValue::DecorationStyle(Some(crate::DecorationStyle::Wavy)),
);
self
}
fn text_decoration_thickness(mut self, thickness: impl IntoReactive<Points>) -> Self {
self.style().bind_value(thickness, |s, thickness: Points| {
s.number(StyleKey::TextDecorationThickness, thickness.0);
});
self
}
fn underline_offset(mut self, offset: impl IntoReactive<Points>) -> Self {
self.style().bind_value(offset, |s, offset: Points| {
s.number(StyleKey::TextUnderlineOffset, offset.0);
});
self
}
fn uppercase(mut self) -> Self {
self.style().value(
StyleKey::TextTransform,
PropertyValue::TextTransform(Some(crate::TextTransform::Uppercase)),
);
self
}
fn lowercase(mut self) -> Self {
self.style().value(
StyleKey::TextTransform,
PropertyValue::TextTransform(Some(crate::TextTransform::Lowercase)),
);
self
}
fn capitalize(mut self) -> Self {
self.style().value(
StyleKey::TextTransform,
PropertyValue::TextTransform(Some(crate::TextTransform::Capitalize)),
);
self
}
fn normal_case(mut self) -> Self {
self.style().value(
StyleKey::TextTransform,
PropertyValue::TextTransform(Some(crate::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, !FontVariant::SMALL_CAPS)
}
fn direction(mut self, direction: impl IntoReactive<LayoutDirection>) -> Self {
self.style()
.bind_value(direction, |s, direction: LayoutDirection| {
s.value(
StyleKey::Direction,
PropertyValue::OptBool(match direction {
LayoutDirection::Inherit => None,
LayoutDirection::Ltr => Some(false),
LayoutDirection::Rtl => Some(true),
}),
);
});
self
}
fn number_of_lines(mut self, lines: impl IntoReactive<u32>) -> Self {
self.style().bind_value(lines, |s, lines: u32| {
s.value(
StyleKey::NumberOfLines,
PropertyValue::NumberOfLines(Some(lines)),
);
});
self
}
fn text_overflow(mut self, mode: impl IntoReactive<crate::EllipsizeMode>) -> Self {
self.style()
.bind_value(mode, |s, mode: crate::EllipsizeMode| {
s.value(
StyleKey::TextOverflow,
PropertyValue::TextOverflow(Some(mode)),
);
});
self
}
fn truncate(self) -> Self {
self.number_of_lines(1u32)
.text_overflow(crate::EllipsizeMode::Tail)
}
fn writing_direction(mut self, direction: WritingDirection) -> Self {
self.style().value(
StyleKey::WritingDirection,
PropertyValue::OptBool(match direction {
WritingDirection::Auto => None,
WritingDirection::Ltr => Some(false),
WritingDirection::Rtl => Some(true),
}),
);
self
}
fn text_justify(mut self) -> Self {
self.style().value(
StyleKey::TextAlign,
PropertyValue::TextAlign(Some(crate::TextAlign::Justify), false),
);
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();
self.style()
.push(Declaration::PartColor(ColorPart::TextShadow, color));
self
}
fn text_shadow(mut self, layers: impl IntoIterator<Item = crate::TextShadow>) -> Self {
let layers: Arc<[crate::TextShadow]> = layers.into_iter().collect();
self.style()
.push(Declaration::TextShadows(TextLayers(layers)));
self
}
fn text_left(mut self) -> Self {
self.style().value(
StyleKey::TextAlign,
PropertyValue::TextAlign(Some(crate::TextAlign::Left), true),
);
self
}
fn text_center(mut self) -> Self {
self.style().value(
StyleKey::TextAlign,
PropertyValue::TextAlign(Some(crate::TextAlign::Center), false),
);
self
}
fn text_right(mut self) -> Self {
self.style().value(
StyleKey::TextAlign,
PropertyValue::TextAlign(Some(crate::TextAlign::Right), true),
);
self
}
fn align_baseline(mut self) -> Self {
self.style().value(
StyleKey::VerticalAlign,
PropertyValue::VerticalAlign(crate::VerticalAlign::Baseline),
);
self
}
fn align_text_top(mut self) -> Self {
self.style().value(
StyleKey::VerticalAlign,
PropertyValue::VerticalAlign(crate::VerticalAlign::TextTop),
);
self
}
fn align_text_bottom(mut self) -> Self {
self.style().value(
StyleKey::VerticalAlign,
PropertyValue::VerticalAlign(crate::VerticalAlign::TextBottom),
);
self
}
fn align_middle(mut self) -> Self {
self.style().value(
StyleKey::VerticalAlign,
PropertyValue::VerticalAlign(crate::VerticalAlign::Middle),
);
self
}
fn letter_spacing(mut self, spacing: impl IntoReactive<AbsoluteLength>) -> Self {
self.style()
.bind_value(spacing, |s, spacing: AbsoluteLength| {
s.number(StyleKey::LetterSpacing, points(spacing));
});
self
}
fn style_when(
mut self,
when: impl IntoReactive<bool>,
f: impl FnOnce(StyleRefinement) -> StyleRefinement,
) -> Self {
let layer = f(StyleRefinement::default());
match when.into_reactive() {
Reactive::Static(true) => self.style().extend_as(Variant::default(), layer),
Reactive::Static(false) => {}
Reactive::Bound(when) => self.style().bind(move |s| {
if when() {
s.extend_as(Variant::default(), layer.resolved());
}
}),
}
self
}
fn style_with(mut self, f: impl Fn(StyleRefinement) -> StyleRefinement + 'static) -> Self {
self.style().bind(move |s| {
let made = f(StyleRefinement::default()).resolved();
s.extend_as(Variant::default(), made);
});
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 selected(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
let s = f(StyleRefinement::default());
self.style().extend_as(Variant::SELECTED, s);
self
}
fn checked(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
let s = f(StyleRefinement::default());
self.style().extend_as(Variant::CHECKED, s);
self
}
fn indeterminate(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
let s = f(StyleRefinement::default());
self.style().extend_as(Variant::INDETERMINATE, s);
self
}
fn expanded(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
let s = f(StyleRefinement::default());
self.style().extend_as(Variant::EXPANDED, s);
self
}
fn aria_pressed(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
let s = f(StyleRefinement::default());
self.style().extend_as(Variant::ARIA_PRESSED, 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_focus_visible(self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self {
in_group(self, "", state::FOCUS_VISIBLE, 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 group_focus_visible_named(
self,
name: &'static str,
f: impl FnOnce(StyleRefinement) -> StyleRefinement,
) -> Self {
in_group(self, name, state::FOCUS_VISIBLE, f)
}
}
fn transform_with<S: Styled, T: Clone + 'static>(
mut s: S,
value: impl IntoReactive<T>,
step: impl Fn(T) -> (TransformKind, f32) + 'static,
) -> S {
let style = s.style();
match value.into_reactive() {
Reactive::Static(value) if !style.is_bound() => {
let (kind, amount) = step(value);
style.push(Declaration::Transform(kind, Bits(amount)));
}
value => style.bind(move |st| {
let (kind, amount) = step(value.get());
st.push(Declaration::Transform(kind, Bits(amount)));
}),
}
s
}
fn transform_reset<S: Styled>(mut s: S, reset: Declaration) -> S {
let style = s.style();
if style.is_bound() {
style.bind(move |st| st.push(reset.clone()));
} else {
style.push(reset);
}
s
}
fn translation(
offset: DefiniteLength,
points_kind: TransformKind,
fraction_kind: TransformKind,
) -> (TransformKind, f32) {
match offset {
DefiniteLength::Absolute(a) => (points_kind, points(a)),
DefiniteLength::Fraction(f) => (fraction_kind, f.0),
}
}
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: u16,
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,
color::rgba,
element::palette::{EMERALD, PINK, RED, SKY, VIOLET},
geometry::point,
tailwind::{ClassEnvironment, ClassProps, Context},
};
fn resolve(list: &ClassList, dark: bool, states: u16, group: u16) -> String {
resolve_with(list, dark, states, group, &|_| {})
}
fn resolve_with(
list: &ClassList,
dark: bool,
states: u16,
group: u16,
inline: &dyn Fn(&mut Style),
) -> String {
let cx = Context {
env: ClassEnvironment {
dark,
..Default::default()
},
window: crate::geometry::size_pt(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 env_methods_are_the_arbitrary_classes() {
let env_of = |list: &ClassList| {
let cx = Context {
env: ClassEnvironment::default(),
window: crate::geometry::size_pt(390.0, 844.0),
rtl: false,
states: 0,
position: 0,
group: &|_| 0,
};
let mut style = Style::default();
list.apply(
&cx,
&PRESETS,
&mut style,
&mut ClassProps::default(),
|_: &mut Style| {},
);
style.pending.env
};
let sides = |p: &str| {
["top", "right", "bottom", "left"]
.map(|side| format!("{p}{}-[env(safe-area-inset-{side})]", &side[..1]))
.join(" ")
};
for (typed, classes) in [
(s().p_safe_area(), sides("p")),
(s().m_safe_area(), sides("m")),
(
s().px_safe_area(),
"pr-[env(safe-area-inset-right)] pl-[env(safe-area-inset-left)]".into(),
),
(
s().my_safe_area(),
"mt-[env(safe-area-inset-top)] mb-[env(safe-area-inset-bottom)]".into(),
),
(s().pl_safe_area(), "pl-[env(safe-area-inset-left)]".into()),
(
s().pt_safe_area_plus(px(8.0)),
"pt-[calc(env(safe-area-inset-top)+8px)]".into(),
),
(s().pb_keyboard(), "pb-[env(keyboard-inset-height)]".into()),
(
s().mb_keyboard_plus(px(49.0)),
"mb-[calc(env(keyboard-inset-height)+49px)]".into(),
),
] {
same(typed.clone(), &classes);
let parsed = tailwind::parse(&PRESETS, &classes);
assert_eq!(env_of(&typed.lower()), env_of(&parsed), "{classes}");
assert!(!env_of(&parsed).is_empty(), "{classes}");
}
}
#[test]
fn svg_paint_is_tailwinds() {
same(
s().fill_color(RED.shade(600))
.stroke_color(SKY.shade(500))
.stroke_width(px(2.0)),
"fill-red-600 stroke-sky-500 stroke-2",
);
same(s().fill_none().stroke_current(), "fill-none stroke-current");
same(s().fill_current().stroke_none(), "fill-current stroke-none");
}
#[test]
fn flex_is_tailwinds_row() {
same(s().flex(), "flex");
same(s().flex().flex_col(), "flex flex-col");
same(s().flex_col().flex(), "flex-col flex");
same(s().items_center(), "items-center");
}
#[test]
fn auto_minimum_sizes_are_tailwinds() {
same(
s().min_w(crate::geometry::auto())
.min_h(crate::geometry::auto()),
"min-w-auto min-h-auto",
);
}
#[test]
fn borders_and_corners_are_tailwinds() {
same(
s().border_t(px(6.0))
.border_t_color(RED.shade(600))
.border_r(px(2.0))
.border_b(px(4.0))
.border_l(px(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(px(3.0))
.border_s(px(1.0))
.border_e(px(2.0))
.border_dashed(),
"border-y-3 border-s border-e-2 border-dashed",
);
same(s().border_none().border(px(2.0)), "border-none border-2");
same(
s().border(px(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(px(2.0))
.outline_offset(px(2.0))
.outline_dashed()
.outline_color(PINK.shade(500)),
"outline-2 outline-offset-2 outline-dashed outline-pink-500",
);
same(
s().outline_dotted().outline(px(2.0)),
"outline-dotted outline-2",
);
same(s().outline_dashed(), "outline-dashed");
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).opacity(0.5);
same(
s().shadow_lg().shadow_color(emerald),
"shadow-lg shadow-emerald-500/50",
);
same(
s().shadow_xl().shadow_color(SKY.shade(500)),
"shadow-xl shadow-sky-500",
);
same(s().inset_shadow_sm(), "inset-shadow-sm");
same(
s().ring(px(2.0))
.ring_color(SKY.shade(500))
.ring_offset(px(2.0)),
"ring-2 ring-sky-500 ring-offset-2",
);
same(
s().ring(px(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(&tailwind::parse(&PRESETS, &classes), dark, 0, 0)
);
}
}
#[test]
fn custom_shadows_are_layers_of_their_own() {
let list = s()
.text_shadow([crate::TextShadow {
color: rgba(0x0000_0099).into(),
offset_x: px(2.0),
offset_y: px(2.0),
radius: px(4.0),
}])
.lower();
let mut style = Style::default();
list.apply(
&Context {
env: ClassEnvironment::default(),
window: crate::geometry::size_pt(390.0, 844.0),
rtl: false,
states: 0,
position: 0,
group: &|_| 0,
},
&PRESETS,
&mut style,
&mut ClassProps::default(),
|_| {},
);
assert_eq!(style.text.shadow_color, Some(rgba(0x0000_0099).into()));
assert_eq!(style.text.shadow_radius, Some(px(4.0)));
assert_eq!(style.text.shadow_offset, Some(point(px(2.0), px(2.0))));
let layer = BoxShadow {
offset_x: px(0.0),
offset_y: px(2.0),
blur: px(4.0),
spread: px(0.0),
color: rgba(0x0000_000d).into(),
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(deg(45.0))
.gradient_from(SKY.shade(400))
.gradient_to(VIOLET.shade(600))
.gradient_to_position(percentage(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(deg(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(px(8.0)).brightness(0.5), "blur-sm brightness-50");
same(
s().saturate(1.5).hue_rotate(deg(90.0)),
"saturate-150 hue-rotate-90",
);
same(
s().backdrop_blur(px(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 keyframe_animations_take_their_frame_rate() {
let capped = |hz: f32| {
move |style: &mut Style| {
use crate::StyleValue;
for (key, value) in [
(StyleKey::AnimationName, StyleValue::Str("spin")),
(StyleKey::AnimationDuration, StyleValue::Number(800.0)),
(StyleKey::AnimationTimingFunction, StyleValue::Str("linear")),
(StyleKey::AnimationFrameRate, StyleValue::Number(hz)),
] {
style.set_key(key, value).unwrap();
}
}
};
same_with(
s().animation(
KeyframeAnimation::new(Keyframes::Spin)
.duration(800.0)
.frame_rate(30.0),
),
"animate-none",
&capped(30.0),
);
let typed = s()
.animation(KeyframeAnimation::new(Keyframes::Spin).frame_rate(24.0))
.lower();
assert!(resolve(&typed, false, 0, 0).contains("frame_rate: Some(24.0)"));
}
#[test]
fn transforms_are_tailwinds() {
same(
s().rotate(deg(12.0)).skew_x(deg(6.0)).scale(0.9),
"rotate-12 skew-x-6 scale-90",
);
same(
s().perspective(px(400.0))
.rotate_y(deg(35.0))
.rotate_x(deg(40.0)),
"perspective-[400px] rotate-y-35 rotate-x-40",
);
same(s().scale_x(1.5).skew_y(deg(-3.0)), "scale-x-150 -skew-y-3");
same(
s().rotate(deg(12.0))
.rotate_x(deg(40.0))
.skew_x(deg(6.0))
.scale(0.9)
.transform_none(),
"rotate-12 rotate-x-40 skew-x-6 scale-90 transform-none",
);
same(
s().translate_x(px(8.0))
.rotate(deg(12.0))
.scale(0.9)
.translate_none()
.rotate_none()
.scale_none(),
"translate-x-2 rotate-12 scale-90 translate-none rotate-none scale-none",
);
same(
s().origin_top_left().backface_hidden(),
"origin-top-left backface-hidden",
);
same(
s().transform_origin(TransformOrigin {
x: px(10.0).into(),
y: relative(0.25),
z: Points::ZERO,
}),
"origin-[10px_25%]",
);
}
#[test]
fn text_is_tailwinds() {
same(
s().underline()
.text_decoration_wavy()
.text_decoration_color(RED.shade(500))
.text_decoration_thickness(px(2.0))
.underline_offset(px(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");
same(s().align_baseline(), "align-baseline");
same(s().align_text_top(), "align-text-top");
same(s().align_text_bottom(), "align-text-bottom");
same(s().align_middle(), "align-middle");
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(px(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");
}
}