use gpui::{
CursorStyle, Div, FontWeight, InteractiveElement, Refineable, Stateful, StyleRefinement, Styled,
};
use crate::theme::Theme;
mod ambient;
mod decl;
mod values;
pub use ambient::{
current_theme, focus_visible, set_focus_ring_mode, set_keyboard_modality, set_theme_snapshot,
FocusRingMode,
};
use decl::resolve;
pub use decl::Decl;
pub use values::{
ColorToken, Corners, Edges, SxAlign, SxColor, SxDirection, SxDisplay, SxFlex, SxFont,
SxJustify, SxLength, SxRadius, SxShadow, SxText, SxTextAlign,
};
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Sx {
base: Vec<Decl>,
hover: Vec<Decl>,
focus: Vec<Decl>,
active: Vec<Decl>,
}
macro_rules! decl_methods {
($($(#[$doc:meta])* $name:ident($($arg:ident: $ty:ty),*) => $decl:expr;)*) => {
$(
$(#[$doc])*
#[must_use]
pub fn $name(mut self, $($arg: $ty),*) -> Self {
self.base.push($decl);
self
}
)*
};
}
impl Sx {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn decl(mut self, decl: Decl) -> Self {
self.base.push(decl);
self
}
#[must_use]
pub fn hover(mut self, styles: impl FnOnce(Sx) -> Sx) -> Self {
let state = styles(Sx::new());
self.hover.extend(state.base);
self
}
#[must_use]
pub fn focus(mut self, styles: impl FnOnce(Sx) -> Sx) -> Self {
let state = styles(Sx::new());
self.focus.extend(state.base);
self
}
#[must_use]
pub fn active(mut self, styles: impl FnOnce(Sx) -> Sx) -> Self {
let state = styles(Sx::new());
self.active.extend(state.base);
self
}
pub fn merge(&mut self, other: &Sx) {
self.base.extend(other.base.iter().cloned());
self.hover.extend(other.hover.iter().cloned());
self.focus.extend(other.focus.iter().cloned());
self.active.extend(other.active.iter().cloned());
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.base.is_empty()
&& self.hover.is_empty()
&& self.focus.is_empty()
&& self.active.is_empty()
}
#[must_use]
pub fn resolve_base(&self, theme: &Theme) -> StyleRefinement {
resolve(&self.base, theme)
}
decl_methods! {
flex() => Decl::Display(SxDisplay::Flex);
block() => Decl::Display(SxDisplay::Block);
hidden() => Decl::Display(SxDisplay::Hidden);
direction(direction: SxDirection) => Decl::Direction(direction);
flex_row() => Decl::Direction(SxDirection::Row);
flex_col() => Decl::Direction(SxDirection::Column);
wrap(wrap: bool) => Decl::Wrap(wrap);
flex_1() => Decl::Flex(SxFlex::One);
flex_auto() => Decl::Flex(SxFlex::Auto);
flex_none() => Decl::Flex(SxFlex::None);
grow(grow: f32) => Decl::Grow(grow);
shrink(shrink: f32) => Decl::Shrink(shrink);
basis(length: impl Into<SxLength>) => Decl::Basis(length.into());
align(align: SxAlign) => Decl::Align(align);
align_self(align: SxAlign) => Decl::AlignSelf(align);
justify(justify: SxJustify) => Decl::Justify(justify);
gap(length: impl Into<SxLength>) => Decl::Gap(length.into());
gap_x(length: impl Into<SxLength>) => Decl::GapX(length.into());
gap_y(length: impl Into<SxLength>) => Decl::GapY(length.into());
relative() => Decl::Absolute(false);
absolute() => Decl::Absolute(true);
inset(edges: Edges, length: impl Into<SxLength>) => Decl::Inset(edges, length.into());
overflow_hidden() => Decl::OverflowHidden(Edges::All);
w(length: impl Into<SxLength>) => Decl::Width(length.into());
h(length: impl Into<SxLength>) => Decl::Height(length.into());
min_w(length: impl Into<SxLength>) => Decl::MinWidth(length.into());
max_w(length: impl Into<SxLength>) => Decl::MaxWidth(length.into());
min_h(length: impl Into<SxLength>) => Decl::MinHeight(length.into());
max_h(length: impl Into<SxLength>) => Decl::MaxHeight(length.into());
aspect_ratio(ratio: f32) => Decl::AspectRatio(ratio);
p(length: impl Into<SxLength>) => Decl::Padding(Edges::All, length.into());
px(length: impl Into<SxLength>) => Decl::Padding(Edges::X, length.into());
py(length: impl Into<SxLength>) => Decl::Padding(Edges::Y, length.into());
padding(edges: Edges, length: impl Into<SxLength>) => Decl::Padding(edges, length.into());
m(length: impl Into<SxLength>) => Decl::Margin(Edges::All, length.into());
margin(edges: Edges, length: impl Into<SxLength>) => Decl::Margin(edges, length.into());
bg(color: impl Into<SxColor>) => Decl::Background(color.into());
text_color(color: impl Into<SxColor>) => Decl::TextColor(color.into());
border_color(color: impl Into<SxColor>) => Decl::BorderColor(color.into());
border(width: f32) => Decl::BorderWidth(Edges::All, gpui::px(width));
border_on(edges: Edges, width: f32) => Decl::BorderWidth(edges, gpui::px(width));
rounded(radius: impl Into<SxRadius>) => Decl::Radius(Corners::All, radius.into());
rounded_on(corners: Corners, radius: impl Into<SxRadius>) => Decl::Radius(corners, radius.into());
shadow(shadow: SxShadow) => Decl::Shadow(shadow);
opacity(opacity: f32) => Decl::Opacity(opacity);
cursor(cursor: CursorStyle) => Decl::Cursor(cursor);
text(size: SxText) => Decl::Text(size);
font_weight(weight: FontWeight) => Decl::FontWeight(weight);
font(font: SxFont) => Decl::Font(font);
line_height(length: impl Into<SxLength>) => Decl::LineHeight(length.into());
text_align(align: SxTextAlign) => Decl::TextAlign(align);
nowrap() => Decl::NoWrap(true);
truncate() => Decl::Truncate;
line_clamp(lines: usize) => Decl::LineClamp(lines);
italic() => Decl::Italic;
underline() => Decl::Underline;
line_through() => Decl::LineThrough;
border_style(border_style: gpui::BorderStyle) => Decl::BorderStyle(border_style);
}
}
impl Sx {
#[must_use]
pub fn rounded_full(self) -> Self {
self.rounded(SxRadius::Full)
}
}
pub trait SxArg {
fn merge_into(self, target: &mut Sx);
}
impl<T: SxArg + Clone> SxArg for &T {
fn merge_into(self, target: &mut Sx) {
self.clone().merge_into(target);
}
}
impl SxArg for Sx {
fn merge_into(self, target: &mut Sx) {
if target.is_empty() {
*target = self;
} else {
target.merge(&self);
}
}
}
impl<T: SxArg> SxArg for Option<T> {
fn merge_into(self, target: &mut Sx) {
if let Some(style) = self {
style.merge_into(target);
}
}
}
impl<T: SxArg, const N: usize> SxArg for [T; N] {
fn merge_into(self, target: &mut Sx) {
for style in self {
style.merge_into(target);
}
}
}
impl<T: SxArg> SxArg for Vec<T> {
fn merge_into(self, target: &mut Sx) {
for style in self {
style.merge_into(target);
}
}
}
macro_rules! tuple_sx_arg {
($($name:ident),+) => {
impl<$($name: SxArg),+> SxArg for ($($name,)+) {
#[allow(non_snake_case)]
fn merge_into(self, target: &mut Sx) {
let ($($name,)+) = self;
$($name.merge_into(target);)+
}
}
};
}
tuple_sx_arg!(A);
tuple_sx_arg!(A, B);
tuple_sx_arg!(A, B, C);
tuple_sx_arg!(A, B, C, D);
tuple_sx_arg!(A, B, C, D, E);
tuple_sx_arg!(A, B, C, D, E, F);
tuple_sx_arg!(A, B, C, D, E, F, G);
tuple_sx_arg!(A, B, C, D, E, F, G, H);
pub fn merge(styles: impl SxArg) -> Sx {
let mut merged = Sx::new();
styles.merge_into(&mut merged);
merged
}
pub trait SxStyled: Sized {
#[must_use]
fn apply_sx(self, sx: Sx) -> Self;
#[must_use]
fn sx(self, styles: impl SxArg) -> Self {
self.apply_sx(merge(styles))
}
}
fn apply_to_interactive<E: Styled + InteractiveElement>(mut element: E, sx: Sx) -> E {
if sx.is_empty() {
return element;
}
let theme = current_theme();
let base = resolve(&sx.base, &theme);
element.style().refine(&base);
if !sx.hover.is_empty() {
let hover = resolve(&sx.hover, &theme);
element = element.hover(move |style| style.refined(hover));
}
if !sx.focus.is_empty() && focus_visible() {
let focus = resolve(&sx.focus, &theme);
element = element.focus(move |style| style.refined(focus));
}
element
}
impl SxStyled for Div {
fn apply_sx(self, sx: Sx) -> Self {
apply_to_interactive(self, sx)
}
}
impl SxStyled for gpui::Svg {
fn apply_sx(self, sx: Sx) -> Self {
apply_to_interactive(self, sx)
}
}
impl SxStyled for gpui::Img {
fn apply_sx(self, sx: Sx) -> Self {
apply_to_interactive(self, sx)
}
}
impl SxStyled for Stateful<Div> {
fn apply_sx(self, sx: Sx) -> Self {
use gpui::StatefulInteractiveElement;
let active = (!sx.active.is_empty()).then(|| resolve(&sx.active, ¤t_theme()));
let element = apply_to_interactive(self, sx);
match active {
Some(active) => element.active(move |style| style.refined(active)),
None => element,
}
}
}
#[macro_export]
macro_rules! sx {
($($tail:tt)*) => {{
let mut merged = $crate::sx::Sx::new();
$crate::__sx_merge!(merged; $($tail)*);
merged
}};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __sx_merge {
($merged:ident;) => {};
($merged:ident; $condition:expr => $style:expr $(, $($tail:tt)*)?) => {
if $condition {
$crate::sx::SxArg::merge_into(&$style, &mut $merged);
}
$($crate::__sx_merge!($merged; $($tail)*);)?
};
($merged:ident; $style:expr $(, $($tail:tt)*)?) => {
$crate::sx::SxArg::merge_into(&$style, &mut $merged);
$($crate::__sx_merge!($merged; $($tail)*);)?
};
}
#[cfg(test)]
mod tests {
use gpui::{px, AbsoluteLength, DefiniteLength, Length};
use super::*;
use crate::theme::{ThemeMode, ThemePreset};
fn theme() -> Theme {
Theme::from_preset(ThemePreset::Neutral, ThemeMode::Light)
}
#[test]
fn rtl_mirrors_rows_and_logical_properties() {
use crate::components::direction::{with_direction, TextDirection};
use gpui::FlexDirection;
let row = Sx::new()
.flex()
.padding(Edges::Start, 2.)
.margin(Edges::End, 1.)
.text_align(SxTextAlign::Start);
let column = Sx::new().flex_col().flex();
let theme = theme();
let ltr = row.resolve_base(&theme);
assert_eq!(ltr.flex_direction, None);
assert_eq!(
ltr.padding.left,
Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.))))
);
assert_eq!(ltr.padding.right, None);
with_direction(TextDirection::Rtl, || {
let rtl = row.resolve_base(&theme);
assert_eq!(rtl.flex_direction, Some(FlexDirection::RowReverse));
assert_eq!(
rtl.padding.right,
Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.))))
);
assert_eq!(rtl.padding.left, None);
assert_eq!(rtl.margin.left, Some(Length::Definite(px(4.).into())));
assert_eq!(
column.resolve_base(&theme).flex_direction,
Some(FlexDirection::Column)
);
});
}
#[test]
fn numbers_follow_the_four_pixel_scale() {
let style = Sx::new()
.gap(6.)
.w(px(10.))
.h(SxLength::Full)
.resolve_base(&theme());
assert_eq!(
style.gap.width,
Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(24.))))
);
assert_eq!(
style.size.width,
Some(Length::Definite(DefiniteLength::Absolute(
AbsoluteLength::Pixels(px(10.))
)))
);
assert_eq!(
style.size.height,
Some(Length::Definite(DefiniteLength::Fraction(1.)))
);
}
#[test]
fn later_styles_win_and_tokens_resolve() {
let base = Sx::new().p(4.).bg(ColorToken::Card);
let compact = Sx::new().p(2.);
let selected = Sx::new().bg(ColorToken::Primary.alpha(0.5));
let theme = theme();
let merged = merge((&base, Some(&compact), None::<&Sx>, &selected));
let style = merged.resolve_base(&theme);
assert_eq!(
style.padding.top,
Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.))))
);
assert_eq!(
style.background,
Some(theme.colors.primary.opacity(0.5).into())
);
let with_macro = crate::sx![base, false => compact, true => selected];
assert_eq!(with_macro, merged_without_compact(&base, &selected));
}
fn merged_without_compact(base: &Sx, selected: &Sx) -> Sx {
merge((base, selected))
}
#[test]
fn states_are_kept_apart() {
let style = Sx::new()
.bg(ColorToken::Background)
.hover(|state| state.bg(ColorToken::Accent));
assert_eq!(style.base.len(), 1);
assert_eq!(style.hover.len(), 1);
}
}