From b4a334ec0abb9973279353528aea917ad4c97c20 Mon Sep 17 00:00:00 2001 From: Samit Basu Date: Fri, 20 Nov 2026 15:48:59 -0800 Subject: [PATCH] Sheet core: parts, keys, layers, and winner provenance (#443) A `Style` gains a `Sheet`: for each part of a widget (a `Part` enum with a `data-slot` string), rules `(When, Tw body, layer)`. `Sheet::resolve` merges the rules whose keys hold, lowest layer first, later winning per property; `replace` drops what is below it. `When` asks for variant, size, attribute, ARIA state, and their negations (`not_aria`, `not_attr`); `Aria` gains `HasPopup`. Layers: defaults, preset, app, scope, ancestor, call site, important; the writer's layer is set by whoever hands out the sheet (`as_preset`, `as_app`, `Builder::styled` for scope). `Builder::part` resolves a part's classes (memoised per build, as a `Tw` is not `Send`) and returns them as the base of the node's own classes; the rules of the containers above now go between that base and the call site (`Rules::apply_layered`), as CSS gives shadcn's `[&_svg]:size-3` over an icon's default but under a caller's explicit class. A node with no sheet is built exactly as before. In debug builds a `Tw` records which class, in which layer, set each property (`Tw::origin_of`): every class method is `#[track_caller]`, and the property list now names box paint and text properties too. Release builds carry none of it. Behavior changes: none for existing widgets (no widget is on the sheet yet). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AJYxo4YJZUXcPJ1bHdAHKy --- benches/frame.rs | 83 +++- crates/eggshell-ui-shadcn/src/preset.rs | 1 + src/builder.rs | 26 +- src/contract.rs | 3 + src/lib.rs | 7 +- src/pipeline.rs | 4 + src/sheet.rs | 571 ++++++++++++++++++++++++ src/tw/grid.rs | 11 + src/tw/layout.rs | 29 ++ src/tw/merge.rs | 72 ++- src/tw/mod.rs | 12 + src/tw/origin.rs | 251 +++++++++++ src/tw/paint.rs | 60 +++ src/tw/rules.rs | 168 ++++++- src/tw/text.rs | 52 +++ tests/it/main.rs | 1 + tests/it/sheet.rs | 263 +++++++++++ 17 files changed, 1593 insertions(+), 21 deletions(-) create mode 100644 src/sheet.rs create mode 100644 src/tw/origin.rs create mode 100644 tests/it/sheet.rs diff --git a/benches/frame.rs b/benches/frame.rs index aafb22d4..403742d9 100644 --- a/benches/frame.rs +++ b/benches/frame.rs @@ -1,6 +1,6 @@ //! What a frame costs: build, layout and draw of plain trees at 100, 1,000 //! and 5,000 nodes (#133), a page of buttons styled on each icon or by one -//! rule on its container (#443), a virtual list's frame at 1,000 to 100,000 rows, +//! rule on its container, or by a sheet (#443), a virtual list's frame at 1,000 to 100,000 rows, //! and the js-framework-benchmark operations on a virtual list (#54). //! //! `cargo bench --bench frame`; one group with `cargo bench --bench frame -- @@ -11,10 +11,13 @@ use std::alloc::{GlobalAlloc, Layout, System}; use std::cell::{Cell, RefCell}; use std::hint::black_box; +use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use criterion::{BatchSize, BenchmarkId, Criterion, criterion_group, criterion_main}; -use eggshell_ui::{Builder, Icon, LayoutState, Match, icons, tw}; +use eggshell_ui::contract::Themed; +use eggshell_ui::sheet::{Part, Sheet, When}; +use eggshell_ui::{Builder, Icon, LayoutState, Match, Style, icons, tw}; use egui::{Context, Id, RawInput, Rect, pos2, vec2}; /// Counts allocations, for the allocations-per-frame figures. @@ -243,6 +246,80 @@ fn rules(c: &mut Criterion) { group.finish(); } +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct Button; + +impl Part for Button { + const SOURCE: &'static str = "button.tsx"; + + fn slot(self) -> &'static str { + "button" + } +} + +fn button_classes() -> eggshell_ui::Tw { + tw().flex().items_center().gap(1.0).px(2.0) +} + +/// Where a page of buttons keeps what every button shares. +#[derive(Clone, Copy, Debug)] +enum Keeping { + /// Built into each button's own classes. + Own, + /// In the style's sheet, resolved for each button. + Sheet, +} + +impl Keeping { + fn name(self) -> &'static str { + match self { + Self::Own => "own classes", + Self::Sheet => "sheet part", + } + } + + fn style(self) -> Themed> { + let mut style = Style::default(); + let mut sheet = Sheet::defaults(); + sheet.rule(Button, When::always(), |_| button_classes()); + style.sheet = sheet; + let style = Arc::new(style); + Themed { + light: style.clone(), + dark: style, + } + } + + fn build(self, b: &mut Builder<'_, '_, ()>, buttons: usize) { + b.div(tw().flex().flex_wrap().gap(1.0).p(2.0), |b| { + for at in 0..buttons { + let classes = match self { + Self::Own => button_classes(), + Self::Sheet => b.part(Button, &[]).merge(tw()), + }; + b.div(classes, |b| b.text(tw(), WORDS[at % WORDS.len()])); + } + }); + } +} + +fn sheets(c: &mut Criterion) { + let ctx = context(); + let mut group = c.benchmark_group("sheet"); + group.sample_size(30); + for keeping in [Keeping::Own, Keeping::Sheet] { + for buttons in [100, 1_000] { + let mut state = LayoutState::new().with_style(keeping.style()); + let view = |b: &mut Builder<'_, '_, ()>, _: &()| keeping.build(b, buttons); + frame(&ctx, &mut state, &mut (), Phase::Layout, view); + group.bench_function(BenchmarkId::new(keeping.name(), buttons), |bench| { + bench.iter(|| frame(&ctx, &mut state, &mut (), Phase::Layout, view)); + }); + } + } + group.finish(); +} + #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] struct RowId(u32); @@ -429,5 +506,5 @@ fn operations(c: &mut Criterion) { group.finish(); } -criterion_group!(benches, trees, rules, list, operations); +criterion_group!(benches, trees, rules, sheets, list, operations); criterion_main!(benches); diff --git a/crates/eggshell-ui-shadcn/src/preset.rs b/crates/eggshell-ui-shadcn/src/preset.rs index 92755644..2d431191 100644 --- a/crates/eggshell-ui-shadcn/src/preset.rs +++ b/crates/eggshell-ui-shadcn/src/preset.rs @@ -870,6 +870,7 @@ impl Shadcn { easing: Easing::InOut, }; style.tokens = self.core_tokens(); + style.sheet.as_preset(); style } diff --git a/src/builder.rs b/src/builder.rs index 1c67c1fd..9781b860 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -261,6 +261,26 @@ impl<'b, 'f, A> Builder<'b, 'f, A> { self.style } + /// TODO(prose): the classes the style's sheet gives `part` for a node with `keys`: merge the call site's over them, and the rules of the containers above come between. A variant or size the sheet leaves out is reported as [`Problem::MissingStyleEntry`](crate::Problem::MissingStyleEntry). + #[track_caller] + pub fn part(&mut self, part: P, keys: &[crate::sheet::Key]) -> Tw { + let sheet = &self.style.sheet; + let (classes, fresh) = self.st.sheets.resolve(sheet, part, keys); + if fresh && let Some(missing) = sheet.unnamed(part, keys) { + crate::report::report( + self.frame.ctx, + crate::Problem::MissingStyleEntry, + Some(Id::NULL.with(("style-entry", format!("{part:?} {missing:?}")))), + || { + format!( + "the style's sheet names no {missing:?} for {part:?}; drawing without it" + ) + }, + ); + } + Tw::over_sheet(classes) + } + /// TODO(prose): builds `body` in place with a style of its own: the style /// here, changed by `edit`. Every node `body` builds, and every control /// among them, is built, measured and drawn with it; nothing outside @@ -287,6 +307,7 @@ impl<'b, 'f, A> Builder<'b, 'f, A> { body: impl FnOnce(&mut Builder<'_, 'f, A>), ) { let mut style = crate::Style::clone(self.style); + style.sheet.as_scope(); edit(&mut style); self.with_style(&Arc::new(style), body); } @@ -1694,7 +1715,10 @@ impl<'b, 'f, A> Builder<'b, 'f, A> { /// Gives `tw` the classes the rules of the containers above make it. #[inline(always)] fn apply_rules(&self, tw: &mut Tw, kind: NodeKind) { - if !self.ambient.rules.is_empty() { + if tw.is_layered() { + let own = std::mem::replace(tw, Tw::blank()); + *tw = self.ambient.rules.apply_layered(&self.st.links, own, kind); + } else if !self.ambient.rules.is_empty() { *tw = self.ambient.rules.apply(&self.st.links, tw, kind); } } diff --git a/src/contract.rs b/src/contract.rs index db0ac46f..ec24108d 100644 --- a/src/contract.rs +++ b/src/contract.rs @@ -1555,6 +1555,8 @@ pub struct Style { pub tones: Tones, /// TODO(prose): the design system's named values, from which egui's own look is set. pub tokens: Tokens, + /// TODO(prose): the classes of every widget's parts, by layer. + pub sheet: crate::sheet::Sheet, /// The widgets' own looks, beside the core-painted fields. extensions: Extensions, } @@ -2165,6 +2167,7 @@ impl Style { motion: MotionStyle::INSTANT, tones: Tones::from_egui(v), tokens: Tokens::from_egui(egui), + sheet: crate::sheet::Sheet::defaults(), extensions: Extensions::default(), } } diff --git a/src/lib.rs b/src/lib.rs index 6e2f4571..3aeb98be 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -390,6 +390,7 @@ mod roving; pub mod scroll; mod scroll_keys; mod shadow_corners; +pub mod sheet; mod shell; mod sizing; mod spans; @@ -442,7 +443,9 @@ pub use text::{ }; #[doc(hidden)] pub use transition::{cycle, tracked_layout_nodes}; +#[cfg(debug_assertions)] +pub use tw::Property; pub use tw::{ - Angle, Aria, BoxPaint, Divide, Easing, Match, Mirror, Opacity, Paint, Progress, Reserve, Ring, - RingPlacement, Sides, Track, Tw, tw, + Angle, Aria, BoxPaint, Divide, Easing, Match, Mirror, Opacity, Origin, Paint, Progress, + Reserve, Ring, RingPlacement, Sides, Source, Track, Tw, tw, }; diff --git a/src/pipeline.rs b/src/pipeline.rs index 043c89a8..558a0ec4 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -321,6 +321,8 @@ pub(crate) struct BuildState { pub observed: std::collections::HashMap, /// The rules containers declared this frame, by the index `Rules` holds. pub links: Vec, + /// What the style's sheet gave the parts built so far. + pub sheets: crate::sheet::Memo, pub names: ReadablePath, pub pass: Pass, } @@ -348,6 +350,7 @@ impl BuildState { seen: Seen::default(), observed: std::collections::HashMap::new(), links: Vec::new(), + sheets: crate::sheet::Memo::default(), names: ReadablePath::default(), pass: Pass::Scratch, } @@ -741,6 +744,7 @@ impl LayoutState { seen: Seen::default(), observed: std::collections::HashMap::new(), links: Vec::new(), + sheets: crate::sheet::Memo::default(), names: ReadablePath::default(), pass: Pass::Live, }, diff --git a/src/sheet.rs b/src/sheet.rs new file mode 100644 index 00000000..3c526460 --- /dev/null +++ b/src/sheet.rs @@ -0,0 +1,571 @@ +//! A style's rules for the parts of its widgets: the classes a part gets, by +//! what it is and what state it is in, written by layers that win in order. + +use std::any::TypeId; +use std::collections::HashMap; +use std::fmt::Debug; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::contract::{Size, Variant}; +use crate::{Aria, Tw}; + +/// TODO(prose): the anatomy of a widget: the nodes a [`Sheet`] styles. +/// +/// ``` +/// use eggshell_ui::sheet::Part; +/// +/// #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +/// enum ChipPart { +/// Root, +/// Label, +/// } +/// +/// impl Part for ChipPart { +/// const SOURCE: &'static str = "badge.tsx"; +/// +/// fn slot(self) -> &'static str { +/// match self { +/// Self::Root => "badge", +/// Self::Label => "badge-label", +/// } +/// } +/// } +/// ``` +pub trait Part: Copy + Eq + Ord + Debug + Send + Sync + 'static { + /// TODO(prose): the shadcn component the widget's look comes from. + const SOURCE: &'static str; + + /// TODO(prose): the part's `data-slot`, which rules match and the part's node declares. + fn slot(self) -> &'static str; +} + +/// TODO(prose): who wrote a rule, which decides whose wins. A later layer's classes win per property over an earlier one's. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Layer { + /// TODO(prose): the widgets' own looks. + Defaults, + /// TODO(prose): a design system's preset. + Preset, + /// TODO(prose): the application's. + App, + /// TODO(prose): a [`Builder::styled`](crate::Builder::styled) scope's. + Scope, + /// TODO(prose): the rules of the containers above a node. + Ancestor, + /// TODO(prose): the classes given where the widget is built. + CallSite, + /// TODO(prose): an `important` rule of a container above. + Important, +} + +/// TODO(prose): one fact about a node that a rule can ask for. +/// +/// ``` +/// use eggshell_ui::Aria; +/// use eggshell_ui::contract::Variant; +/// use eggshell_ui::sheet::Key; +/// +/// let keys = [Key::Variant(Variant::DEFAULT), Key::Aria(Aria::Invalid)]; +/// assert_eq!(keys.len(), 2); +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Key { + /// TODO(prose): the node's variant. + Variant(Variant), + /// TODO(prose): the node's size. + Size(Size), + /// TODO(prose): an attribute, as `data-[orientation=vertical]`. + Attr(&'static str, &'static str), + /// TODO(prose): an ARIA state. + Aria(Aria), + /// TODO(prose): in a rule: the node says no such attribute. + NotAttr(&'static str, &'static str), + /// TODO(prose): in a rule: the node says no such ARIA state. + NotAria(Aria), +} + +/// TODO(prose): the keys a rule needs: it applies to a node whose keys include all of them. +/// +/// ``` +/// use eggshell_ui::Aria; +/// use eggshell_ui::contract::{Size, Variant}; +/// use eggshell_ui::sheet::When; +/// +/// let invalid_small = When::always().size(Size("sm")).aria(Aria::Invalid); +/// let primary = When::always().variant(Variant("primary")); +/// assert_ne!(invalid_small, primary); +/// ``` +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct When { + keys: [Option; 4], +} + +impl When { + /// TODO(prose): no keys: every node of the part. + pub const fn always() -> Self { + Self { keys: [None; 4] } + } + + /// TODO(prose): and the node has `variant`. + #[must_use] + pub fn variant(self, variant: Variant) -> Self { + self.and(Key::Variant(variant)) + } + + /// TODO(prose): and the node is `size`. + #[must_use] + pub fn size(self, size: Size) -> Self { + self.and(Key::Size(size)) + } + + /// TODO(prose): and the node says the attribute `name` is `value`. + #[must_use] + pub fn attr(self, name: &'static str, value: &'static str) -> Self { + self.and(Key::Attr(name, value)) + } + + /// TODO(prose): and the node says `state`. + #[must_use] + pub fn aria(self, state: Aria) -> Self { + self.and(Key::Aria(state)) + } + + /// TODO(prose): and the node does not say the attribute `name` is `value`: `not-data-[name=value]`. + #[must_use] + pub fn not_attr(self, name: &'static str, value: &'static str) -> Self { + self.and(Key::NotAttr(name, value)) + } + + /// TODO(prose): and the node does not say `state`: `not-aria-*`. + #[must_use] + pub fn not_aria(self, state: Aria) -> Self { + self.and(Key::NotAria(state)) + } + + /// TODO(prose): and the node has `key`. + #[must_use] + pub fn and(mut self, key: Key) -> Self { + match self.keys.iter_mut().find(|slot| slot.is_none()) { + Some(slot) => *slot = Some(key), + None => { + // TODO(#279): report a rule that asks for more than four keys + } + } + self + } + + fn named(&self) -> impl Iterator + '_ { + self.keys.iter().flatten().copied() + } + + fn holds(&self, keys: &[Key]) -> bool { + self.named().all(|key| match key { + Key::NotAttr(name, value) => !keys.contains(&Key::Attr(name, value)), + Key::NotAria(state) => !keys.contains(&Key::Aria(state)), + key => keys.contains(&key), + }) + } +} + +/// What a part is named by: its widget's parts, and its slot. +type PartKey = (TypeId, &'static str); + +type Body = Arc Tw + Send + Sync>; + +#[derive(Clone)] +struct Stored { + when: When, + layer: Layer, + replace: bool, + body: Body, +} + +impl Debug for Stored { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Stored") + .field("when", &self.when) + .field("layer", &self.layer) + .field("replace", &self.replace) + .finish_non_exhaustive() + } +} + +fn next_version() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + +/// TODO(prose): the rules of a style: for each part of each widget, the classes it gets when its keys hold. +/// +/// ``` +/// use eggshell_ui::contract::Variant; +/// use eggshell_ui::sheet::{Key, Part, Sheet, When}; +/// use eggshell_ui::tw; +/// +/// #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +/// struct Chip; +/// +/// impl Part for Chip { +/// const SOURCE: &'static str = "badge.tsx"; +/// +/// fn slot(self) -> &'static str { +/// "badge" +/// } +/// } +/// +/// let mut sheet = Sheet::defaults(); +/// sheet +/// .rule(Chip, When::always(), |t| t.px(2.0).rounded_md()) +/// .rule(Chip, When::always().variant(Variant("wide")), |t| t.px(4.0)); +/// let wide = sheet.resolve(Chip, &[Key::Variant(Variant("wide"))]); +/// assert_eq!(wide.style(), tw().px(4.0).style()); +/// ``` +#[derive(Clone, Debug)] +pub struct Sheet { + layer: Layer, + rules: Arc>>, + /// Changes with every edit, so that the installed style's every-frame comparison stays cheap. + version: u64, +} + +impl Default for Sheet { + fn default() -> Self { + Self::defaults() + } +} + +impl PartialEq for Sheet { + fn eq(&self, other: &Self) -> bool { + self.version == other.version && self.layer == other.layer + } +} + +impl Sheet { + /// TODO(prose): a sheet with no rules, written at the layer of the widgets' defaults. + pub fn defaults() -> Self { + Self { + layer: Layer::Defaults, + rules: Arc::default(), + version: 0, + } + } + + /// TODO(prose): the rules written from here on are a preset's. + pub fn as_preset(&mut self) -> &mut Self { + self.layer = Layer::Preset; + self + } + + /// TODO(prose): the rules written from here on are the application's. + pub fn as_app(&mut self) -> &mut Self { + self.layer = Layer::App; + self + } + + pub(crate) fn as_scope(&mut self) -> &mut Self { + self.layer = Layer::Scope; + self + } + + /// TODO(prose): the layer the rules written now are in. + pub fn layer(&self) -> Layer { + self.layer + } + + /// TODO(prose): adds the classes `body` writes for `part` while `when` holds, at this sheet's layer, after the rules it has. + pub fn rule( + &mut self, + part: P, + when: When, + body: impl Fn(Tw) -> Tw + Send + Sync + 'static, + ) -> &mut Self { + self.add(part, when, false, body) + } + + /// TODO(prose): [`rule`](Self::rule), but the part's classes start empty under it: every rule below that holds with it is dropped. + /// + /// ``` + /// use eggshell_ui::contract::Variant; + /// use eggshell_ui::sheet::{Key, Part, Sheet, When}; + /// use eggshell_ui::tw; + /// + /// #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] + /// struct Chip; + /// + /// impl Part for Chip { + /// const SOURCE: &'static str = "badge.tsx"; + /// + /// fn slot(self) -> &'static str { + /// "badge" + /// } + /// } + /// + /// let mut sheet = Sheet::defaults(); + /// sheet.rule(Chip, When::always(), |t| t.px(2.0).gap(1.0)); + /// sheet.as_app().replace(Chip, When::always(), |t| t.px(4.0)); + /// let chip = sheet.resolve(Chip, &[]); + /// assert_eq!(chip.style(), tw().px(4.0).style()); + /// ``` + pub fn replace( + &mut self, + part: P, + when: When, + body: impl Fn(Tw) -> Tw + Send + Sync + 'static, + ) -> &mut Self { + self.add(part, when, true, body) + } + + fn add( + &mut self, + part: P, + when: When, + replace: bool, + body: impl Fn(Tw) -> Tw + Send + Sync + 'static, + ) -> &mut Self { + let layer = self.layer; + Arc::make_mut(&mut self.rules) + .entry(part_key(part)) + .or_default() + .push(Stored { + when, + layer, + replace, + body: Arc::new(body), + }); + self.version = next_version(); + self + } + + /// TODO(prose): the classes of `part` for a node with `keys`: the rules that hold, the lowest layer's first, each over the last. The node's `data-slot` is the part's. + /// + /// A builder keeps what it resolved, so this runs each rule's body: for a call outside a build, such as a test's. + pub fn resolve(&self, part: P, keys: &[Key]) -> Tw { + self.resolved(part, part_key(part), keys) + } + + fn resolved(&self, part: P, at: PartKey, keys: &[Key]) -> Tw { + let mut holding: Vec<&Stored> = self + .rules + .get(&at) + .into_iter() + .flatten() + .filter(|rule| rule.when.holds(keys)) + .collect(); + holding.sort_by_key(|rule| rule.layer); + let from = holding.iter().rposition(|rule| rule.replace).unwrap_or(0); + holding + .iter() + .skip(from) + .fold(Tw::blank(), |classes, rule| { + classes.merge((rule.body)(Tw::blank()).staged(rule.layer)) + }) + .slot(part.slot()) + } + + /// TODO(prose): the variants and sizes the sheet's rules name for the parts of `P`'s widget. + pub fn keys(&self) -> impl Iterator + use

{ + let widget = TypeId::of::

(); + let mut named = Vec::new(); + let rules = self + .rules + .iter() + .filter(|(at, _)| at.0 == widget) + .flat_map(|(_, rules)| rules); + for key in rules.flat_map(|rule| rule.when.named()) { + if matches!(key, Key::Variant(_) | Key::Size(_)) && !named.contains(&key) { + named.push(key); + } + } + named.into_iter() + } + + /// The first variant or size in `keys` that `part`'s rules leave out while naming others of its kind. + pub(crate) fn unnamed(&self, part: P, keys: &[Key]) -> Option { + let named: Vec = self + .rules + .get(&part_key(part)) + .into_iter() + .flatten() + .flat_map(|rule| rule.when.named()) + .collect(); + let same_kind = |a: &Key, b: &Key| { + matches!( + (a, b), + (Key::Variant(_), Key::Variant(_)) | (Key::Size(_), Key::Size(_)) + ) + }; + keys.iter() + .find(|key| !named.contains(key) && named.iter().any(|known| same_kind(known, key))) + .copied() + } +} + +/// The classes resolved for a part, by the keys they were for. +type Resolved = Vec<(Box<[Key]>, Tw)>; + +/// What a build has resolved, by sheet version. A [`Tw`] is not `Send`, so +/// the sheet, which a style shares between threads, cannot keep it. +#[derive(Default)] +pub(crate) struct Memo { + sheets: HashMap>, +} + +impl Memo { + /// The most sheets kept: scopes that edit theirs make a new one each frame. + const SHEETS: usize = 16; + + /// [`Sheet::resolve`], and whether it was resolved now rather than found. + pub(crate) fn resolve(&mut self, sheet: &Sheet, part: P, keys: &[Key]) -> (Tw, bool) { + if self.sheets.len() >= Self::SHEETS && !self.sheets.contains_key(&sheet.version) { + self.sheets.clear(); + } + let at = part_key(part); + let known = self + .sheets + .entry(sheet.version) + .or_default() + .entry(at) + .or_default(); + if let Some((_, resolved)) = known.iter().find(|(known, _)| **known == *keys) { + return (resolved.clone(), false); + } + let resolved = sheet.resolved(part, at, keys); + known.push((keys.into(), resolved.clone())); + (resolved, true) + } +} + +fn part_key(part: P) -> PartKey { + (TypeId::of::

(), part.slot()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tw; + + #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] + enum Test { + Root, + Icon, + } + + impl Part for Test { + const SOURCE: &'static str = "test.tsx"; + + fn slot(self) -> &'static str { + match self { + Self::Root => "test", + Self::Icon => "test-icon", + } + } + } + + const WIDE: Variant = Variant("wide"); + const NARROW: Variant = Variant("narrow"); + + fn sheet() -> Sheet { + let mut sheet = Sheet::defaults(); + sheet + .rule(Test::Root, When::always(), |t| t.px(2.0).gap(1.0)) + .rule(Test::Root, When::always().variant(WIDE), |t| t.px(4.0)) + .rule(Test::Root, When::always().variant(NARROW), |t| t.px(1.0)) + .rule( + Test::Root, + When::always().variant(WIDE).aria(Aria::Invalid), + |t| t.gap(3.0), + ) + .rule(Test::Icon, When::always(), |t| t.size(4.0)); + sheet + } + + #[test] + fn the_rules_that_hold_are_merged_in_order_later_winning_per_property() { + let sheet = sheet(); + let wide = sheet.resolve(Test::Root, &[Key::Variant(WIDE)]); + assert_eq!(wide.style(), tw().px(4.0).gap(1.0).style()); + let invalid = sheet.resolve(Test::Root, &[Key::Variant(WIDE), Key::Aria(Aria::Invalid)]); + assert_eq!(invalid.style(), tw().px(4.0).gap(3.0).style()); + } + + #[test] + fn a_negated_key_holds_while_the_node_lacks_the_state() { + let mut sheet = Sheet::defaults(); + sheet + .rule(Test::Root, When::always().not_aria(Aria::Disabled), |t| { + t.px(2.0) + }) + .rule(Test::Root, When::always().not_attr("side", "top"), |t| { + t.py(3.0) + }); + let free = sheet.resolve(Test::Root, &[]); + assert_eq!(free.style(), tw().px(2.0).py(3.0).style()); + let keys = [Key::Aria(Aria::Disabled), Key::Attr("side", "top")]; + assert_eq!(sheet.resolve(Test::Root, &keys).style(), tw().style()); + } + + #[test] + fn a_part_is_resolved_from_its_own_rules_only() { + let icon = sheet().resolve(Test::Icon, &[Key::Variant(WIDE)]); + assert_eq!(icon.style(), tw().size(4.0).style()); + } + + #[test] + fn a_later_layer_wins_whatever_the_order_the_rules_were_written_in() { + let mut sheet = Sheet::defaults(); + sheet + .as_app() + .rule(Test::Root, When::always(), |t| t.px(8.0)); + sheet.layer = Layer::Defaults; + sheet.rule(Test::Root, When::always(), |t| t.px(2.0).gap(1.0)); + let root = sheet.resolve(Test::Root, &[]); + assert_eq!(root.style(), tw().px(8.0).gap(1.0).style()); + } + + #[test] + fn replace_drops_what_is_below_it_and_only_where_it_holds() { + let mut sheet = sheet(); + sheet + .as_app() + .replace(Test::Root, When::always().variant(WIDE), |t| t.py(5.0)); + let wide = sheet.resolve(Test::Root, &[Key::Variant(WIDE)]); + assert_eq!(wide.style(), tw().py(5.0).style()); + let narrow = sheet.resolve(Test::Root, &[Key::Variant(NARROW)]); + assert_eq!(narrow.style(), tw().px(1.0).gap(1.0).style()); + } + + #[test] + fn an_edit_makes_the_sheet_unequal_and_a_clone_equal() { + let mut sheet = sheet(); + let clone = sheet.clone(); + assert_eq!(sheet, clone); + sheet.rule(Test::Root, When::always(), |t| t.px(9.0)); + assert_ne!(sheet, clone); + assert_eq!( + clone.resolve(Test::Root, &[]).style(), + tw().px(2.0).gap(1.0).style(), + "the clone keeps its rules" + ); + } + + #[test] + fn a_variant_the_sheet_leaves_out_is_found_when_it_names_others() { + let sheet = sheet(); + let missing = Key::Variant(Variant("missing")); + assert_eq!(sheet.unnamed(Test::Root, &[missing]), Some(missing)); + assert_eq!(sheet.unnamed(Test::Root, &[Key::Variant(WIDE)]), None); + assert_eq!( + sheet.unnamed(Test::Icon, &[missing]), + None, + "a part with no variants takes any" + ); + } + + #[test] + fn the_keys_a_part_names_are_its_variants_and_sizes() { + let keys: Vec = sheet().keys::().collect(); + assert_eq!(keys.len(), 2); + assert!(keys.contains(&Key::Variant(WIDE)) && keys.contains(&Key::Variant(NARROW))); + } +} diff --git a/src/tw/grid.rs b/src/tw/grid.rs index 4b8c57da..39dd476d 100644 --- a/src/tw/grid.rs +++ b/src/tw/grid.rs @@ -125,21 +125,25 @@ fn full(line: &mut Line) { macro_rules! placement { ($($span:ident, $span_full:ident, $start:ident, $end:ident, $field:ident, $axis:literal;)*) => {$( #[doc = concat!("Spans `count` ", $axis, "s (`", stringify!($span), "-`).")] + #[cfg_attr(debug_assertions, track_caller)] pub fn $span(self, count: u16) -> Self { self.styled(|s| span(s.$field(), count)) } #[doc = concat!("Spans every ", $axis, " of the explicit grid.")] + #[cfg_attr(debug_assertions, track_caller)] pub fn $span_full(self) -> Self { self.styled(|s| full(s.$field())) } #[doc = concat!("Starts at grid line `line` (negative counts from the end).")] + #[cfg_attr(debug_assertions, track_caller)] pub fn $start(self, line: i16) -> Self { self.styled(|s| s.$field().start = GridPlacement::from_line_index(line)) } #[doc = concat!("Ends at grid line `line` (negative counts from the end).")] + #[cfg_attr(debug_assertions, track_caller)] pub fn $end(self, line: i16) -> Self { self.styled(|s| s.$field().end = GridPlacement::from_line_index(line)) } @@ -151,36 +155,43 @@ macro_rules! placement { macro_rules! grid_methods { () => { /// `grid-cols-`: `count` columns of `minmax(0, 1fr)`. + #[cfg_attr(debug_assertions, track_caller)] pub fn grid_cols(self, count: u16) -> Self { self.styled(|s| *s.grid_template_columns() = even(count)) } /// `grid-rows-`: `count` rows of `minmax(0, 1fr)`. + #[cfg_attr(debug_assertions, track_caller)] pub fn grid_rows(self, count: u16) -> Self { self.styled(|s| *s.grid_template_rows() = even(count)) } /// An arbitrary column track list, as in `grid-cols-[48px_minmax(0,1fr)_...]`. + #[cfg_attr(debug_assertions, track_caller)] pub fn grid_cols_tracks(self, tracks: &[Track]) -> Self { self.styled(|s| *s.grid_template_columns() = template(tracks)) } /// An arbitrary row track list. + #[cfg_attr(debug_assertions, track_caller)] pub fn grid_rows_tracks(self, tracks: &[Track]) -> Self { self.styled(|s| *s.grid_template_rows() = template(tracks)) } /// `grid-flow-row`: auto-placed items fill rows. + #[cfg_attr(debug_assertions, track_caller)] pub fn grid_flow_row(self) -> Self { self.styled(|s| *s.grid_auto_flow() = taffy::GridAutoFlow::Row) } /// `grid-flow-col`: auto-placed items fill columns. + #[cfg_attr(debug_assertions, track_caller)] pub fn grid_flow_col(self) -> Self { self.styled(|s| *s.grid_auto_flow() = taffy::GridAutoFlow::Column) } /// `grid-flow-dense`: back-fills holes, keeping the flow direction. + #[cfg_attr(debug_assertions, track_caller)] pub fn grid_flow_dense(self) -> Self { self.styled(|s| { let flow = s.grid_auto_flow(); diff --git a/src/tw/layout.rs b/src/tw/layout.rs index 0dc24f00..f1bb4f66 100644 --- a/src/tw/layout.rs +++ b/src/tw/layout.rs @@ -92,6 +92,7 @@ fn space(units: f32) -> LengthPercentage { macro_rules! spacing { ($($name:ident, $doc:literal, |$s:ident, $v:ident| $set:expr;)*) => {$( #[doc = $doc] + #[cfg_attr(debug_assertions, track_caller)] pub fn $name(self, units: f32) -> Self { self.styled(|$s| { let $v = units * SPACE_UNIT; $set }) } @@ -101,6 +102,7 @@ macro_rules! spacing { macro_rules! auto_margins { ($($name:ident, $doc:literal, |$s:ident| $set:expr;)*) => {$( #[doc = $doc] + #[cfg_attr(debug_assertions, track_caller)] pub fn $name(self) -> Self { self.styled(|$s| $set) } @@ -112,26 +114,31 @@ macro_rules! lengths { ($($name:ident, $px:ident, $frac:ident, $full:ident, $auto:ident, $what:literal, |$s:ident, $l:ident| $set:expr;)*) => {$( #[doc = concat!("Sets ", $what, " in spacing units.")] + #[cfg_attr(debug_assertions, track_caller)] pub fn $name(self, units: f32) -> Self { self.styled(|$s| { let $l = Len::space(units); $set }) } #[doc = concat!("Sets ", $what, " in points.")] + #[cfg_attr(debug_assertions, track_caller)] pub fn $px(self, points: f32) -> Self { self.styled(|$s| { let $l = Len::Points(points); $set }) } #[doc = concat!("Sets ", $what, " to the fraction `numerator / denominator` of the parent.")] + #[cfg_attr(debug_assertions, track_caller)] pub fn $frac(self, numerator: f32, denominator: f32) -> Self { self.styled(|$s| { let $l = Len::fraction(numerator, denominator); $set }) } #[doc = concat!("Sets ", $what, " to 100% of the parent.")] + #[cfg_attr(debug_assertions, track_caller)] pub fn $full(self) -> Self { self.styled(|$s| { let $l = Len::Fraction(1.0); $set }) } #[doc = concat!("Sets ", $what, " to `auto`.")] + #[cfg_attr(debug_assertions, track_caller)] pub fn $auto(self) -> Self { self.styled(|$s| { let $l = Len::Auto; $set }) } @@ -141,6 +148,7 @@ macro_rules! lengths { macro_rules! keywords { ($($name:ident, $doc:literal, |$s:ident| $set:expr;)*) => {$( #[doc = $doc] + #[cfg_attr(debug_assertions, track_caller)] pub fn $name(self) -> Self { self.styled(|$s| $set) } @@ -157,6 +165,7 @@ macro_rules! layout_methods { /// ```html /// -12.5 /// ``` + #[cfg_attr(debug_assertions, track_caller)] pub fn w_ch(self, n: f32) -> Self { self.styled(|s| { *s.width() = Dimension::AUTO; @@ -165,6 +174,7 @@ macro_rules! layout_methods { } /// `min-w-[ch]`: the minimum width in `ch`. See [`w_ch`](Self::w_ch). + #[cfg_attr(debug_assertions, track_caller)] pub fn min_w_ch(self, n: f32) -> Self { self.styled(|s| { *s.min_width() = LengthPercentageAuto::AUTO; @@ -178,6 +188,7 @@ macro_rules! layout_methods { /// grows the node, and is reported in debug builds as /// [`OutgrewReserve`](crate::Problem::OutgrewReserve). The templates are /// never shown or announced. + #[cfg_attr(debug_assertions, track_caller)] pub fn min_w_text(self, reserve: Reserve) -> Self { self.styled(|s| { *s.min_width() = LengthPercentageAuto::AUTO; @@ -186,6 +197,7 @@ macro_rules! layout_methods { } /// `max-w-[ch]`: the maximum width in `ch`. See [`w_ch`](Self::w_ch). + #[cfg_attr(debug_assertions, track_caller)] pub fn max_w_ch(self, n: f32) -> Self { self.styled(|s| { *s.max_width() = LengthPercentageAuto::AUTO; @@ -300,6 +312,7 @@ macro_rules! layout_methods { } /// `gap-`: spacing between children on both axes. + #[cfg_attr(debug_assertions, track_caller)] pub fn gap(self, units: f32) -> Self { self.styled(|s| { *s.gap_width() = space(units); @@ -308,31 +321,37 @@ macro_rules! layout_methods { } /// `gap-x-`: spacing between columns. + #[cfg_attr(debug_assertions, track_caller)] pub fn gap_x(self, units: f32) -> Self { self.styled(|s| *s.gap_width() = space(units)) } /// `gap-y-`: spacing between rows. + #[cfg_attr(debug_assertions, track_caller)] pub fn gap_y(self, units: f32) -> Self { self.styled(|s| *s.gap_height() = space(units)) } /// `grow-`. + #[cfg_attr(debug_assertions, track_caller)] pub fn grow_by(self, factor: f32) -> Self { self.styled(|s| *s.flex_grow() = factor) } /// `aspect-[]`: width divided by height. + #[cfg_attr(debug_assertions, track_caller)] pub fn aspect(self, ratio: f32) -> Self { self.styled(|s| *s.aspect_ratio() = Some(ratio)) } /// `border-`: border width in points on every side. + #[cfg_attr(debug_assertions, track_caller)] pub fn border(self, points: f32) -> Self { self.styled(|s| s.set_border(taffy::Rect::length(points))) } /// `border-x-`: left and right border widths in points. + #[cfg_attr(debug_assertions, track_caller)] pub fn border_x(self, points: f32) -> Self { self.styled(|s| { *s.border_left() = LengthPercentage::length(points); @@ -341,6 +360,7 @@ macro_rules! layout_methods { } /// `border-y-`: top and bottom border widths in points. + #[cfg_attr(debug_assertions, track_caller)] pub fn border_y(self, points: f32) -> Self { self.styled(|s| { *s.border_top() = LengthPercentage::length(points); @@ -349,46 +369,55 @@ macro_rules! layout_methods { } /// `border-t-`: top border width in points. + #[cfg_attr(debug_assertions, track_caller)] pub fn border_t(self, points: f32) -> Self { self.styled(|s| *s.border_top() = LengthPercentage::length(points)) } /// `border-r-`: right border width in points. + #[cfg_attr(debug_assertions, track_caller)] pub fn border_r(self, points: f32) -> Self { self.styled(|s| *s.border_right() = LengthPercentage::length(points)) } /// `border-b-`: bottom border width in points. + #[cfg_attr(debug_assertions, track_caller)] pub fn border_b(self, points: f32) -> Self { self.styled(|s| *s.border_bottom() = LengthPercentage::length(points)) } /// `border-l-`: left border width in points. + #[cfg_attr(debug_assertions, track_caller)] pub fn border_l(self, points: f32) -> Self { self.styled(|s| *s.border_left() = LengthPercentage::length(points)) } /// `basis-`: flex basis in spacing units. + #[cfg_attr(debug_assertions, track_caller)] pub fn basis(self, units: f32) -> Self { self.styled(|s| *s.flex_basis() = Len::space(units).to()) } /// `basis-px`: flex basis in points. + #[cfg_attr(debug_assertions, track_caller)] pub fn basis_px(self, points: f32) -> Self { self.styled(|s| *s.flex_basis() = Len::Points(points).to()) } /// `basis-1/2`: flex basis as a fraction of the container. + #[cfg_attr(debug_assertions, track_caller)] pub fn basis_frac(self, numerator: f32, denominator: f32) -> Self { self.styled(|s| *s.flex_basis() = Len::fraction(numerator, denominator).to()) } /// `basis-full`. + #[cfg_attr(debug_assertions, track_caller)] pub fn basis_full(self) -> Self { self.styled(|s| *s.flex_basis() = Len::Fraction(1.0).to()) } /// `basis-auto`. + #[cfg_attr(debug_assertions, track_caller)] pub fn basis_auto(self) -> Self { self.styled(|s| *s.flex_basis() = Dimension::AUTO) } diff --git a/src/tw/merge.rs b/src/tw/merge.rs index fe593da0..9715fc9a 100644 --- a/src/tw/merge.rs +++ b/src/tw/merge.rs @@ -45,15 +45,56 @@ impl Touched { /// the one place that names them. macro_rules! layout_properties { ($($name:ident: $($field:ident).+ => $ty:ty),+ $(,)?) => { - #[derive(Clone, Copy)] + /// TODO(prose): a property of a class list, named for the style field it sets. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[expect(non_camel_case_types, reason = "named for the style field they stand for")] - enum Property { + #[cfg_attr(debug_assertions, expect(missing_docs, reason = "named for the style field they stand for"))] + #[cfg_attr(not(debug_assertions), allow(dead_code))] + pub enum Property { $($name,)+ RadiusNw, RadiusNe, RadiusSw, RadiusSe, Opacity, + // The properties below are not merged through `Touched`: their + // classes are `Option`s, set or not. They are named so that a + // winner can be too. + Background, + BorderColorTop, + BorderColorRight, + BorderColorBottom, + BorderColorLeft, + Ring, + Shadow, + DivideX, + DivideY, + TextSize, + TextLineHeight, + TextFamily, + TextWeight, + TextColor, + TextFontStyle, + TextDecoration, + TextWhiteSpace, + TextAlign, + TextTracking, + TextCase, + TextSelect, + TextNumerals, + } + + impl Property { + /// Every property that [`Touched`] tracks. + #[cfg(debug_assertions)] + const TOUCHED: &[Property] = &[ + $(Property::$name,)+ + Property::RadiusNw, + Property::RadiusNe, + Property::RadiusSw, + Property::RadiusSe, + Property::Opacity, + ]; } #[expect(clippy::disallowed_macros, reason = "a const assertion fails the build, not a run")] @@ -249,6 +290,7 @@ impl Shape<'_> { impl Tw { /// Writes layout with `set`, which records each property it writes. + #[cfg_attr(debug_assertions, track_caller)] pub(super) fn write_layout(&mut self, set: impl FnOnce(&mut Layout<'_>)) { let (style, ch) = (self.style.clone(), self.ch.clone()); let mut written = Touched::default(); @@ -259,6 +301,13 @@ impl Tw { }); if super::layout::is_finite(&self.style, &self.ch) { self.touched = self.touched | written; + #[cfg(debug_assertions)] + self.note_all( + Property::TOUCHED + .iter() + .copied() + .filter(|&p| written.has(p)), + ); } else { (self.style, self.ch) = (style, ch); self.lengths = super::Lengths::Rejected; @@ -266,11 +315,21 @@ impl Tw { } /// Writes the box paint that merging tracks with `set`. + #[cfg_attr(debug_assertions, track_caller)] pub(super) fn write_shape(&mut self, set: impl FnOnce(&mut Shape<'_>)) { + let mut written = Touched::default(); set(&mut Shape { paint: &mut self.paint, - touched: &mut self.touched, + touched: &mut written, }); + self.touched = self.touched | written; + #[cfg(debug_assertions)] + self.note_all( + Property::TOUCHED + .iter() + .copied() + .filter(|&p| written.has(p)), + ); } /// These classes with `other` applied on top, as `tailwind-merge` does: @@ -364,6 +423,13 @@ impl Tw { self.variants = self.variants.merge(other.variants); self.touched = self.touched | other.touched; self.lengths = self.lengths.or(other.lengths); + #[cfg(debug_assertions)] + { + self.origins = match (self.origins, other.origins) { + (Some(own), Some(later)) => Some(Box::new(own.over(*later))), + (own, later) => later.or(own), + }; + } self.rules = match (self.rules, other.rules) { (Some(own), Some(later)) => Some(Box::new(own.merge(*later))), (own, later) => later.or(own), diff --git a/src/tw/mod.rs b/src/tw/mod.rs index 10903f1f..34add076 100644 --- a/src/tw/mod.rs +++ b/src/tw/mod.rs @@ -16,6 +16,7 @@ mod easing; mod grid; mod layout; mod merge; +mod origin; mod paint; mod rules; mod text; @@ -32,7 +33,12 @@ pub use ch::Reserve; pub(crate) use ch::{MinWidth, TextWidths}; pub use easing::Easing; pub use grid::Track; +#[cfg(debug_assertions)] +pub use merge::Property; use merge::{Layout, Touched}; +#[cfg(debug_assertions)] +pub(crate) use origin::Origins; +pub use origin::{Origin, Source}; pub use paint::{BoxPaint, Divide, Ring, RingPlacement, Sides}; pub use rules::{Aria, Match}; pub(crate) use rules::{Link, Observed, Ruled, Rules}; @@ -71,6 +77,9 @@ pub struct Tw { /// most nodes, which keeps a `Tw` small. pub(crate) rules: Option>, touched: Touched, + /// The class that set each property, in debug builds. + #[cfg(debug_assertions)] + origins: Option>, } /// Whether a class was ignored because a length it was given is infinite or @@ -122,6 +131,8 @@ pub fn tw() -> Tw { lengths: Lengths::Finite, rules: None, touched: Touched::default(), + #[cfg(debug_assertions)] + origins: None, } } @@ -226,6 +237,7 @@ impl Tw { self } + #[cfg_attr(debug_assertions, track_caller)] fn styled(mut self, set: impl FnOnce(&mut Layout<'_>)) -> Self { self.write_layout(set); self diff --git a/src/tw/origin.rs b/src/tw/origin.rs new file mode 100644 index 00000000..1b338c6b --- /dev/null +++ b/src/tw/origin.rs @@ -0,0 +1,251 @@ +//! Which class set each property of a class list, and in which layer it was +//! written. Debug builds only: a release `Tw` carries none of it. + +use std::panic::Location; + +#[cfg(debug_assertions)] +use super::Property; +use super::Tw; +use crate::sheet::Layer; + +/// TODO(prose): who wrote a class. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Source { + /// TODO(prose): the Rust call that wrote it. + Rust(&'static Location<'static>), + /// TODO(prose): a class of a shadcn style sheet. + Shadcn { + /// TODO(prose): the file of the pinned shadcn checkout. + file: &'static str, + /// TODO(prose): the line in `file`. + line: u32, + /// TODO(prose): the class as written there. + class: &'static str, + }, +} + +/// TODO(prose): where the value a property has came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Origin { + /// TODO(prose): the layer whose rule or call set it. + pub layer: Layer, + /// TODO(prose): the class that set it. + pub source: Source, +} + +/// The winner of each property a class list sets. +#[cfg(debug_assertions)] +#[derive(Clone, Debug, Default)] +pub(crate) struct Origins(Vec<(Property, Origin)>); + +#[cfg(debug_assertions)] +impl Origins { + fn set(&mut self, property: Property, origin: Origin) { + match self.0.iter_mut().find(|(known, _)| *known == property) { + Some(known) => known.1 = origin, + None => self.0.push((property, origin)), + } + } + + fn get(&self, property: Property) -> Option { + self.0 + .iter() + .find_map(|(known, origin)| (*known == property).then_some(*origin)) + } + + /// These origins with `later`'s over them, property by property. + pub(crate) fn over(mut self, later: Self) -> Self { + for (property, origin) in later.0 { + self.set(property, origin); + } + self + } +} + +#[cfg(debug_assertions)] +impl Tw { + /// TODO(prose): the origin of `property`'s value, if a class set one. Debug builds only. + pub fn origin_of(&self, property: Property) -> Option { + self.origins.as_ref()?.get(property) + } + + /// Notes that the caller of the class method being run set `property`. + #[track_caller] + pub(super) fn note(&mut self, property: Property) { + let origin = Origin { + layer: Layer::CallSite, + source: Source::Rust(Location::caller()), + }; + self.origins + .get_or_insert_with(Box::default) + .set(property, origin); + } + + /// Notes each of `properties` the caller set. + #[track_caller] + pub(super) fn note_all(&mut self, properties: impl IntoIterator) { + for property in properties { + self.note(property); + } + } + + /// Gives the properties set so far by plain calls the layer `layer`. + pub(crate) fn staged(mut self, layer: Layer) -> Self { + for (_, origin) in self + .origins + .iter_mut() + .flat_map(|origins| origins.0.iter_mut()) + { + if origin.layer == Layer::CallSite { + origin.layer = layer; + } + } + self + } + + /// TODO(prose): gives the properties set so far by plain Rust calls `source`: the class of a shadcn sheet they were written for. Nothing in release builds. + #[must_use] + pub fn sourced(mut self, source: Source) -> Self { + for (_, origin) in self + .origins + .iter_mut() + .flat_map(|origins| origins.0.iter_mut()) + { + if matches!(origin.source, Source::Rust(_)) { + origin.source = source; + } + } + self + } +} + +#[cfg(not(debug_assertions))] +impl Tw { + #[inline(always)] + pub(crate) fn staged(self, _: Layer) -> Self { + self + } + + /// TODO(prose): gives the properties set so far by plain Rust calls `source`: the class of a shadcn sheet they were written for. Nothing in release builds. + #[must_use] + #[inline(always)] + pub fn sourced(self, _: Source) -> Self { + self + } +} + +#[cfg(all(test, debug_assertions))] +mod tests { + use egui::Color32; + + use super::*; + use crate::tw::tw; + + fn rust(origin: Option) -> (Layer, u32) { + let Some(Origin { + layer, + source: Source::Rust(at), + }) = origin + else { + return (Layer::Defaults, 0); + }; + (layer, at.line()) + } + + #[test] + fn a_class_notes_the_line_that_called_it() { + let (classes, line) = (tw().px(2.0), line!()); + assert_eq!( + rust(classes.origin_of(Property::padding_left)), + (Layer::CallSite, line) + ); + assert_eq!(classes.origin_of(Property::padding_top), None, "only px"); + assert_eq!(classes.origin_of(Property::width), None); + } + + #[test] + fn every_kind_of_class_notes_its_property() { + let line = line!() + 2; + let classes = tw() + .rounded_md() + .bg(Color32::RED) + .border_t_color(Color32::BLUE) + .text(Color32::GREEN); + for (property, extra) in [ + (Property::RadiusNw, 0), + (Property::Background, 1), + (Property::BorderColorTop, 2), + (Property::TextColor, 3), + ] { + assert_eq!( + rust(classes.origin_of(property)), + (Layer::CallSite, line + extra), + "{property:?}" + ); + } + assert_eq!(classes.origin_of(Property::BorderColorLeft), None); + } + + #[test] + fn a_merge_keeps_the_origin_of_the_class_that_won_each_property() { + let (first, first_line) = (tw().px(2.0).gap(1.0), line!()); + let (second, second_line) = (tw().px(4.0), line!()); + let merged = first.merge(second); + assert_eq!( + rust(merged.origin_of(Property::padding_left)), + (Layer::CallSite, second_line) + ); + assert_eq!( + rust(merged.origin_of(Property::gap_width)), + (Layer::CallSite, first_line) + ); + } + + #[test] + fn a_class_given_a_non_finite_length_notes_nothing() { + let rejected = tw().w_px(f32::NAN); + assert_eq!(rejected.origin_of(Property::width), None); + } + + #[test] + fn staging_gives_plain_calls_a_layer_and_leaves_staged_ones() { + let staged = tw().px(2.0).staged(Layer::Preset).merge(tw().py(1.0)); + let staged = staged.staged(Layer::App); + assert_eq!( + staged.origin_of(Property::padding_left).map(|o| o.layer), + Some(Layer::Preset) + ); + assert_eq!( + staged.origin_of(Property::padding_top).map(|o| o.layer), + Some(Layer::App) + ); + } + + #[test] + fn sourcing_names_the_class_a_rust_call_stands_for() { + let class = Source::Shadcn { + file: "styles/style-vega.css", + line: 182, + class: "px-2.5", + }; + let sourced = tw().px(2.5).sourced(class); + let again = sourced.clone().merge(tw().py(1.0)).sourced(Source::Shadcn { + file: "styles/style-vega.css", + line: 183, + class: "py-1", + }); + assert_eq!( + sourced.origin_of(Property::padding_left).map(|o| o.source), + Some(class) + ); + assert_eq!( + again.origin_of(Property::padding_left).map(|o| o.source), + Some(class), + "a class already sourced keeps its source" + ); + assert!(matches!( + again.origin_of(Property::padding_top).map(|o| o.source), + Some(Source::Shadcn { line: 183, .. }) + )); + } +} diff --git a/src/tw/paint.rs b/src/tw/paint.rs index dbb69883..c1a4067a 100644 --- a/src/tw/paint.rs +++ b/src/tw/paint.rs @@ -3,6 +3,8 @@ use crate::finite::clamp; use egui::{Color32, CornerRadius, Shadow}; +#[cfg(debug_assertions)] +use super::Property; use super::merge::Shape; use super::{BoxTw, Opacity, Tw}; @@ -103,6 +105,39 @@ impl BoxPaint { } } +/// The properties `after` paints differently from `before`. +#[cfg(debug_assertions)] +fn changed_paint(before: &BoxPaint, after: &BoxPaint) -> impl Iterator { + [ + (before.background != after.background, Property::Background), + ( + before.border_colors.top != after.border_colors.top, + Property::BorderColorTop, + ), + ( + before.border_colors.right != after.border_colors.right, + Property::BorderColorRight, + ), + ( + before.border_colors.bottom != after.border_colors.bottom, + Property::BorderColorBottom, + ), + ( + before.border_colors.left != after.border_colors.left, + Property::BorderColorLeft, + ), + ( + before.ring != after.ring || before.ring_placement != after.ring_placement, + Property::Ring, + ), + (before.shadow != after.shadow, Property::Shadow), + (before.divide_x != after.divide_x, Property::DivideX), + (before.divide_y != after.divide_y, Property::DivideY), + ] + .into_iter() + .filter_map(|(changed, property)| changed.then_some(property)) +} + fn radius(points: u8) -> CornerRadius { CornerRadius::same(points) } @@ -110,6 +145,7 @@ fn radius(points: u8) -> CornerRadius { macro_rules! rounded { ($($name:ident, $doc:literal, $points:expr;)*) => {$( #[doc = $doc] + #[cfg_attr(debug_assertions, track_caller)] pub fn $name(self) -> Self { self.shaped(|p| p.set_radius(radius($points))) } @@ -119,6 +155,7 @@ macro_rules! rounded { macro_rules! side_colors { ($($name:ident, $doc:literal, |$p:ident, $c:ident| $set:expr;)*) => {$( #[doc = $doc] + #[cfg_attr(debug_assertions, track_caller)] pub fn $name(self, color: impl Into) -> Self { self.painted(|$p| { let $c = Some(color.into()); $set }) } @@ -130,6 +167,7 @@ macro_rules! side_colors { macro_rules! paint_methods { () => { /// `bg-`. + #[cfg_attr(debug_assertions, track_caller)] pub fn bg(self, color: impl Into) -> Self { self.painted(|p| p.background = Some(color.into())) } @@ -145,12 +183,14 @@ macro_rules! paint_methods { } /// `divide-x-`: hairlines between children laid out in a row. + #[cfg_attr(debug_assertions, track_caller)] pub fn divide_x(self, width: f32, color: impl Into) -> Self { let color = color.into(); self.painted(|p| p.divide_x = Some(Divide { width, color })) } /// `divide-y-`: hairlines between children laid out in a column. + #[cfg_attr(debug_assertions, track_caller)] pub fn divide_y(self, width: f32, color: impl Into) -> Self { let color = color.into(); self.painted(|p| p.divide_y = Some(Divide { width, color })) @@ -169,30 +209,35 @@ macro_rules! paint_methods { } /// `rounded-[px]`: corner radius in points, rounded to whole points. + #[cfg_attr(debug_assertions, track_caller)] pub fn rounded_px(self, points: f32) -> Self { self.shaped(|p| p.set_radius(radius(clamp(points.round(), 0.0, 255.0) as u8))) } /// `rounded-tr-[px]`: top-right corner radius in points, rounded to /// whole points; the other corners keep theirs. + #[cfg_attr(debug_assertions, track_caller)] pub fn rounded_tr_px(self, points: f32) -> Self { self.shaped(|p| *p.radius_ne() = clamp(points.round(), 0.0, 255.0) as u8) } /// `rounded-br-[px]`: bottom-right corner radius in points, rounded to /// whole points; the other corners keep theirs. + #[cfg_attr(debug_assertions, track_caller)] pub fn rounded_br_px(self, points: f32) -> Self { self.shaped(|p| *p.radius_se() = clamp(points.round(), 0.0, 255.0) as u8) } /// `rounded-tl-[px]`: top-left corner radius in points, rounded to /// whole points; the other corners keep theirs. + #[cfg_attr(debug_assertions, track_caller)] pub fn rounded_tl_px(self, points: f32) -> Self { self.shaped(|p| *p.radius_nw() = clamp(points.round(), 0.0, 255.0) as u8) } /// `rounded-bl-[px]`: bottom-left corner radius in points, rounded to /// whole points; the other corners keep theirs. + #[cfg_attr(debug_assertions, track_caller)] pub fn rounded_bl_px(self, points: f32) -> Self { self.shaped(|p| *p.radius_sw() = clamp(points.round(), 0.0, 255.0) as u8) } @@ -201,6 +246,7 @@ macro_rules! paint_methods { /// CSS's `outline`, so a container that clips (a scroll container, /// `overflow_hidden`) cuts off the ring of a child flush with its edge: /// leave at least the ring's width as padding inside one. + #[cfg_attr(debug_assertions, track_caller)] pub fn ring(self, width: f32, color: impl Into) -> Self { let color = color.into(); self.painted(|p| p.ring = Some(Ring { width, color })) @@ -213,16 +259,19 @@ macro_rules! paint_methods { /// ```html ///

/// ``` + #[cfg_attr(debug_assertions, track_caller)] pub fn ring_inset(self) -> Self { self.painted(|p| p.ring_placement = RingPlacement::Inside) } /// `shadow-*`. + #[cfg_attr(debug_assertions, track_caller)] pub fn shadow(self, shadow: Shadow) -> Self { self.painted(|p| p.shadow = Some(shadow)) } /// `opacity-*`. + #[cfg_attr(debug_assertions, track_caller)] pub fn opacity(self, opacity: Opacity) -> Self { self.shaped(|p| p.set_opacity(opacity)) } @@ -230,15 +279,24 @@ macro_rules! paint_methods { } impl Tw { + #[cfg_attr(debug_assertions, track_caller)] fn painted(mut self, set: impl FnOnce(&mut BoxPaint)) -> Self { let mut after = self.paint; set(&mut after); + #[cfg(debug_assertions)] + let before = self.paint; self.paint = self.lengths.keep(self.paint, after, BoxPaint::is_finite); + #[cfg(debug_assertions)] + { + let changed: Vec = changed_paint(&before, &self.paint).collect(); + self.note_all(changed); + } self } /// [`painted`](Self::painted) for the properties that merging tracks: /// the corner radii and the opacity. + #[cfg_attr(debug_assertions, track_caller)] fn shaped(mut self, set: impl FnOnce(&mut Shape<'_>)) -> Self { self.write_shape(set); self @@ -248,10 +306,12 @@ impl Tw { } impl BoxTw { + #[cfg_attr(debug_assertions, track_caller)] fn painted(self, set: impl FnOnce(&mut BoxPaint)) -> Self { Self(self.0.painted(set)) } + #[cfg_attr(debug_assertions, track_caller)] fn shaped(self, set: impl FnOnce(&mut Shape<'_>)) -> Self { Self(self.0.shaped(set)) } diff --git a/src/tw/rules.rs b/src/tw/rules.rs index 997e31dd..9d59a70c 100644 --- a/src/tw/rules.rs +++ b/src/tw/rules.rs @@ -5,9 +5,10 @@ use std::ops::Not; use super::{BoxTw, Tw}; use crate::pipeline::NodeKind; +use crate::sheet::Layer; /// An ARIA state a node can say of itself and a [`Match`] can ask for. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Aria { /// TODO(prose): `aria-busy`. Busy, @@ -17,6 +18,8 @@ pub enum Aria { Disabled, /// TODO(prose): `aria-expanded`. Expanded, + /// TODO(prose): `aria-haspopup`. + HasPopup, /// TODO(prose): `aria-invalid`. Invalid, /// TODO(prose): `aria-pressed`. @@ -83,6 +86,9 @@ pub(crate) struct Ruled { has: Vec, /// Whether the rule these classes are the body of wins over a node's own. important: bool, + /// The classes the node's sheet gave it, which the rules above go over + /// and the node's own classes go over them. + base: Option>, } impl Ruled { @@ -91,6 +97,10 @@ impl Ruled { self.rules.extend(later.rules); self.has.extend(later.has); self.important |= later.important; + self.base = match (self.base, later.base) { + (Some(own), Some(later)) => Some(Box::new(own.merge(*later))), + (own, later) => later.or(own), + }; self } } @@ -357,39 +367,70 @@ impl Rules { self.top.is_none() } - /// `own` as the rules above give it its classes: the rules that match, - /// the farthest container's first, under `own`; the `important` ones - /// over it. - #[inline(never)] - pub(crate) fn apply(&self, links: &[Link], own: &Tw, kind: NodeKind) -> Tw { + /// The rules that match a node of `kind` with `facts`, the farthest + /// container's first. + fn matching<'a>(&self, links: &'a [Link], facts: &Facts, kind: NodeKind) -> Vec<&'a Rule> { let mut chain = Vec::new(); let mut at = self.top; while let Some(link) = at.and_then(|at| links.get(at as usize)) { chain.push(link); at = link.above; } - let facts = own.rules.as_ref().map_or(&NO_FACTS, |ruled| &ruled.facts); - let matching: Vec<&Rule> = chain + let depth = self.depth; + chain .iter() .rev() .flat_map(|link| { - let direct = link.depth == self.depth; + let direct = link.depth == depth; link.rules.iter().filter(move |rule| { (direct || rule.reach == Reach::Descendants) && rule.when.matches(kind, facts, false) }) }) - .collect(); + .collect() + } + + /// `own` as the rules above give it its classes: the rules that match, + /// the farthest container's first, under `own`; the `important` ones + /// over it. + #[inline(never)] + pub(crate) fn apply(&self, links: &[Link], own: &Tw, kind: NodeKind) -> Tw { + let matching = self.matching(links, own.facts(), kind); let mut under = Tw::blank(); for rule in matching.iter().filter(|rule| !rule.body.is_important()) { - under = under.merge(rule.body.clone()); + under = under.merge(rule.body.clone().staged(Layer::Ancestor)); } let mut applied = under.merge(own.clone()); for rule in matching.iter().filter(|rule| rule.body.is_important()) { - applied = applied.merge(rule.body.clone()); + applied = applied.merge(rule.body.clone().staged(Layer::Important)); } applied } + + /// [`apply`](Self::apply) for a node with a sheet's classes: the rules + /// that match go over those and under the node's own. + #[inline(never)] + pub(crate) fn apply_layered(&self, links: &[Link], own: Tw, kind: NodeKind) -> Tw { + let (sheet, own) = own.split_sheet(); + let flat; + let facts = match &sheet { + Some(sheet) => { + flat = sheet.facts().clone().merge(own.facts().clone()); + &flat + } + None => own.facts(), + }; + let matching = self.matching(links, facts, kind); + let mut under = sheet.unwrap_or_else(Tw::blank); + for rule in matching.iter().filter(|rule| !rule.body.is_important()) { + under = under.merge(rule.body.clone().staged(Layer::Ancestor)); + } + let mut applied = under.merge(own); + for rule in matching.iter().filter(|rule| rule.body.is_important()) { + applied = applied.merge(rule.body.clone().staged(Layer::Important)); + } + applied.without_sheet() + } } impl Tw { @@ -477,6 +518,40 @@ impl Tw { self } + /// Classes that say nothing, over the classes `sheet` gives a node: what + /// is merged into them goes over `sheet`, and the rules of the containers + /// above go between. + pub(crate) fn over_sheet(sheet: Tw) -> Tw { + let mut classes = Tw::blank(); + classes.ruled().base = Some(Box::new(sheet)); + classes + } + + /// Whether the node's classes hold a sheet's, to go under its own. + #[inline(always)] + pub(crate) fn is_layered(&self) -> bool { + self.rules + .as_ref() + .is_some_and(|ruled| ruled.base.is_some()) + } + + /// The sheet's classes of the node and its own. + fn split_sheet(mut self) -> (Option, Tw) { + let sheet = self + .rules + .as_mut() + .and_then(|ruled| ruled.base.take()) + .map(|sheet| *sheet); + (sheet, self) + } + + fn without_sheet(mut self) -> Tw { + if let Some(ruled) = self.rules.as_mut() { + ruled.base = None; + } + self + } + fn is_important(&self) -> bool { self.rules.as_ref().is_some_and(|ruled| ruled.important) } @@ -492,3 +567,72 @@ impl Tw { self.rules.get_or_insert_with(Box::default) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::tw::tw; + + fn glyph_size(rules: &Rules, links: &[Link], own: Tw) -> taffy::Dimension { + rules + .apply_layered(links, own, NodeKind::Glyph) + .style + .size + .width + } + + #[test] + fn rules_above_go_between_the_sheet_and_the_call_site() { + let mut links = Vec::new(); + let above = tw().descendants(Match::glyph(), |t| t.size_px(12.0)); + let rules = Rules::NONE.within(&above, &mut links); + let sheet = || tw().size_px(16.0).slot("icon"); + let width = |points| taffy::Dimension::length(points); + + let from_sheet = Tw::over_sheet(sheet()); + assert_eq!(glyph_size(&rules, &links, from_sheet), width(12.0)); + + let called = Tw::over_sheet(sheet()).merge(tw().size_px(20.0)); + assert_eq!(glyph_size(&rules, &links, called), width(20.0)); + + let nowhere = Tw::over_sheet(sheet()); + assert_eq!(glyph_size(&Rules::NONE, &[], nowhere), width(16.0)); + } + + #[test] + fn rules_above_match_the_sheets_slot() { + let mut links = Vec::new(); + let above = tw().children(Match::slot("icon"), |t| t.size_px(9.0)); + let rules = Rules::NONE.within(&above, &mut links); + let matched = Tw::over_sheet(tw().size_px(16.0).slot("icon")); + let plain = Tw::over_sheet(tw().size_px(16.0)); + let width = |points| taffy::Dimension::length(points); + assert_eq!(glyph_size(&rules, &links, matched), width(9.0)); + assert_eq!(glyph_size(&rules, &links, plain), width(16.0)); + } + + #[test] + fn the_applied_classes_keep_no_sheet() { + let applied = Rules::NONE.apply_layered(&[], Tw::over_sheet(tw().px(1.0)), NodeKind::Div); + assert!(!applied.is_layered()); + } + + #[cfg(debug_assertions)] + #[test] + fn each_property_keeps_the_layer_that_won_it() { + use crate::Property; + let mut links = Vec::new(); + let above = tw() + .descendants(Match::glyph(), |t| t.size_px(12.0)) + .descendants(Match::glyph(), |t| t.gap(2.0).important()); + let rules = Rules::NONE.within(&above, &mut links); + let sheet = tw().size_px(16.0).m(1.0).gap(1.0).staged(Layer::Preset); + let own = Tw::over_sheet(sheet).merge(tw().p(3.0)); + let applied = rules.apply_layered(&links, own, NodeKind::Glyph); + let layer = |property| applied.origin_of(property).map(|origin| origin.layer); + assert_eq!(layer(Property::width), Some(Layer::Ancestor)); + assert_eq!(layer(Property::margin_left), Some(Layer::Preset)); + assert_eq!(layer(Property::padding_left), Some(Layer::CallSite)); + assert_eq!(layer(Property::gap_width), Some(Layer::Important)); + } +} diff --git a/src/tw/text.rs b/src/tw/text.rs index 32b53fcd..2880fb05 100644 --- a/src/tw/text.rs +++ b/src/tw/text.rs @@ -2,6 +2,8 @@ use egui::{Color32, FontFamily}; +#[cfg(debug_assertions)] +use super::Property; use super::Tw; use crate::text::{ FontStyle, Numerals, TextAlign, TextCase, TextClasses, TextDecoration, TextSpec, Tracking, @@ -11,27 +13,71 @@ use crate::text::{ macro_rules! text_flags { ($($name:ident, $doc:literal, |$t:ident| $set:expr;)*) => {$( #[doc = $doc] + #[cfg_attr(debug_assertions, track_caller)] pub fn $name(self) -> Self { self.texted(|$t| $set) } )*}; } +/// The properties `after` sets differently from `before`. +#[cfg(debug_assertions)] +fn changed_text(before: &TextClasses, after: &TextClasses) -> Vec { + [ + (before.size != after.size, Property::TextSize), + ( + before.line_height != after.line_height, + Property::TextLineHeight, + ), + (before.family != after.family, Property::TextFamily), + (before.weight != after.weight, Property::TextWeight), + (before.color != after.color, Property::TextColor), + ( + before.font_style != after.font_style, + Property::TextFontStyle, + ), + ( + before.decoration != after.decoration, + Property::TextDecoration, + ), + ( + before.white_space != after.white_space, + Property::TextWhiteSpace, + ), + (before.align != after.align, Property::TextAlign), + (before.tracking != after.tracking, Property::TextTracking), + (before.case != after.case, Property::TextCase), + (before.select != after.select, Property::TextSelect), + (before.numerals != after.numerals, Property::TextNumerals), + ] + .into_iter() + .filter_map(|(changed, property)| changed.then_some(property)) + .collect() +} + impl Tw { + #[cfg_attr(debug_assertions, track_caller)] fn texted(mut self, set: impl FnOnce(&mut TextClasses)) -> Self { let mut after = self.text.clone(); set(&mut after); let before = std::mem::take(&mut self.text); + #[cfg(debug_assertions)] + let changed = changed_text(&before, &after); self.text = self.lengths.keep(before, after, |text| { [text.size, text.line_height] .into_iter() .flatten() .all(f32::is_finite) }); + #[cfg(debug_assertions)] + if self.lengths != super::Lengths::Rejected { + self.note_all(changed); + } self } /// The text role: size, line height, family and weight. + #[cfg_attr(debug_assertions, track_caller)] pub fn role(self, spec: TextSpec) -> Self { self.texted(|t| { t.size = Some(spec.size); @@ -42,21 +88,25 @@ impl Tw { } /// `font-normal`, `font-medium`, `font-semibold` or `font-bold`. + #[cfg_attr(debug_assertions, track_caller)] pub fn font_weight(self, weight: Weight) -> Self { self.texted(|t| t.weight = Some(weight)) } /// `text-`. + #[cfg_attr(debug_assertions, track_caller)] pub fn text(self, color: impl Into) -> Self { self.texted(|t| t.color = Some(color.into())) } /// `font-`: the family only, keeping the inherited size. + #[cfg_attr(debug_assertions, track_caller)] pub fn font(self, family: FontFamily) -> Self { self.texted(|t| t.family = Some(family)) } /// `tracking-*`. + #[cfg_attr(debug_assertions, track_caller)] pub fn tracking(self, tracking: Tracking) -> Self { self.texted(|t| t.tracking = Some(tracking)) } @@ -86,12 +136,14 @@ impl Tw { /// `line-clamp-`: wraps over at most `lines` lines (at least one), /// the last ending with an ellipsis where the text overflows. + #[cfg_attr(debug_assertions, track_caller)] pub fn line_clamp(self, lines: u32) -> Self { self.texted(|t| t.white_space = Some(WhiteSpace::Clamp(lines.max(1)))) } /// `truncate`: no wrapping, an ellipsis at the end, and `overflow-hidden` /// so the node may shrink below its text. + #[cfg_attr(debug_assertions, track_caller)] pub fn truncate(self) -> Self { self.texted(|t| t.white_space = Some(WhiteSpace::Truncate)) .overflow_x_hidden() diff --git a/tests/it/main.rs b/tests/it/main.rs index 1a3b53c7..5a5104a6 100644 --- a/tests/it/main.rs +++ b/tests/it/main.rs @@ -129,6 +129,7 @@ mod segmented_classes; mod select; mod selection; mod shadow_pixels; +mod sheet; mod sizing; mod skeleton; mod slider_header; diff --git a/tests/it/sheet.rs b/tests/it/sheet.rs new file mode 100644 index 00000000..f4b6cb81 --- /dev/null +++ b/tests/it/sheet.rs @@ -0,0 +1,263 @@ +//! A style's sheet (#443): the classes it gives a widget's parts, which +//! layer's win, and where the rules of the containers above come in. + +use eggshell_ui::contract::Variant; +use eggshell_ui::sheet::{Key, Part, When}; +use eggshell_ui::testing::{Driver, Target}; +use eggshell_ui::{Aria, Builder, Icon, Match, Problem, TextSpec, TextStyle, Weight, icons, tw}; +use egui::{FontFamily, vec2}; + +use crate::support; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Chip { + Root, + Icon, +} + +impl Part for Chip { + const SOURCE: &'static str = "badge.tsx"; + + fn slot(self) -> &'static str { + match self { + Self::Root => "chip", + Self::Icon => "chip-icon", + } + } +} + +const WIDE: Variant = Variant("wide"); + +fn base_text() -> TextStyle { + TextStyle::new( + TextSpec { + size: 14.0, + line_height: 20.0, + family: FontFamily::Proportional, + weight: Weight::Normal, + }, + egui::Color32::BLACK, + ) +} + +fn driver(view: fn(&mut Builder<'_, '_, ()>, &())) -> Driver<()> { + let mut d = support::driver(vec2(300.0, 200.0), base_text(), (), view).build(); + d.frames(4); + d +} + +fn size_of(d: &Driver<()>, name: &str) -> (f32, f32) { + let rect = d.rect(Target::suffix(name)); + (rect.width(), rect.height()) +} + +fn chevron() -> Icon { + Icon::new(icons::CHEVRON_DOWN) +} + +fn chip_rules(style: &mut eggshell_ui::Style) { + style + .sheet + .rule(Chip::Root, When::always(), |t| t.w_px(100.0).h_px(30.0)) + .rule(Chip::Root, When::always().variant(WIDE), |t| t.w_px(160.0)) + .rule(Chip::Root, When::always().aria(Aria::Invalid), |t| { + t.h_px(36.0) + }) + .rule(Chip::Icon, When::always(), |t| t.size_px(16.0)); +} + +fn parts(b: &mut Builder<'_, '_, ()>, _: &()) { + b.styled(chip_rules, |b| { + let plain = b.part(Chip::Root, &[]); + b.div_id("plain", plain, |_| {}); + let wide = b.part(Chip::Root, &[Key::Variant(WIDE)]); + b.div_id("wide", wide, |_| {}); + let invalid = b.part(Chip::Root, &[Key::Aria(Aria::Invalid)]); + b.div_id("invalid", invalid, |_| {}); + let called = b.part(Chip::Root, &[]).merge(tw().h_px(50.0)); + b.div_id("called", called, |_| {}); + }); +} + +#[test] +fn a_part_gets_the_classes_of_the_rules_whose_keys_hold() { + let d = driver(parts); + assert_eq!(size_of(&d, "\"plain\""), (100.0, 30.0)); + assert_eq!(size_of(&d, "\"wide\""), (160.0, 30.0), "a variant"); + assert_eq!(size_of(&d, "\"invalid\""), (100.0, 36.0), "an ARIA state"); +} + +#[test] +fn the_call_site_wins_over_the_sheet_property_by_property() { + let d = driver(parts); + assert_eq!( + size_of(&d, "\"called\""), + (100.0, 50.0), + "the height is the call site's, the width the sheet's" + ); +} + +fn icons_in_containers(b: &mut Builder<'_, '_, ()>, _: &()) { + b.styled(chip_rules, |b| { + let alone = b.part(Chip::Icon, &[]); + b.icon("alone", alone, chevron()); + b.div_id( + "container", + tw().descendants(Match::glyph(), |t| t.size_px(12.0)), + |b| { + let from_sheet = b.part(Chip::Icon, &[]); + b.icon("from-sheet", from_sheet, chevron()); + let called = b.part(Chip::Icon, &[]).merge(tw().size_px(20.0)); + b.icon("called", called, chevron()); + }, + ); + }); +} + +#[test] +fn the_rules_of_a_container_go_over_the_sheet_and_under_the_call_site() { + let d = driver(icons_in_containers); + assert_eq!(size_of(&d, "\"alone\""), (16.0, 16.0), "the sheet's own"); + assert_eq!( + size_of(&d, "\"from-sheet\""), + (12.0, 12.0), + "the container's rule beats the sheet's" + ); + assert_eq!( + size_of(&d, "\"called\""), + (20.0, 20.0), + "an explicit class beats the container's rule" + ); +} + +fn slots(b: &mut Builder<'_, '_, ()>, _: &()) { + b.styled(chip_rules, |b| { + b.div_id( + "container", + tw().children(Match::slot("chip-icon"), |t| t.size_px(9.0)), + |b| { + let icon = b.part(Chip::Icon, &[]); + b.icon("icon", icon, chevron()); + b.icon("other", tw().size_px(16.0), chevron()); + }, + ); + }); +} + +#[test] +fn a_part_declares_its_slot_for_the_rules_that_match_one() { + let d = driver(slots); + assert_eq!(size_of(&d, "\"icon\""), (9.0, 9.0)); + assert_eq!(size_of(&d, "\"other\""), (16.0, 16.0), "no slot, no match"); +} + +fn layers(b: &mut Builder<'_, '_, ()>, _: &()) { + b.styled( + |style| { + style + .sheet + .as_app() + .rule(Chip::Root, When::always(), |t| t.w_px(80.0)); + style + .sheet + .as_preset() + .rule(Chip::Root, When::always(), |t| t.w_px(100.0).h_px(30.0)); + }, + |b| { + let root = b.part(Chip::Root, &[]); + b.div_id("root", root, |_| {}); + }, + ); +} + +#[test] +fn a_later_layer_wins_whatever_order_its_rules_were_written_in() { + let d = driver(layers); + assert_eq!(size_of(&d, "\"root\""), (80.0, 30.0)); +} + +fn replaced(b: &mut Builder<'_, '_, ()>, _: &()) { + b.styled( + |style| { + style.sheet.as_preset(); + chip_rules(style); + style + .sheet + .as_app() + .replace(Chip::Root, When::always().variant(WIDE), |t| t.h_px(44.0)); + }, + |b| { + let wide = b.part(Chip::Root, &[Key::Variant(WIDE)]); + b.div_id("wide", wide, |_| {}); + let plain = b.part(Chip::Root, &[]); + b.div_id("plain", plain, |_| {}); + }, + ); +} + +#[test] +fn replace_discards_the_rules_below_it_where_it_holds() { + let d = driver(replaced); + let (width, height) = size_of(&d, "\"wide\""); + assert_eq!(height, 44.0); + assert_ne!(width, 160.0, "the variant's width is gone with the rest"); + assert_eq!( + size_of(&d, "\"plain\""), + (100.0, 30.0), + "elsewhere untouched" + ); +} + +fn unnamed(b: &mut Builder<'_, '_, ()>, _: &()) { + b.styled(chip_rules, |b| { + let odd = b.part(Chip::Root, &[Key::Variant(Variant("missing"))]); + b.div_id("odd", odd, |_| {}); + }); +} + +#[test] +fn a_variant_the_sheet_leaves_out_is_reported_and_drawn_without_it() { + let mut d = driver(unnamed); + d.expect_reported(Problem::MissingStyleEntry); + assert_eq!(size_of(&d, "\"odd\""), (100.0, 30.0)); +} + +fn negated(b: &mut Builder<'_, '_, ()>, _: &()) { + b.styled( + |style| { + style + .sheet + .rule(Chip::Root, When::always().not_aria(Aria::HasPopup), |t| { + t.w_px(70.0).h_px(20.0) + }); + }, + |b| { + let free = b.part(Chip::Root, &[]); + b.div_id("free", free, |_| {}); + let popup = b.part(Chip::Root, &[Key::Aria(Aria::HasPopup)]); + b.div_id("popup", popup, |_| {}); + }, + ); +} + +#[test] +fn a_negated_key_applies_while_the_node_lacks_the_state() { + let d = driver(negated); + assert_eq!(size_of(&d, "\"free\""), (70.0, 20.0)); + assert_ne!(size_of(&d, "\"popup\""), (70.0, 20.0)); +} + +#[test] +fn a_preset_hands_out_the_sheet_of_each_theme_at_the_preset_layer() { + use eggshell_ui_shadcn::{Palette, Shadcn, ShadcnStyle}; + let themed = Shadcn::themed(ShadcnStyle::Vega, Palette::new()); + assert_eq!( + themed.light.sheet.layer(), + eggshell_ui::sheet::Layer::Preset + ); + assert_eq!(themed.dark.sheet.layer(), eggshell_ui::sheet::Layer::Preset); + assert_eq!( + eggshell_ui::Style::default().sheet.layer(), + eggshell_ui::sheet::Layer::Defaults + ); +}