Skip to content

feat(theme): ordered environmental adaptations in defineTheme - #5543

Merged
imdreamrunner merged 1 commit into
mainfrom
feat/theme-tiers
Sep 9, 2026
Merged

imdreamrunner merged 1 commit into
mainfrom
feat/theme-tiers

Conversation

@imdreamrunner

@imdreamrunner imdreamrunner commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Why

Themes need opt-in adaptations for environmental conditions without swapping themes, handwritten media-query CSS, or React styling state.

This replaces the superseded mobile / tablet / desktop / wide API previously prototyped in this PR with the accepted contract from #5806.

API

defineTheme({
  name: 'acme',
  adaptations: {
    widthBreakpoints: {
      sm: 640,
      md: 768,
      lg: 1024,
      xl: 1280,
      '2xl': 1536,
    },
    rules: [
      {
        when: {
          width: {from: 'lg', below: 'xl'},
          pointer: 'coarse',
          contrast: 'more',
        },
        value: {
          components: {/* overrides */},
        },
      },
    ],
  },
});

Semantics

  • Width points are fixed named tier starts; from is inclusive and below is exclusive.
  • width, pointer, contrast, and motion fields in one when are ANDed.
  • Rules cascade in authored order. Later matching writes win, including a deliberate write back to the root value.
  • Media-surface overrides (onDark / onLight) remain more specific and emit after adaptations.
  • A breakpoint map without value rules emits no media-query CSS.
  • Child themes inherit breakpoint overrides and ordered rules, append their own rules, and re-resolve inherited values against the child root metadata.
  • Adaptation localTokens may replace only exact names already enrolled by the root lineage.
  • Custom component visual-prop values must be introduced on the root theme before a rule styles them.

Implementation

  • One shared value resolver serves root themes and adaptation rule values.
  • Runtime injection and astryx theme build use the same ordered CSS generator.
  • Built modules retain normalized breakpoint/rule data, generative axes, and local-token lineage required for source-equivalent extends; resolved CSS layers stay in the stylesheet only.
  • AppShell.mobileNav.breakpoint now accepts sm | md | lg | xl | 2xl | none, reads the nearest active Theme, and switches to the wider layout at equality.
  • Theme docs, template guidance, architecture records, and the breaking changeset now describe the accepted API.

Validation

  • pnpm build
  • pnpm lint:strict
  • pnpm -F @astryxdesign/core typecheck
  • pnpm -F @astryxdesign/cli typecheck:strict
  • Core, Lab, CLI, docs, template, and knowledge checks
  • 3,129 CLI node tests passed in the isolated node-project run
  • 1,181 focused theme/AppShell/layout tests passed after review fixes
  • Four independent review passes; final pass returned no actionable issues
  • Storybook production build
  • Real Chromium: exclusive width edge, pointer-only and combined conditions, reduced motion, nested theme scopes, and CSS present at first paint

Status: Draft. Keep this PR in draft until the implementation and accepted specification are reviewed together.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 26, 2026
@vercel

vercel Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
astryx Ready Ready Preview Sep 9, 2026 12:58am UTC

Request Review

@github-actions

github-actions Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

Modified Components

AppShell (@astryxdesign/core) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 578 -
Complexity N/A Very High (101) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/core N/A 4.8KB 1.2KB

Accessibility Audit

Status: No accessibility violations detected.

Visual Regression

Status: Skipped — Broad stable scope is deferred to the daily release gate. It covers 380 trusted baseline shots instead of recapturing them for this PR. View the report


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

@github-actions github-actions Bot removed the needs:design-review Affects visuals — Design should review label Aug 26, 2026
github-actions Bot added a commit that referenced this pull request Aug 26, 2026

@cixzhang cixzhang left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — runtime/build parity and the boundary CSS are carefully covered.

One correctness issue still blocks: an unchanged child theme loses inherited explicit overrides inside a tier. At 600px, Chromium changed the inherited accent from red to blue and dropped the heading override. Could you preserve the effective inherited token/component overrides and add that child-theme regression?

[Reviewed by Robohands]

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — the inherited-override fix is right, and deriving it from the axes rather than carrying declarations is the right call.

It doesn't merge, and so CI has run nothing on this head: no build, no tests, no lint. The light-dark() guard is the one conflict that isn't mechanical — #5566 moved it off the generated CSS, yours widened it to read the tier CSS, and merged it needs both the theme's own values and each tier layer's. Your test at build-theme.tiers.test.mjs:175 is the check.

The second is the shape you just fixed. Deriving pinned-ness from values can't see a pin equal to what the axis generates, so it loses inside a tier: '--font-size-base': '0.875rem' on a 14/1.2 scale emits 1rem in mobile; 2rem holds. themeTiers.ts:478 calls that harmless — true at the theme level, not in a tier.

Is there a cheap way to keep that case without the 10.5 KB?

Full review

[Reviewed by Robohands]

@xinzi-bot

Copy link
Copy Markdown

@cixzhang Thanks. I’ve addressed both review rounds and the two notes from the review wiki.

Tiers now preserve inherited token and component overrides, including explicit pins equal to their generated value. Those ambiguous pins use sparse path-only metadata; child themes can still replace inherited pins normally.

The light-dark() guard now covers root- and tier-owned values without counting global data-token defaults.

I also replaced the iOS zoom example with coarse-pointer control sizing, documented the uneven-scale effect of pinned tokens, and made the three unused exports internal.

Could you take another look?

@github-actions
github-actions Bot requested a review from cixzhang August 27, 2026 17:42
@xinzi-bot

Copy link
Copy Markdown

@cixzhang Thanks — I agree the implementation and the release contract need to match. Rather than add adaptation-only fail-closed behavior, I updated AST-012 on this PR to state the boundary precisely:

  • when tooling can resolve a finite built-in prop domain, a rule-only value absent from the root is rejected;
  • opaque alias-backed domains retain the existing root-theme validation boundary; passing validation does not make the axis extensible.

The reason is that fail-closed is a meaningful product limitation, not merely stricter validation. Today 41 of 234 visual-prop pairs are unenumerable, including valid built-ins such as avatar-group.size. Fail-closed would reject those valid values in adaptations unless authors add redundant root declarations.

We explored the clean shared fix in draft #6061. The current prototype adds about 1,100 lines and a roughly 24 MB TypeScript runtime dependency to resolve four finite named domains, and it still has correctness edge cases. This is effectively introducing a TypeScript-checker subsystem, not a small validator patch. Applying it only to adaptations would also make adaptation validation stricter than root-theme validation for the same value.

The co-matching token-cycle blocker remains fixed and covered. PR 5543 is now cleanly rebased onto current main, and the spec, architecture record, template guidance, and consumer docs all describe the alias boundary explicitly. Could we treat the alias-resolution limitation as non-blocking here and continue evaluating the shared root+adaptation solution separately in #6061?

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — the ordered cascade, extension metadata, build parity, and exact-head Chromium matrix hold.

Two failures still block:

Please resolve alias domains or reject unprovable rule-only values before output, and preserve old-Core builds or declare the required Core range with migration guidance.

[Reviewed by Robohands]

@xinzi-bot

Copy link
Copy Markdown

@cixzhang Thanks — the old-Core compatibility finding is real and separate from the alias discussion. I reproduced it with the packed CLI against Core 0.5.4: a non-adaptation theme failed because the CLI required generateAdaptationCSS unconditionally. The fix keeps baseline theme builds working against Core 0.5.4, but requires the new Core capability when the selected theme actually declares or inherits adaptations; unsupported adaptation builds fail atomically with ERR_CORE_INCOMPATIBLE rather than silently dropping rules.

On size:not-a-real-avatar-size: we are intentionally not resolving or rejecting that value in #5543. This is not a newly discovered or previously unstated omission. We explicitly called out this exact boundary in two earlier comments:

  1. The first blocker-resolution comment explains that an opaque alias such as AvatarSize cannot be enumerated by the existing validator, that the same invalid value is accepted at the root, and that adaptation-only validation would create inconsistent policies.
  2. The follow-up release-contract comment records the revised AST-012 contract, quantifies the fail-closed cost (41 of 234 visual-prop pairs are currently unenumerable, including valid built-ins), and links the shared resolver experiment in Validate theme visual props from generated Core contract #6061.

The reason remains concrete: for an opaque alias-backed domain, current tooling cannot distinguish invalid size:not-a-real-avatar-size from valid built-in size:lg. Failing closed in this PR rejects both; resolving it correctly requires the shared TypeScript-aware machinery explored in #6061 (about 1,100 lines and a ~24 MB runtime dependency in the current prototype, with remaining correctness edges). Applying that only to adaptations would also make adaptations stricter than root themes for the same value.

Accordingly, #5543 rejects rule-only values when the finite domain is resolvable and explicitly documents opaque alias-backed domains as the same known validation boundary shared with root themes. Passing validation does not make a closed axis extensible. We are treating this documented alias limitation as non-blocking here and keeping the proper root+adaptation resolver as separate work. If that release decision is not accepted, that is a spec/scope disagreement—not a newly uncovered correctness bug in this head.

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — the published-Core compatibility path now preserves non-adaptation builds and rejects unsupported adaptation themes before output.

Two compatibility failures remain:

Please preserve existing token inputs and either resolve alias-backed domains or reject unprovable rule-only values before output.

[Reviewed by Robohands]

@xinzi-bot

Copy link
Copy Markdown

Follow-up: I separated the two review questions.

The alias behavior itself is unchanged in #5543: opaque alias-backed domains retain the boundary proposed in #6139, while resolvable finite domains are rejected. I have not approved the spec PR; that decision remains with the spec owners.

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — legacy token inputs now hold, and compatibility, type generation, cascade, and the exact-head browser checks pass.

One blocker remains: alias-backed closed visual props still fail open. avatar-group size:not-a-real-avatar-size exits 0, emits unreachable CSS, and writes no type augmentation. Please reject rule-only values that tooling cannot prove belong to the closed component surface before output.

[Reviewed by Robohands]

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The revised spec in #6139 is now approved: adaptation component writes must reuse the exact shared root validation result, add only the no-conditional-enrollment check, and carry unresolved shared results unchanged. This PR is still based on the older #6139 head and must be restacked after that spec lands.

Please then demonstrate the implementation matches DEC-5 with focused fixtures for: a finite built-in absent from root; an authoritative open primitive absent from root; a root-enrolled custom value used by a rule; a rule-only custom value rejected; and the same unresolved shared result/diagnostic at root and in an adaptation. Keep the already-fixed old-Core and legacy-token compatibility regressions. After restacking, rerun exact-head full CI, pr-a11y, and Stable visual regression.

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — old-Core compatibility, legacy token inputs, generated types, cascade, exact-head Chromium, and required CI checks are clean.

One architecture block remains. The build still uses a docs-derived value index and adaptation-only validator. Root validation only checks component/axis names, so the paths happen to agree for today’s unresolved alias case but rules won’t inherit future root-validation improvements; the shipped docs also teach the superseded exception.

Please make root validation return one reusable target/axis/domain/extension result, consume it unchanged for rules, add only the conditional-enrollment check, and cover finite built-ins, open primitive values, root-enrolled custom values, rejected rule-only custom values, and identical unresolved results/diagnostics.

[Reviewed by Robohands]

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mouse users can still receive a touch-only Heading weight. A coarse-only weight:bold:800 followed by a fine-pointer level:2 rule emits font-weight:800 inside the fine block because the cumulative fallback carries every earlier rule without checking co-matchability. Please preserve earlier leaves only from rules that can match the later condition, add coarse/fine regression coverage, and provide the AST-012 real-Safari evidence for exclusive width edges and primary-pointer classification.

[Reviewed by Robohands]

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The feature's width and primary-pointer behavior is still unverified for Safari users. The coarse/fine Heading leak is fixed, and exact-head compatibility, generated types, template sync, CI, and Chromium checks pass. AST-012 requires real Safari—not Playwright WebKit—to prove exclusive width edges and primary-pointer classification. Please attach one Safari receipt covering 639/640 and coarse/fine results.

[Reviewed by Robohands]

Themes can opt into CSS-first token, theme-local token, and component changes for named viewport widths, primary-pointer precision, contrast preference, and motion preference. Conditions compose with AND, width lower bounds are inclusive, upper bounds are exclusive, and later matching rules win in declaration order.

This implements merged AST-012. Component writes reuse root target, axis, value-domain, and extension validation; adaptations add only the no-conditional-enrollment rule. Built-ins and shared unresolved results behave exactly as they do at the root, while custom values that require generated type augmentation must be enrolled on the effective root before a rule restyles them.

Theme extension preserves breakpoints, generative-axis metadata, local-token enrollment, and ordered rules. Runtime and static builds use the same CSS lowering. Media surfaces follow adaptations and write the same derived component leaves, so onDark/onLight retain precedence. Explicit Heading weight props remain overrides inside adaptation and media blocks.

Reachable co-matching token graphs are validated after ordered cascade, allowing later repairs while rejecting every final cycle. Sparse rules, malformed conditions, reserved local-token routing, and malformed adaptation metadata fail before output.

AppShell accepts all five named breakpoints plus none, resolves them through the nearest theme, uses exclusive upper boundaries, and keeps none non-mobile during SSR regardless of the mobile hint.

The CLI treats adaptation generation as a Core capability rather than an unconditional baseline export. Plain themes continue to build against Core 0.5.4; themes with valid or malformed adaptation intent fail atomically when unsupported. Runtime interception preserves selected-theme lineage and generative axes across source, package, CommonJS, ESM, factory, spread, and extension paths, and fails closed wherever adaptation intent cannot be observed.

Root and media token inputs retain their historical runtime acceptance. Strict token-shape validation applies only to the new adaptation-rule surface.

@imdreamrunner
@xinzi-bot

Copy link
Copy Markdown

Real Safari evidence for current head 5f40dabf26492f029cc7a0971b502b7b92dec2d9:

  • Platform: Mac Studio (Apple silicon), macOS 26.6.2 (25G83)
  • Browser: Safari 26.6.2 (21624.5.1.11.3), bundled safaridriver; capability reports browserName: Safari, safari:useSimulator: false
  • Queries tested: the exact syntax emitted by AST-012 — (width < 768px), (width >= 768px), (pointer: fine), and (pointer: coarse)
Safari CSS viewport (width < 768px) (width >= 768px)
767px true false
768px false true
769px false true

At all three widths, matchMedia() and independently applied CSS custom-property markers agreed. This verifies that below is exclusive at equality and from is inclusive.

On this Mac Studio, Safari classified the primary pointer as:

  • (pointer: fine): true
  • (pointer: coarse): false
  • (any-pointer: fine): true
  • (any-pointer: coarse): false
  • (hover: hover): true

The prior coarse/fine Heading leak is also fixed on this head: root/default weight guards are unconditional, while authored conditional weight overrides are replayed only under their own rule condition and in authored order. Focused regressions cover coarse→fine exclusivity, coarse plus a broader later rule, co-matching last-write-wins, root-customized fallback, and media-surface precedence.

The Safari session used a temporary localhost page and was closed after capture.

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — the coarse/fine Heading isolation now holds, and the exact-head Safari receipt covers exclusive width edges and primary-pointer classification.

[Reviewed by Robohands]

This branch was successfully deployed

1 active deployment
Preview — 5f40dabf Deployed Sep 9, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants