Skip to content

Design note: a cascade pass between build and layout (descendant, has-, aria/data-state rules) #443

Open

Description

@samitbasu

Approved as a design note first (user, 2026-11-19); no code yet.

The idea. eggshell builds the whole node tree each frame, then lays it out with taffy, then draws. A cascade pass between build and layout could resolve CSS-like selector rules against the complete tree, before measuring:

  • descendant and child rules: [&_svg]:, *:, **: (top-down);
  • has-[…]: a parent styled by its children (bottom-up; only possible once the children exist);
  • semantic-state rules: aria-checked:, aria-invalid:, data-[state=open]:, matched against the accessibility state nodes already carry.

hover:, focus-visible: and active: stay draw-time variants, as they are now.

Why. About 46% of shadcn's classes don't map today (the #433 spike), mostly exactly these selector forms. With rules as data, widgets could carry shadcn's classes almost verbatim, so the importer's ceiling rises and the "one shadcn source, no special cases" principle reaches state-dependent styling too.

The note must cover:

Activity

  1. samitbasu commented on Nov 20, 2026

    @samitbasu
    OwnerAuthor

    Motivating cases for the note, from the pinned source; use them as its worked examples:

    1. Focus within: .cn-input-group (styles/style-vega.css:1398) has-[[data-slot=input-group-control]:focus-visible]:border-ring ring-3. The group shows the ring when its inner input is focused. Extras: the command feature, a command palette, Combobox and Autosuggest (#345) #401's combobox wires this by hand today.
    2. Invalid within: the same rule's has-[[aria-invalid=true]]:border-destructive.
    3. Choice cards: .cn-field-label (:640) has-data-checked:bg-primary/5 border-primary/30. A card highlights when the control inside it is checked.
    4. Content-aware spacing: has-data-[icon=inline-start]:pl-1.5 (6 uses), which the button can't know today with custom children.

    A framing to keep: a widget's build declares structure, roles, state and rules. Theme values (Style tokens and extensions, #435) stay available during build; only context-dependent values are resolved in the pass, between build and layout.

  2. samitbasu commented on Nov 20, 2026

    @samitbasu
    OwnerAuthor

    Design note: selector rules (descendant, has-, state), resolved inside the build

    Status: proposal for review. No code. The questions at the end are the user's to decide.

    Written against main e984119. File:line references are on that commit. Counts of shadcn's classes are from apps/v4/registry/styles/style-vega.css at the pinned ref (f50887a): 2,657 class uses in @apply rules.

    0. The short version

    The issue proposes a pass between build and layout. I recommend no separate pass. Each rule form is resolved inside the build, at the moment its information first exists:

    form needs resolved
    descendant/child ([&_svg]:, *:, **:), ancestor (in-*, group-data-*) the ancestors on the way down: a node's rules travel in the builder's ambient, as inherited text already does
    has-[…] the children on the way up: a container's own style is resolved after its body has run, from facts its children report
    semantic state (aria-*, data-[state=…]) the node's state at build, because eggshell rebuilds every frame: any state the app or widget knows is fixed for that frame
    hover:, focus-visible:, active:, group-hover: input at draw, unchanged

    It rests on two invariants of the build:

    1. The build is depth-first, and a container's node is created after its children (src/builder.rs:1743-1765, new_node(style, &kids, node) at :1762). Everything above a node is known when it is built, and everything below is known when its container closes.
    2. The tree is rebuilt every frame. "State" that isn't input (expanded, invalid, checked, open, a prop such as data-[size=sm]) is a value the builder already has.

    A separate pass would have to keep every node's unresolved Tw (a whole taffy Style and more; nodes keep only the resolved style, src/pipeline.rs:98), walk the tree again, and re-resolve inherited text after the fact. It buys nothing the build's own order doesn't already give.

    1. What the forms cost us today

    These are the uses in Vega's stylesheet, by the most demanding variant in each class. Classes with no variant, or with draw-time ones only, are left out.

    form uses layout paint animation
    descendant/child: [&_svg]:, [&>svg]:, *:, **: 174 90 84 0
    has-[…] 105 68 37 0
    ancestor/sibling: in-*, group-*, peer-* 176 87 82 7
    state: aria-*, data-*, not-* 549 94 200 255
    • The animation half of the state row is data-open:animate-in, data-closed:fade-out-0 and similar. That's presence and transition work, so it's out of scope here.
    • The rest, about 650 uses (a quarter of all classes), is this note's subject. The spike's 46% unmapped share for Button, Badge and Combobox is mostly these forms. The remainder is missing utilities and arbitrary values, which Tw grows one by one.
    • "Own classes win" is what shadcn already writes. Vega's descendant icon sizing is [&_svg:not([class*='size-'])]:size-N 38 times, against 11 bare [&>svg]:size-N, one of them size-3!.

    2. The rule forms in Tw

    Selectors match attributes, which a node declares in its classes, the way HTML puts data-slot and the class list on one element. The match set is closed and typed; there are no CSS strings.

    // Attributes: what rules match on.
    tw().slot("button")                       // data-slot="button"
        .attr("size", "sm")                   // data-size="sm" / data-[size=sm]
        .aria(Aria::Invalid)                  // aria-invalid (also Expanded, Checked, Selected, Disabled, HasPopup)
    
    // Rules: classes for other nodes, or for this one depending on others.
        .descendants(Match::Glyph, |t| t.size(4.0).shrink_0())      // [&_svg:not([class*='size-'])]:size-4 shrink-0
        .children(Match::Glyph, |t| t.size(3.0).important())        // [&>svg]:size-3!
        .children(Match::slot("input-group"), |t| t.h(8.0))         // *:data-[slot=input-group]:h-8
        .has(Match::Glyph.attr("icon", "inline-start"), |t| t.pl(2.0))  // has-data-[icon=inline-start]:pl-2
        .has(Match::aria(Aria::Invalid), |t| t.border_color(destructive)) // has-aria-invalid:border-destructive
        .within(Match::slot("button-group"), |t| t.rounded_md())    // in-data-[slot=button-group]:rounded-md
    • Match is a small enum combinator: a node kind (Glyph and Icon stand for svg, plus Text and Any), a slot, an attribute, an ARIA state, and not. It is Copy and holds &'static str names, so matching compares pointers or short strings and allocates nothing.
    • State on the node itself needs no rule. aria-expanded:bg-muted on the button is .when(open, |t| t.bg(muted)), because the widget knows open when it builds. The importer emits that form.
    • has bodies are box classes only: layout and box paint, no inherited text. The children have already inherited the container's text by the time has resolves (builder.rs:1533, tw.text.over(self.inherited)). The body's type, BoxTw, has no text methods, so this is a type error rather than a runtime report. Vega's has- uses that set text: measured in PR 2, and expected to be few.
    • peer-* (16 uses) matches an earlier sibling, which is built before the node. It fits the same model but is left until a widget needs it.

    3. Where it sits

    • Down (descendant, child, within). Builder::ambient_in (builder.rs:1612) already computes what a container hands its body. It gains the container's rules, as a persistent list (Rc chain): a container without rules passes the pointer through, and one with rules pushes a link. When a node is built, the active rules that match it are merged into its classes before resolved_style (builder.rs:1566). children rules apply at depth 1 only, and descendants at any depth.
    • Up (has). Each built node returns a small set of facts to its parent: its kind, slot, attributes and ARIA state, OR'ed with its subtree's facts. children-scoped facts are kept apart from the rest, for has-[>…]. container already holds the parent's Tw across body (it resolves the style before body today, but nothing stops it from resolving it after). It evaluates the parent's has rules against the facts, then calls new_node.
    • State. ARIA state that is set today from a draw closure moves to build-time node data. NodeHandle::expanded (builder.rs:2239) writes AccessKit from the draw closure, so has-aria-expanded couldn't see it. With .aria(Aria::Expanded) in the classes, the draw closure reads the node's data instead, and AccessKit is written from one source.
    • Overlays and pop-outs don't receive rules, matching shadcn: Base UI portals its popups, so a trigger's [&_svg]: never reaches the popup either.
    • A region's content is built after layout (src/region.rs, src/pipeline.rs:876). It inherits the ambient rules of its leaf. Its facts can't reach an ancestor's has, because that ancestor was laid out a phase earlier. This is documented, the one place has is blind.

    4. Ordering and specificity

    CSS decides by specificity, then source order. I propose a simpler order that gives the same result for what shadcn writes:

    1. A node's own classes win over rules from outside, property by property. Tw already records which properties a list set (Touched, src/tw/merge.rs:23). An ancestor's rule fills only the properties the node left untouched. This is exactly :not([class*='size-']), generalised.
    2. important() reverses that for one rule (size-3!).
    3. Among ancestors, the nearest wins. That's the same as text inheritance, so b.styled and rules read alike.
    4. Within one class list, later wins, as Tw::merge does now (src/tw/merge.rs:298). A has or .when piece is merged at the position it was written.
    • Where CSS differs: a bare [&>svg]:size-4 beats a child's own size-3 in CSS, because the selector is more specific, but under rule 1 the child wins. Vega writes the guarded form in 38 of 49 cases. The importer flags the bare ones, and reports when the same component also sizes that child, so the difference is visible, never silent.

    5. Per-frame cost

    • Down: for each node, about (active rules) × (match test). The rules active at any node are those of its ancestors: a handful for a widget, none for most of an app's own tree. A node under no rules pays one pointer copy.
    • Up: one OR of a fact set per node. Facts are a fixed bitset for kinds and ARIA states, plus a short inline list of slot names. That list is only collected under a container whose has rules name slots, so the common case is the bitset alone.
    • No extra walk, no kept Tws, and no re-layout. Everything resolves before new_node, so taffy sees final styles once.
    • PR 1 checks the cost with the frame bench (benches/frame.rs): a rule-free tree must show no change, and a Button-heavy page gets a number in the PR.

    6. How widgets move

    A widget keeps resolving its own look eagerly (variant and size tables, .when for its own state). It takes up rules only where a rule reaches nodes it doesn't build, or depends on what it contains:

    • Button (src/owned/button.rs):
      • Glyph size is b.glyph(tw().size_px(glyph)) at :673 today, so a glyph the caller builds in children (:679) gets no size. It becomes descendants(Match::Glyph, size) on the button, which reaches the caller's glyphs too.
      • Icon-side padding (has-data-[icon=inline-start]:pl-2) isn't implemented at all today. It becomes a has rule, so it holds for the caller's icons as well as .icon().
    • Badge, menu items, select, stepper, checkbox, command list each pass a glyph metric down by hand today: 8 .glyph(tw()…) sites, and glyph / icon_size fields in contract.rs and the badge style.
    • Combobox and input-group gain the most, through *:data-[slot=…] and has-aria-invalid.
    • The migration is behaviour-preserving, widget by widget. Goldens stay identical, except Button's icon padding, which is the Preset: Button matches current shadcn (generated by shadcn-import) #433 change.

    7. With scoped style (#355), owned style (#435) and the importer (#433)

    • b.styled scopes the Style, meaning tokens and metrics. Rules scope classes for matching nodes. Both travel down the same ambient, with the same nearest-wins order.
      • The importer currently maps descendant selectors onto b.styled. Once rules land they map onto rules verbatim, and b.styled stays the app's tool for token overrides.
    • Global style changes only through &mut LayoutState (unrepresentable mid-build) #435. Rules are per-node classes, so they don't live in Style, and the owned-style change doesn't touch them. Two points meet:
      • (a) Global base rules: shadcn's globals.css has * { border-border outline-ring/50 }. That could be a Style-level rule list at the root (Q3).
      • (b) Where a preset's classes come from: shadcn's style files are a stylesheet, slot → classes (.cn-button → …). With attributes and rules, a preset could be exactly that, a generated slot → Tw table stored as a Style extension, with each widget declaring its slot. That is a later step, not part of this note's PRs (Q4).
    • Preset: Button matches current shadcn (generated by shadcn-import) #433, the Button generation, isn't blocked.
      • The generator emits has-data-[icon=inline-start] and [&_svg:not([class*='size-'])] in today's eager form: the widget's icon.is_some() and the metrics glyph size.
      • It records each one as the mapping kind "eager, rule-ready".
      • When PRs 1-2 land, only the emitter changes, and Button's goldens don't move again.

    8. What it deletes

    • Most of the importer's unmapped categories:
      • [&…], *:, **:, has-*, in-*, group-data-*;
      • aria-* and data-* state on other nodes.
    • The hand-threaded icon-size metrics, once their widgets move (§6).
    • Draw-closure ARIA writes such as expanded, which become build-time node data with one writer.
    • Per-widget special cases for "what's inside me", such as the icon padding, which today would have been an if icon.is_some() in each widget.

    9. Order of work, each a PR

    1. Attributes and top-down rules. slot/attr/aria in Tw, Match, descendants/children/within, own-wins via Touched, important, and bench numbers. The importer maps those forms.
    2. has. Facts bubbled up, the style resolved after body in container, and BoxTw.
    3. ARIA state at build. expanded, invalid, checked, selected and has_popup move to node data, and their AccessKit writes come from it.
    4. Widgets, one PR each, goldens unchanged. Button first, through the Preset: Button matches current shadcn (generated by shadcn-import) #433 generator's emitter.

    Questions for the user

    # Question Recommendation
    Q1 A separate pass between build and layout, as the issue proposes, or resolution inside the build (down on entry, up on close)? Inside the build. Same results, no second walk, no kept Tws, no re-inheritance.
    Q2 Ordering: a node's own classes win over ancestor rules unless important() (shadcn's :not([class*=size-]) as the rule), or full CSS specificity? Own classes win. It is what shadcn writes in 38 of 49 cases. The importer flags the rest.
    Q3 A root-level rule list in Style for shadcn's * { border-border … } base layer? Yes, but later. Today's defaults already give the same result; it becomes useful when presets are stylesheets.
    Q4 Long term, should a preset be a generated slot → Tw stylesheet (with rules) rather than per-widget style structs? Yes as the direction, decided separately. This note's PRs don't depend on it.
    Q5 has restricted to box classes (no inherited text), enforced by type? Yes. The alternative is re-resolving the children's text after the fact.
  3. samitbasu commented on Nov 20, 2026

    @samitbasu
    OwnerAuthor

    User answers (2026-11-19):

    • Q1: rules are resolved inside the build: descendant rules flow down with the builder, and has- applies as each parent closes after its children.
    • Q2: own classes win over ancestor rules, property by property, with important() as the explicit override.
    • Q5: has- sets box properties only, enforced by type.
    • Q3: a root rule list for shadcn's base layer, later.
    • Q4: adopt the stylesheet direction:
      • widgets are behaviour plus anatomy, with typed part enums (names from Radix/Base UI parts and shadcn's data-slot);
      • presets are a Sheet of conditional Tw rules per part, with small typed metric structs only for numbers widgets compute with;
      • layers, later wins per property: widget defaults → preset → app → b.styled scopes → ancestor rules → call-site classes. replace is explicit.
      • Debug-build provenance per property (the layer plus a source: shadcn file:line from the importer, #[track_caller] for Rust), shown by a Computed-style inspector in the F12 overlay, plus frame.why(node, prop) and a console dump.

    Next: a design note for the Sheet, its layers, provenance and the inspector. #435 PR 2 builds the extension map and the preset split now, without converting each extras struct (those move to parts via the importer).

  4. samitbasu commented on Nov 20, 2026

    @samitbasu
    OwnerAuthor

    Rule forms in Tw: API sketch for PR 1 and PR 2 (from the note, checked against main a26345f)

    No code yet. Three things in the code shape it, and four questions at the end.

    What the code already gives us

    • "Own classes win" is Tw::merge. It already merges per property (src/tw/merge.rs:298, Touched is what it consults), so a rule is merged under the node's own classes: rule.merge(own). important() flips the order: own.merge(rule). No second precedence mechanism and no pass over Touched.
    • Down: Builder::ambient_in (builder.rs:1612) is where a container's rules join what its body inherits. Ambient is Copy today, so the rule chain (Option<Rc<Link>>, a persistent list) makes it Clone. A container with no rules passes the same pointer. A virtual list's rows (RowsLeaf) keep the chain, since they are built after layout.
    • Up: container (builder.rs:1743) builds the node's Node (self.node, with its inherited text) before the body. For has it splits: text first, since the children inherit it; then the body; then the has rules over the children's facts; then resolved_style and new_node. A node with no has rules is resolved exactly as today.

    The API

    // What a node says of itself (typed; no strings but names):
    tw().slot("input-group")                 // data-slot
        .attr("size", "sm")                  // data-size
        .aria(Aria::Invalid)                 // aria-invalid etc. (PR 3 makes AccessKit read it)
    
    // Rules (data: a Match, a scope and a Tw body; the closure runs at once):
        .descendants(Match::glyph(), |t| t.size(4.0).shrink_0())        // [&_svg]:size-4 shrink-0
        .children(Match::glyph(), |t| t.size(3.0).important())          // [&>svg]:size-3!
        .children(Match::slot("input-group"), |t| t.h(8.0))             // *:data-[slot=input-group]:h-8
        .has(Match::slot("icon").attr("side", "start"), |b| b.pl(1.5))  // has-data-[icon=inline-start]:pl-1.5
        .has(Match::aria(Aria::Invalid), |b| b.border_color(c))         // has-aria-invalid:border-destructive
    • Match is a Copy combinator over &'static strs: a kind (glyph(), text(), any()), slot, attr, aria, not. Matching allocates nothing.
    • children/has look one level (>); descendants looks at any depth. in-*/within/peer-* are left for a widget that needs them.
    • important() is on the rule's body (t.size(3.0).important()), not a property flag, so one rule can mix.
    • Own state needs no rule (.when(open, ..)), as in the note.

    Order of resolution for one node

    ancestors' rules (nearest wins) merged under own classes, with important rules merged over them; then, once the body has run, has rules (box-only) merged at the position they were written. Rules whose scope does not reach a node (overlays, pop-outs) are not passed to it, per the note.

    Questions

    1. BoxTw, enforced by type. The body of has gets a type with only layout and box-paint methods. Without duplicating those few hundred signatures: (a) a newtype BoxTw(Tw) whose methods are generated from one macro list of the layout/paint surface (one place names them, like layout_properties!), or (b) make the layout/paint methods provided methods of a trait implemented for Tw and BoxTw, which means every user imports a trait. Recommend (a).
    2. has over focus. The motivating case (the input group's ring) is has-[…:focus-visible]. Focus is input, known to the build only from the previous frame (as has_focus_within already reads it). I'd offer Match::focus_visible() resolved from last frame's focus, with a one-frame lag documented; the alternative is leaving it to has_focus_within by hand, as today. Recommend the former.
    3. First Match surface. The forms above, nothing more; not and peer/within when a widget wants one. OK?
    4. Benchmarks. PR 1 adds a frame-bench scenario for a Button-heavy page with rules, and a rule-free tree must show no change in criterion.

    Plan: PR 1 = attrs + descendants/children + merge order + important + bench; PR 2 = has + BoxTw + facts. Both with tests through the real builder, TODO(prose) one-liners and doctests, and no widget changes.

  5. samitbasu commented on Nov 20, 2026

    @samitbasu
    OwnerAuthor

    User answers on the rule-forms API (2026-11-20, sonnet-1's sketch above):

    1. BoxTw: a macro-generated newtype (one list of box methods, like layout_properties!), not a trait.
    2. Match::focus_visible() for has, read from last frame's focus, with the one-frame lag documented.
    3. The first Match surface: kind (glyph/text/any), slot, attr, aria, not. peer/within come later, on demand.
    4. The bench: PR 1 adds a button-heavy rules scenario, and a rule-free tree shows no measurable change.

    Go: PR 1 (attrs, descendants/children, merge order, important, the bench), then PR 2 (has, BoxTw, facts).

  6. added 3 commits that reference this issue on Nov 20, 2026
  7. samitbasu commented on Nov 20, 2026

    @samitbasu
    OwnerAuthor

    Design note: the Sheet (parts, layers, provenance, the inspector)

    Status: proposal for review. No code. It follows the user's Q4 answer: widgets are behaviour plus anatomy, and presets are a Sheet of conditional Tw rules per part. The questions at the end are the user's to decide.

    Written against main 6f3b241, after #456/#458 (rules), #459 (Tw 840 bytes) and #435's extension map. The worked example throughout is shadcn's Button: bases/base/ui/button.tsx and styles/style-vega.css:145-203 at the pinned ref f50887a.

    0. The short version

    • A widget names its parts with a typed enum (ButtonPart::Root). It builds each part's node from style.sheet.resolve(part, &keys), a Tw, then lays the call site's classes over it.
    • A Sheet is an ordered list of rules: (part, when, Tw body, layer, source). when is a conjunction of typed Keys: variant, size, attribute, ARIA state.
    • Layers, later wins per property: widget defaults → preset → app → b.styled scopes → ancestor rules (Tw rule forms, PR 1: descendants and children rules, slot/attr/aria, important (#443) #456) → call site. replace() is the one explicit way to discard what lower layers set.
    • Debug builds record, for every property of every node, the layer and source of its winning value: shadcn file:line for imported rules, the Rust call site through #[track_caller]. The F12 overlay shows it as a Computed-style pane, why(node, property) answers it in tests, and a console dump prints it.
    • The importer emits a Sheet per shadcn style (Vega, Lyra) as checked-in Rust, one generated rule per cn-* class block, each carrying its source line.

    1. Parts: typed enums

    /// A widget's anatomy: the nodes a sheet can style.
    pub trait Part: Copy + Eq + Ord + Debug + Send + Sync + 'static {
        /// The shadcn component this widget's look comes from (one source per widget).
        const SOURCE: &'static str;               // "button.tsx"
        /// This part's `data-slot`: what rules and the importer match.
        fn slot(self) -> &'static str;             // "button", "button-icon"
    }
    
    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
    pub enum ButtonPart { Root, Icon, Label }
    • Variant names come from the Radix/Base UI anatomy: Root, Trigger, Content, Item, ItemIndicator, Separator.
    • slot() is shadcn's data-slot string, so the importer maps cn-select-trigger → SelectPart::Trigger by name, and Tw rule forms, PR 1: descendants and children rules, slot/attr/aria, important (#443) #456's Match::slot matches the same string.
    • A widget's part node carries the slot. Building with a part sets Tw::slot(part.slot()), so ancestor rules (*:data-[slot=input-group]:…) and has rules find it with no extra declaration.
    • The trait is open. The extras' and an app's own widgets declare parts the same way, and core names none of them.

    2. Keys and When

    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum Key {
        Variant(Variant),                          // cva `variant:`, today's `Variant`
        Size(Size),                                // cva `size:`, today's `Size`
        Attr(&'static str, &'static str),          // data-[orientation=vertical], data-[side=top]
        Aria(Aria),                                // aria-expanded, aria-invalid, aria-checked (#456's `Aria`)
    }
    
    /// All of its keys hold. `When::always()` is the part's base.
    pub struct When { keys: [Option<Key>; 4] }     // Copy, no allocation; 4 covers shadcn's deepest
    • The widget supplies the node's keys when it resolves: [Key::Variant(v), Key::Size(s), Key::Aria(Aria::Expanded)]. They're the values it already has at build: props, plus state known because the tree is rebuilt every frame (§0 of the first note).
    • dark: is not a key. Style is already a light/dark pair (Themed<Arc<Style>>, Global style changes only through &mut LayoutState (unrepresentable mid-build) #435), so the importer writes dark: classes into the dark half's sheet and the base classes into both. The theme decides which sheet is read, not a condition in it.
    • hover:, focus-visible: and active: stay Tw variants inside a rule's body (t.hover(|p| p.bg(..))), resolved at draw as now.
    • in-data-[slot=button-group]: is an ancestor condition, not the node's own. It stays Tw rule forms, PR 1: descendants and children rules, slot/attr/aria, important (#443) #456's form (a within rule, on demand), emitted by the importer on the ancestor's part.
    • Unknown keys are still reported. A sheet knows which Variants and Sizes it names for each widget. Resolving with one it never names reports Problem::MissingStyleEntry as Keyed::lookup does today (contract.rs:61).

    3. The Sheet API and resolve

    pub struct Sheet { /* rules by part, in layer order; Arc'd so clones are cheap */ }
    
    impl Sheet {
        /// A rule at the layer of whoever is writing (§4).
        #[track_caller]
        pub fn rule<P: Part>(&mut self, part: P, when: When, body: impl FnOnce(Tw) -> Tw) -> &mut Self;
        /// The same, but the part's properties start empty under it: every lower rule is dropped.
        #[track_caller]
        pub fn replace<P: Part>(&mut self, part: P, when: When, body: impl FnOnce(Tw) -> Tw) -> &mut Self;
        /// The part's classes for a node with `keys`: every matching rule, in layer then
        /// insertion order, merged with `Tw::merge` (later wins per property).
        pub fn resolve<P: Part>(&self, part: P, keys: &[Key]) -> Tw;
        /// The variants and sizes the sheet names for `P`'s widget (for galleries and the report).
        pub fn keys<P: Part>(&self) -> impl Iterator<Item = Key> + '_;
    }

    The Button, roughly as the importer would emit it (Vega, light half, abridged; focus is Tw's focus-visible variant):

    use ButtonPart::*;
    s.rule(Root, When::always(), |t| t                       // style-vega.css:146 (.cn-button) + button.tsx:6 (cva base)
        .rounded_md().border(1.0).border_color(TRANSPARENT).text_sm().font_medium()
        .focus(|p| p.border_color(k.ring).ring(3.0, k.ring.alpha(0.5)))
        .descendants(Match::glyph(), |t| t.size(4.0).shrink_0())      // [&_svg:not([class*='size-'])]:size-4
    );
    s.rule(Root, When::always().aria(Aria::Invalid), |t| t.border_color(k.destructive).ring(3.0, k.destructive.alpha(0.2)));
    s.rule(Root, When::variant("default"), |t| t.bg(k.primary).text(k.primary_foreground)
        .hover(|p| p.bg(k.primary.alpha(0.8))));                      // :150
    s.rule(Root, When::size("default"), |t| t.h(9.0).gap(1.5).px(2.5)  // :182
        .has(Match::glyph().attr("icon", "inline-start"), |b| b.pl(2.0))
        .has(Match::glyph().attr("icon", "inline-end"),   |b| b.pr(2.0)));
    s.rule(Root, When::size("xs"), |t| t.h(6.0).gap(1.0).rounded_px(8.0).px(2.0).text_xs()
        .descendants(Match::glyph(), |t| t.size(3.0)));               // :174
    • resolve cost. A widget's rules are indexed by part. Resolving filters that list (Button: 1 base, 1 invalid, 6 variants, 8 sizes) by When against the given keys, then merges the matches (2-4 for a button). Results are memoised by (part, keys) in the sheet. A sheet is immutable once it is in an Arc<Style>, so the memo is valid until set_style.
    • b.styled scopes edit a clone, which starts cold. PR 1 measures that case with the frame bench's rules scenario (Tw rule forms, PR 1: descendants and children rules, slot/attr/aria, important (#443) #456 measured one rule at +16% per button, from cloning its body).
    • Small typed metric structs stay where a widget computes with a number rather than paints it: a slider's thumb travel, a switch's thumb inset, a splitter's grip hit area. They become Keyed<Size, M> extensions beside the sheet (Global style changes only through &mut LayoutState (unrepresentable mid-build) #435's map), not rules.
      • Button needs none. Height, padding, gap, radius and icon size are all classes. press_shift is active:translate-y-px. Today's ButtonStyle (contract.rs:436) and Metrics (:381) go entirely.

    4. Layers, and what "later wins" means

    # layer who writes it where it lives
    1 widget defaults the widget's crate: today's XStyle::from_egui the sheet, written by Sheet::defaults()
    2 preset generated by the importer, then the preset's own Rust adjustments the sheet, via Shadcn::sheet(..)
    3 app the app, over the preset pair before set_style (Themed::map) the sheet
    4 b.styled scope `b.styled( s
    5 ancestor rules descendants / children / has on containers above (#456/#458) the builder's ambient
    6 call site b.button(..).classes(tw()…) the node's own Tw
    • The layer of a sheet rule is the writer's, not an argument.
      • The sheet carries a current layer, set by the code that hands it out: Sheet::defaults() for widget crates, the preset constructor, the app's set_style path, and b.styled (which sets scope before calling the edit).
      • So an app can't write a rule "as the preset", and provenance (§5) always names the true writer.
    • Within a layer, insertion order. Across layers, the layer number. "Later wins" is per property: each step is Tw::merge (merge.rs:298), which already merges property by property.
    • replace() empties the part's properties before its body, for the keys it names. "This app's destructive button is not tinted" is replace(Root, When::variant("destructive"), ..), with no need to undo every lower property by hand.
    • The one change to Tw rule forms, PR 1: descendants and children rules, slot/attr/aria, important (#443) #456's resolution.
      • Today Rules::apply (rules.rs:364) merges ancestor rules under the node's whole own Tw. With a sheet, the node's own Tw splits into its sheet part (layers 1-4) and its call-site part (layer 6), and ancestor rules sit between them:
        sheet.merge(ancestors).merge(call_site), then the important ones over all of it.
      • That's what shadcn gets from CSS. .cn-button-size-xs's [&_svg]:size-3 beats the icon's own default size (16) but not a caller's explicit size-5.
      • The widget hands the two over separately, through a builder entry that takes both (b.part_node(sheet_tw, call_site_tw, ..)). Its node is otherwise built exactly as now.
      • A plain div has no sheet part, so its behaviour is unchanged.
    • important() (Tw rule forms, PR 1: descendants and children rules, slot/attr/aria, important (#443) #456) stays the explicit override, above layer 6.

    5. Provenance, debug builds only

    #[cfg(debug_assertions)]
    pub struct Origin { pub layer: Layer, pub source: Source }
    
    #[cfg(debug_assertions)]
    pub enum Source {
        Shadcn { file: &'static str, line: u32, class: &'static str },   // emitted by the importer
        Rust(&'static std::panic::Location<'static>),                     // #[track_caller]
    }
    • What is recorded.
      • A Tw gains, in debug builds only, an Option<Box<Origins>>: the origin of each property it has set, written by the same mark that sets Touched (merge.rs:23). merge carries the winner's origin with the value.
      • Release builds have no field, so Tw stays 840 bytes there.
      • Touched covers layout, radii and opacity today. Box paint and text classes merge field by field. PR 1 extends the one property list (layout_properties!) to name those too, so every property has an identity to hang an origin on.
    • Where Rust sources come from.
      • #[track_caller] on every class method. They're generated from the macro lists (layout_methods! layout.rs:152, paint_methods! paint.rs:130, grid_methods! grid.rs:151), so that's one attribute in each list.
      • Plus Sheet::rule, replace and b.styled.
      • Location::caller() costs nothing in release, where the field is gone.
    • Imported sources are literals in the generated file: Source::Shadcn { file: "styles/style-vega.css", line: 182, class: "has-data-[icon=inline-start]:pl-2" }. That's per class, not per block, because the spike's parser already keeps each class's span (source.rs:34).
    • Per node: the built Node keeps its final origins (debug only), so the overlay and why read them after layout.
    • The full chain (every layer that set the property, not only the winner) is recorded only for a traced node. Recording it for every node every frame would cost too much even in debug. Tracing a node (§6) makes the next build keep its chain, one frame later, as Match::focus_visible does (Tw rule forms, PR 2: has, BoxTw, Match::focus_visible (#443) #458).

    6. The inspector, why, and the console dump

    • The F12 overlay (Debug::Outlines, debug.rs:65) already labels the node under the pointer. It gains a pinned node, chosen by clicking with the overlay on (Esc unpins), and a Computed-style pane for it, like a browser's devtools:

      /Page/Save  (button · Root · variant=default size=default)
      padding-left   8    preset  style-vega.css:182  has-data-[icon=inline-start]:pl-2
                     10   preset  style-vega.css:182  px-2.5          (overridden)
      background   primary/80 on hover   preset  style-vega.css:150  hover:bg-primary/80
      height        40    call site  examples/toolbar.rs:51  .h(10.0)
                    36    preset  style-vega.css:182  h-9             (overridden)
      
      • Overridden entries come from the traced chain (§5), so they appear on the frame after pinning.
    • why(node, property) for tests and tools:

      let why = d.why(Target::suffix("Save"), Property::PaddingLeft);   // Driver; Placed::why for apps
      assert_eq!(why.winner.layer, Layer::Preset);
      • It traces the node and steps a frame if no chain is recorded yet.
      • Debug builds only; in release, why doesn't exist.
    • The console dump, which CLAUDE.md prefers for developer tooling:

      • Shift+F12 with a node pinned prints the same table to stderr.
      • EGGSHELL_WHY=<path suffix> prints it for every node matching that suffix whenever its computed style changes.
      • Paths are the overlay's readable paths, so a test failure's path pastes straight in.

    7. How widgets migrate

    Each widget's PR is behaviour-preserving unless it is the one whose values the importer changes:

    1. Declare XPart, with SOURCE and slots.
    2. Write today's XStyle::from_egui values as the widget-defaults layer, and the shadcn preset's current hand values as preset rules.
    3. Build each part through resolve, plus the call site's classes, through the two-part builder entry.
    4. Delete XStyle's look and metric fields. Numbers the widget computes with move to a Keyed<Size, M> extension.
    5. Goldens must not change, except where a value really changed.
    • Order: Button first, through the generator (Preset: Button matches current shadcn (generated by shadcn-import) #433; its goldens move once, to current shadcn). Then Badge (extras, ghost/link), then the controls with the most hand-wired descendant and has logic: the input group, combobox and select.
    • Toggle looks (toggle_off/toggle_on on ButtonStyle) become TogglePart from shadcn's toggle.tsx (one source per widget), keyed by Aria::Pressed.
    • Disabled::{Colors, Faded} stays as it is. It's how a widget paints the disabled state, not a class. shadcn's disabled:opacity-50 maps onto Faded(0.5) through Aria::Disabled.

    8. How the importer emits a Sheet

    • cargo xtask shadcn-import --write generates crates/eggshell-ui-shadcn/src/sheets/{vega,lyra}.rs, which are checked in. --check, run in CI, fails if they are stale against the pinned ref.
    • Per widget, a mapping table names the source and the parts: button.tsx → ButtonPart, cn-button → Root, cn-button-variant-* → Key::Variant, cn-button-size-* → Key::Size. That's the "one shadcn source per widget" record Preset: Button matches current shadcn (generated by shadcn-import) #433 asked for.
    • Per class, one of these mapping kinds, recorded in the report:
      • a Tw call;
      • a token (bg-primary → k.primary);
      • a key (aria-invalid:);
      • the dark half (dark:);
      • a rule ([&_svg], *:, has-);
      • a draw-time variant (hover:);
      • a constant expression evaluated at import (rounded-[min(var(--radius-md),8px)] → 8);
      • unmapped.
    • Unmapped classes are written into the generated file as comments with their source line (// unmapped: transition-all (style-vega.css:6)), and listed in the report. A reviewer sees every gap in the diff.
    • Tokens: the generated function is fn vega(k: &Tokens) -> Sheet, one per theme half. Colours resolve when the preset is built, not per frame.
    • The preset's own adjustments (e.g. the darker scrim, since there's no backdrop blur) are Rust after the generated rules, in the preset layer. Their provenance points at that Rust line, so "shadcn's value" and "our deviation" are always distinguishable.

    9. Order of work, each a PR

    1. Core: Part, Key/When, Sheet with layers, replace, resolve and its memo; the two-part builder entry and the change to Rules::apply; debug origins with #[track_caller] in the method lists. No widget changes. Bench numbers for resolve and for a cold b.styled.
    2. Inspection: tracing, the Computed-style pane in the F12 overlay, Driver::why / Placed::why, and the console dump.
    3. Importer → Sheet and Button (Preset: Button matches current shadcn (generated by shadcn-import) #433): the generator, the Vega and Lyra button sheets, Button migrated, and ButtonStyle deleted. Goldens move once, with a before/after sheet by area.
    4. Widgets, one PR each, behaviour-preserving: Badge, input group, combobox, select, then the rest.

    Questions for the user

    # Question Recommendation
    Q1 dark: as a key, or generated into the dark half's sheet? The dark half. The theme pair already exists, and a sheet then never tests the theme per node.
    Q2 The Sheet as a field of core Style, or an extension? A field. Every widget reads it, and core's parts use it from day one.
    Q3 Ancestor rules between the sheet layers and the call site (a change to #456's apply), as the decided layer order says? Yes. It is CSS's result for shadcn's [&_svg] over an icon's default, and it keeps a caller's explicit class winning.
    Q4 Generated sheets checked in, with --check in CI, or generated at build time? Checked in. Reviewable diffs, no build-time dependency on the ref.
    Q5 The full override chain only for a traced (pinned) node, one frame late, with winners always kept in debug? Yes. It costs nothing for untraced nodes, and the pane shows the chain a frame after the click.
    Q6 Part variant names from Base UI's anatomy, with shadcn's data-slot as the slot string? Yes. It reads like Rust, and the importer matches on the string.
    Q7 Metrics a widget computes with: Keyed<Size, M> extensions beside the sheet? Yes, and only those. Anything painted or laid out is a class.
  8. samitbasu commented on Nov 20, 2026

    @samitbasu
    OwnerAuthor

    User answers on the Sheet note (2026-11-20). The note is approved with these answers:

    1. Q1: dark: classes are generated into the dark half's sheet; there's no per-node theme key.
    2. Q2: the Sheet is a field of core Style.
    3. Q3: ancestor rules sit between the sheet layers and the call site. That's a small change to Tw rule forms, PR 1: descendants and children rules, slot/attr/aria, important (#443) #456's apply; an explicit call-site class still wins.
    4. Q4: generated sheets are checked in, with shadcn-import --check in CI.
    5. Q5: winners are always recorded in debug builds, and the full override chain only for a traced (pinned) node, one frame late.
    6. Q6: part variants are named from Base UI's anatomy, with shadcn's data-slot as the slot string.
    7. Q7: typed metric structs (Keyed<Size, M>) only for numbers a widget computes with; everything painted or laid out is a class.

    Build order:

    1. PR 1, the Sheet core (sonnet-1);
    2. PR 2, inspection;
    3. PR 3, the importer emitting checked-in sheets plus Button (Preset: Button matches current shadcn (generated by shadcn-import) #433, wordy-guy);
    4. PR 4+, the other widgets per epic Epic: controls on the cascade + Sheet style system #446.
  9. samitbasu commented on Nov 20, 2026

    @samitbasu
    OwnerAuthor

    Addition to the Sheet core (user, 2026-11-20, from #433): When supports negated keys (not_aria, not_attr), plus Aria::HasPopup.

  10. samitbasu commented on Nov 21, 2026

    @samitbasu
    OwnerAuthor

    Follow-ups to #464, before widgets migrate (2026-11-20):

    1. The user decided b.part(part, keys, call_site) takes the caller's classes, so the call-site merge can't be forgotten. It replaces b.part(part, keys).merge(call_site).
    2. Sheet equality (found by wordy-guy in Preset: Button matches current shadcn (generated by shadcn-import) #433): version is a global counter, so two builds of the same style compare unequal once sheets have rules. That breaks install_in's no-op check, which then re-resolves every part every frame, and the Style equality tests. Resolve it per the user's Global style changes only through &mut LayoutState (unrepresentable mid-build) #435 decision (equality dropped; Arc::ptr_eq for change detection): Sheet equality is Arc::ptr_eq on the rules, and the memo stays keyed by version. Tests that compared whole styles compare behaviour instead. install_in is deleted in Global style changes only through &mut LayoutState (unrepresentable mid-build) #435 PR 4 anyway. No fingerprinting.
  11. added a commit that references this issue on Nov 21, 2026
  12. samitbasu commented on Nov 21, 2026

    @samitbasu
    OwnerAuthor

    User decisions on the Sheet's ergonomics (2026-11-20), before widgets migrate:

    1. Rule bodies receive the sheet's own tokens: Fn(Tw, &Tokens) -> Tw, as in |t, k| t.ring(2.0, k.primary). A theme colour needs no capture and always comes from the right half (light/dark). The generated sheets' let k = k.clone(); move |t| goes.
    2. Shorthand: sheet.rule(part, |t, k| ..) for unconditional rules and sheet.rule_when(part, when, |t, k| ..) for conditional ones, likewise replace/replace_when. When::always() stays only as a value.

    A small follow-up PR to #466 (sonnet-1), then #433's generator emits the new form.

  13. added 3 commits that reference this issue on Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions