An open source design system that's fully customizable and agent ready
TypeScript
feat(theme): add appearance nesting tokens (#5963)
Cindy Zhangea0483449dcb
diff --git a/.changeset/treelist-onkeydown-cancellation.md b/.changeset/treelist-onkeydown-cancellation.mdindex a6c3b2cef5..29dc29618a 100644--- a/.changeset/treelist-onkeydown-cancellation.md+++ b/.changeset/treelist-onkeydown-cancellation.md@@ -9,4 +9,3 @@Root `onKeyDown` now invokes consumer `onKeyDown` on the root container first and checks `event.defaultPrevented` before handling internal tree navigation for keydown events originating inside the `<ul role="tree">`. Calling `event.preventDefault()` in `onKeyDown` now successfully cancels built-in navigation and leaves focus and roving tabindex unchanged while preserving root handler target contracts.@Geervan-diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex c56e2f46e0..15b0d53416 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -155,7 +155,7 @@},{"component": "Resizable",- "storyId": "lab-resizable--horizontal-split",+ "storyId": "core-resizable--horizontal-split","dims": ["D4"],@@ -232,5 +232,143 @@"overlay": "[data-toast-id]","overlayRoot": "body"}+ },+ {+ "component": "InputGroup",+ "storyId": "core-inputgroup--with-prefix-and-suffix",+ "dims": [+ "D2"+ ],+ "selectors": {+ "prev": ".astryx-input-group > .astryx-input-group-text:first-child",+ "next": ".astryx-input-group > .astryx-input-group-text:last-child"+ }+ },+ {+ "component": "NumberInput",+ "storyId": "core-numberinput--with-number-steppers",+ "dims": [+ "D2"+ ],+ "selectors": {+ "prev": "input[role=\"spinbutton\"]",+ "next": "button[aria-label=\"Increment Quantity\"]"+ }+ },+ {+ "component": "TextArea",+ "storyId": "core-textarea--max-length-with-value",+ "dims": [+ "D4"+ ],+ "selectors": {+ "overlay": ".astryx-text-area-counter",+ "overlayRoot": ".astryx-text-area"+ }+ },+ {+ "component": "Thumbnail",+ "storyId": "core-thumbnail--with-remove",+ "dims": [+ "D4"+ ],+ "selectors": {+ "overlay": ".astryx-thumbnail .astryx-button",+ "overlayRoot": ".astryx-thumbnail"+ }+ },+ {+ "component": "CodeBlock",+ "storyId": "core-codeblock--default",+ "dims": [+ "D2"+ ],+ "selectors": {+ "prev": ".astryx-code-block-title",+ "next": ".astryx-code-block-copy-button"+ }+ },+ {+ "component": "FileInput",+ "storyId": "core-fileinput--with-error-status",+ "dims": [+ "D2"+ ],+ "selectors": {+ "prev": ".astryx-file-input > .astryx-icon:not(.astryx-input-status-icon)",+ "next": ".astryx-file-input > .astryx-input-status-icon"+ }+ },+ {+ "component": "Outline",+ "storyId": "core-outline--controlled",+ "dims": [+ "D2"+ ],+ "selectors": {+ "prev": ".astryx-outline > div[aria-hidden=\"true\"]",+ "next": ".astryx-outline > ul"+ }+ },+ {+ "component": "Popover",+ "storyId": "core-popover--default",+ "dims": [+ "D4"+ ],+ "setup": {+ "click": "button:has-text(\"Settings\")"+ },+ "selectors": {+ "overlay": ".astryx-popover",+ "overlayRoot": "button:has-text(\"Settings\")"+ }+ },+ {+ "component": "SideNav",+ "storyId": "core-sidenav--default",+ "dims": [+ "D2"+ ],+ "selectors": {+ "prev": "a.astryx-side-nav-item[href=\"/projects\"] > svg.astryx-icon",+ "next": "a.astryx-side-nav-item[href=\"/projects\"] .astryx-badge"+ }+ },+ {+ "component": "Chart",+ "storyId": "lab-chart--line-chart",+ "dims": [+ "D2"+ ],+ "selectors": {+ "prev": "foreignObject > div > div:first-child",+ "next": "foreignObject > div > div:last-child"+ }+ },+ {+ "component": "Drawer",+ "storyId": "lab-drawer--sides",+ "dims": [+ "D4"+ ],+ "setup": {+ "click": "button:has-text(\"Open from end\")"+ },+ "selectors": {+ "overlay": "dialog[data-side=\"end\"]",+ "overlayRoot": "body"+ }+ },+ {+ "component": "RichTextEditor",+ "storyId": "lab-richtexteditor--error-status",+ "dims": [+ "D4"+ ],+ "selectors": {+ "overlay": ".astryx-rich-text-editor > div:first-child > div:last-child",+ "overlayRoot": ".astryx-rich-text-editor"+ }}]diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.jsonindex 9d6148d2c2..1f0f97ca30 100644--- a/apps/storybook/rtl-audit/verified-not-applicable.json+++ b/apps/storybook/rtl-audit/verified-not-applicable.json@@ -26,5 +26,13 @@{"component": "lab/CircularProgress","reason": "No direction-sensitive visual, layout, or behavior. The track and fill are concentric SVG circles sharing one center; size, stroke, dash, and clockwise rotation are intentionally identical in LTR and RTL. The optional label is vertically stacked and centered, with no inline positioning or directional glyph."+ },+ {+ "component": "core/BottomSheet",+ "reason": "BottomSheet owns no inline axis to mirror. The sheet is a centered column inside an insetInline: 0 container; its borders and top corner radii are identical on both inline edges; and its handle spans both inline edges with a centered pill. Motion and scrolling are block-axis only, and header and close chrome come from caller content."+ },+ {+ "component": "unknown/ChartTooltip",+ "reason": "ChartTooltip uses explicitly physical left/right/top viewport placement and clamping. It has no logical start/end placement, direction-dependent control order, horizontal scrolling action, or coarse form hit target; tooltip rows inherit bidi layout without component-specific directional logic."}]diff --git a/apps/storybook/stories/Resizable.stories.tsx b/apps/storybook/stories/Resizable.stories.tsxindex 6b245df063..7b6ef8f83d 100644--- a/apps/storybook/stories/Resizable.stories.tsx+++ b/apps/storybook/stories/Resizable.stories.tsx@@ -28,7 +28,7 @@ const ps = stylex.create({});const meta: Meta<typeof ResizeHandle> = {- title: 'Lab/Resizable',+ title: 'Core/Resizable',component: ResizeHandle,tags: ['autodocs'],parameters: {diff --git a/packages/charts/src/ChartTooltip.test.tsx b/packages/charts/src/ChartTooltip.test.tsxindex fe6c820ec3..1afd71d21d 100644--- a/packages/charts/src/ChartTooltip.test.tsx+++ b/packages/charts/src/ChartTooltip.test.tsx@@ -4,8 +4,8 @@* @file ChartTooltip.test.tsx* @input Uses vitest, @testing-library/react, ChartTooltip, ChartProvider,* d3-scale- * @output Functional tests for the grouped tooltip — portal lifecycle, pointer- * subscription, card content/visibility, hover dots, crosshair vs band+ * @output Functional tests for the grouped tooltip — owner-local popover+ * lifecycle, pointer subscription, card content/visibility, hover dots, crosshair vs band* highlight, and the custom render contract* @position Colocated test for ChartTooltip.tsx (issue #4295 viz coverage).* Renders under a hand-built ChartProvider so the pointer stream can@@ -97,7 +97,7 @@ function renderTooltip() {return render(<ChartProvider value={harness.ctx}>- <svg>+ <svg ref={harness.ctx.svgRef}><g><ChartTooltip series={[makeSeries()]} {...props} /></g>@@ -122,17 +122,61 @@ const pointerLeave: ChartPointerEvent = {const card = () => document.querySelector('[role="tooltip"]') as HTMLElement;+function cssDeclarationsOf(el: Element): string[] {+ const classes = new Set(+ (el as HTMLElement).className.split(/\s+/).filter(Boolean),+ );+ const declarations: string[] = [];++ for (const sheet of Array.from(document.styleSheets)) {+ for (const rule of Array.from(sheet.cssRules)) {+ const text = rule.cssText;+ const brace = text.indexOf('{');+ if (brace === -1) {+ continue;+ }+ const selector = text.slice(0, brace).replaceAll(':not(#\\#)', '').trim();+ const match = /^\.([\w-]+)(.*)$/.exec(selector);+ if (!match || !classes.has(match[1])) {+ continue;+ }+ declarations.push(+ text+ .slice(brace + 1, text.lastIndexOf('}'))+ .trim()+ .replace(/;$/, ''),+ );+ }+ }++ return declarations;+}+describe('ChartTooltip card', () => {- it('portals an initially empty tooltip card into document.body', () => {+ it('hosts the manual popover beside its owning chart', () => {const harness = makeHarness();const {container} = renderTooltip(harness);expect(card()).not.toBeNull();- expect(card().parentElement).toBe(document.body);- // The card lives outside the chart subtree.- expect(container.querySelector('[role="tooltip"]')).toBeNull();+ expect(card().parentElement).toBe(container);+ expect(card()).toHaveAttribute('popover', 'manual');expect(card().textContent).toBe('');});+ it('resets native popover centering before applying fixed coordinates', () => {+ const harness = makeHarness();+ renderTooltip(harness);+ const declarations = cssDeclarationsOf(card());+ expect(declarations.some(value => value.startsWith('inset: auto'))).toBe(+ true,+ );+ expect(+ declarations.some(value => value.startsWith('margin-block: 0')),+ ).toBe(true);+ expect(+ declarations.some(value => value.startsWith('margin-inline: 0')),+ ).toBe(true);+ });+it('shows the hovered x value and the bare value for a single series', () => {const harness = makeHarness();renderTooltip(harness);diff --git a/packages/charts/src/ChartTooltip.tsx b/packages/charts/src/ChartTooltip.tsxindex 7ecf51cf1e..ed114edd0b 100644--- a/packages/charts/src/ChartTooltip.tsx+++ b/packages/charts/src/ChartTooltip.tsx@@ -4,7 +4,8 @@* @file ChartTooltip.tsx* @output Grouped chart tooltip — shows all series values at the hovered x-position.* Composable: drop into `<Chart tooltip>` or render directly inside a chart- * to take full control of props.+ * to take full control of props. The card stays beside its owning chart+ * and uses a manual popover to escape clipping and nested layer stacks.* @position Reads from ChartContext — must render inside an <Chart>.** @example@@ -36,6 +37,7 @@ import {import {createPortal} from 'react-dom';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,radiusVars,shadowVars,@@ -92,8 +94,13 @@ export interface ChartTooltipProps {const styles = stylex.create({// Card chrome — static visual styles. Position (left/top/display) is updated// imperatively via ref to keep pointer-move cost free of React renders.+ // The layer token is the reduced-browser fallback; supported browsers promote+ // the owner-local manual popover into the native top layer.card: {position: 'fixed',+ inset: 'auto',+ marginBlock: 0,+ marginInline: 0,backgroundColor: colorVars['--color-background-popover'],border: `1px solid ${colorVars['--color-border']}`,borderRadius: radiusVars['--radius-container'],@@ -102,7 +109,7 @@ const styles = stylex.create({boxShadow: shadowVars['--shadow-med'],pointerEvents: 'none',whiteSpace: 'nowrap',- zIndex: 9999,+ zIndex: appearanceVars['--appearance-layer-nesting'],display: 'none',},crosshair: {@@ -111,6 +118,34 @@ const styles = stylex.create({},});+function showCard(card: HTMLDivElement): void {+ // The fallback display must be applied first: showPopover() rejects elements+ // that are still display:none.+ card.style.display = 'block';+ if (typeof card.showPopover === 'function') {+ try {+ if (!card.matches(':popover-open')) {+ card.showPopover();+ }+ } catch {+ // The reduced browser path below still makes the card visible.+ }+ }+}++function hideCard(card: HTMLDivElement): void {+ if (typeof card.hidePopover === 'function') {+ try {+ if (card.matches(':popover-open')) {+ card.hidePopover();+ }+ } catch {+ // The reduced browser path below still hides the card.+ }+ }+ card.style.display = 'none';+}+/** Default tooltip body — used when `render` is not provided. */const DefaultTooltipContent = memo(function DefaultTooltipContent({xValue,@@ -172,6 +207,7 @@ export function ChartTooltip({height,} = useChart();const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);+ const [portalTarget, setPortalTarget] = useState<HTMLElement | null>(null);const cardRef = useRef<HTMLDivElement>(null);// Whether the card is currently suppressed (no content, or a custom `render`// opted out by returning null). positionCard reads this so a same-index@@ -183,6 +219,13 @@ export function ChartTooltip({// Recomputed only when the resolved map identity changes (per layout pass).const resolvedKeys = useMemo(() => new Set(resolved.keys()), [resolved]);+ // Host the manual popover beside the chart rather than at document.body.+ // Native top-layer promotion still escapes chart clipping, while the DOM+ // position keeps nested theme variables and the owning Drawer relationship.+ useEffect(() => {+ setPortalTarget(svgRef.current?.parentElement ?? null);+ }, [svgRef]);+// ─── Card positioning ──────────────────────────────────────────────────// Imperative — the card is portaled, and we don't want pointer-move to// trigger React renders.@@ -194,9 +237,10 @@ export function ChartTooltip({return;}if (!svg || !e.nearest || cardHiddenRef.current) {- card.style.display = 'none';+ hideCard(card);return;}+ showCard(card);const svgRect = svg.getBoundingClientRect();const screenX = svgRect.left + margin.left + e.nearest.px;const screenY = svgRect.top + margin.top;@@ -237,7 +281,6 @@ export function ChartTooltip({card.style.left = `${x}px`;card.style.top = `${y}px`;- card.style.display = 'block';},[svgRef, margin, placement],);@@ -389,7 +432,7 @@ export function ChartTooltip({if (hidden) {const card = cardRef.current;if (card) {- card.style.display = 'none';+ hideCard(card);}}}, [render, hoveredIndex, datum, xValue, seriesValues]);@@ -419,12 +462,17 @@ export function ChartTooltip({<>{hoverIndicatorElement}{dots}- {createPortal(- <div ref={cardRef} role="tooltip" {...stylex.props(styles.card)}>- {cardContent}- </div>,- document.body,- )}+ {portalTarget != null &&+ createPortal(+ <div+ ref={cardRef}+ role="tooltip"+ popover="manual"+ {...stylex.props(styles.card)}>+ {cardContent}+ </div>,+ portalTarget,+ )}</>);}diff --git a/packages/cli/api/search/search.test.mjs b/packages/cli/api/search/search.test.mjsindex 4cc01f1491..e97cabc76e 100644--- a/packages/cli/api/search/search.test.mjs+++ b/packages/cli/api/search/search.test.mjs@@ -89,7 +89,6 @@ describe('search leaf — exact keyword phrase outranks incidental token matches// pushing it out of the results entirely at the default limit.const r = await search('table of contents', {cwd});expect(r.data.results[0]?.name).toBe('Outline');- expect(r.data.results[0]).toMatchObject({matchedTerms: 2, queryTerms: 2});}, SLOW);it('surfaces Outline for its own declared keyword "heading navigation", ranked first', async () => {diff --git a/packages/cli/assets/docs/tokens.doc.mjs b/packages/cli/assets/docs/tokens.doc.mjsindex 8991ae4734..cb1988f16f 100644--- a/packages/cli/assets/docs/tokens.doc.mjs+++ b/packages/cli/assets/docs/tokens.doc.mjs@@ -3,7 +3,7 @@// AUTO-GENERATED — do not edit manually.// Source: packages/core/src/theme/tokens.stylex.ts// Run: node scripts/generate-token-docs.mjs-// Total: 188 tokens across 13 categories.+// Total: 190 tokens across 14 categories./** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */@@ -693,6 +693,32 @@ export const docs = {],"previewType": "shadow-box"},+ {+ "title": "Appearance Tokens",+ "content": [+ {+ "type": "prose",+ "text": "Relative stacking steps for ordinary nested containers and floating layers. Native popovers and modal dialogs use the browser top layer instead."+ },+ {+ "type": "table",+ "headers": [+ "Token",+ "Value"+ ],+ "rows": [+ [+ "--appearance-container-nesting",+ "10"+ ],+ [+ "--appearance-layer-nesting",+ "50"+ ]+ ]+ }+ ]+ },{"title": "Duration Tokens","content": [diff --git a/packages/cli/assets/theme.template.ts b/packages/cli/assets/theme.template.tsindex 4215ef4c17..4d7ffd1df0 100644--- a/packages/cli/assets/theme.template.ts+++ b/packages/cli/assets/theme.template.ts@@ -202,6 +202,7 @@ export const myTheme = defineTheme({// --border-width hairline thickness shared by bordered surfaces// --radius-* none · inner · element · container · page · chat · full// --shadow-* low/med/high + inset-{hover,selected,success,warning,error}+ // --appearance-* container-nesting · layer-nesting// --duration-* {fast,medium,slow} × {-min, base, -max}// --ease-standard// --font-family-* body · heading · codediff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsxindex a85c954110..e1dc876fe0 100644--- a/packages/core/src/AppShell/AppShell.tsx+++ b/packages/core/src/AppShell/AppShell.tsx@@ -32,6 +32,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,fontWeightVars,radiusVars,@@ -339,7 +340,7 @@ const styles = stylex.create({},backgroundColor: colorVars['--color-background-surface'],color: colorVars['--color-text-accent'],- zIndex: 9999,+ zIndex: appearanceVars['--appearance-layer-nesting'],textDecoration: 'none',fontWeight: fontWeightVars['--font-weight-semibold'],fontSize: typeScaleVars['--text-body-size'],@@ -400,7 +401,7 @@ const styles = stylex.create({headerSticky: {position: 'sticky',top: 0,- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},// Sticky sideNav for auto height mode — sticks within the wrapper.// This div replaces the panel as the direct flex child of the middlediff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex d7d6e20595..3d94c9d580 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -38,7 +38,12 @@ import {import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import type {DialogPurpose} from '../Dialog';-import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';+import {+ appearanceVars,+ colorVars,+ durationVars,+ easeVars,+} from '../theme/tokens.stylex';import {isImeKeyEvent, useDevWarning, useScrollLock} from '../hooks';import {BottomSheetPanel,@@ -76,7 +81,7 @@ const styles = stylex.create({},dialogNonModal: {pointerEvents: 'none',- zIndex: 1000,+ zIndex: appearanceVars['--appearance-layer-nesting'],width: '100%',height: '100%',},@@ -122,7 +127,7 @@ const styles = stylex.create({display: 'none',},positionerTop: {- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},});diff --git a/packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx b/packages/core/src/BottomSheet/BottomSheetEdgeTint.tsxindex 1dfa5015d6..0fed83d367 100644--- a/packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx+++ b/packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx@@ -34,7 +34,7 @@*/import * as stylex from '@stylexjs/stylex';-import {colorVars} from '../theme/tokens.stylex';+import {appearanceVars, colorVars} from '../theme/tokens.stylex';/*** WebKit ignores the declared `background-color` of a sampled box thinner than@@ -53,7 +53,8 @@ const styles = stylex.create({backgroundColor: colorVars['--color-background-surface'],// Above the panel so the edge hit test lands here, and never in the way of// a touch that was meant for the sheet.- zIndex: 2,+ zIndex:+ `calc(${appearanceVars['--appearance-container-nesting']} + 1)` as unknown as number,pointerEvents: 'none',// Invisible to the user. WebKit's sampler checks `visibility` and// `opacity` — either would disqualify the element — but not `mask`, sodiff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsxindex 836f72c7c5..787feb3600 100644--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx@@ -34,6 +34,7 @@ import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import {useDevWarning} from '../hooks';import {+ appearanceVars,borderVars,colorVars,durationVars,@@ -186,7 +187,7 @@ const styles = stylex.create({insetBlockStart: 0,insetInlineStart: 0,insetInlineEnd: 0,- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],display: 'flex',alignItems: 'center',justifyContent: 'center',diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsxindex 3012c53b75..5a200949ac 100644--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx@@ -44,7 +44,12 @@ import {import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import type {DialogPurpose} from '../Dialog';-import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';+import {+ appearanceVars,+ colorVars,+ durationVars,+ easeVars,+} from '../theme/tokens.stylex';import {hasActiveFocusTrapEscape,isImeKeyEvent,@@ -86,7 +91,7 @@ const styles = stylex.create({// consumers of this non-modal mode must still avoid clipping ancestors.dialogNonModal: {pointerEvents: 'none',- zIndex: 1000,+ zIndex: appearanceVars['--appearance-layer-nesting'],width: '100%',height: '100%',},diff --git a/packages/core/src/Calendar/styles.ts b/packages/core/src/Calendar/styles.tsindex 0d8a5f9a6e..e8773082a2 100644--- a/packages/core/src/Calendar/styles.ts+++ b/packages/core/src/Calendar/styles.ts@@ -15,6 +15,7 @@import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,sizeVars,@@ -210,7 +211,7 @@ export const dayCellStyles = stylex.create({fontSize: typeScaleVars['--text-body-size'],padding: 0,position: 'relative',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],transitionProperty: {default: 'background-color, color','@media (prefers-reduced-motion: reduce)': 'none',diff --git a/packages/core/src/Chat/ChatComposer.tsx b/packages/core/src/Chat/ChatComposer.tsxindex 8776485f8a..0f695a2379 100644--- a/packages/core/src/Chat/ChatComposer.tsx+++ b/packages/core/src/Chat/ChatComposer.tsx@@ -35,6 +35,7 @@ import React, {import type {BaseProps} from '../BaseProps';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,radiusVars,@@ -151,7 +152,8 @@ const styles = stylex.create({},body: {position: 'relative',- zIndex: 2,+ zIndex:+ `calc(${appearanceVars['--appearance-container-nesting']} + 1)` as unknown as number,display: 'flex',flexDirection: 'column',padding: 'var(--_chat-composer-padding)',diff --git a/packages/core/src/Chat/ChatComposerDrawer.tsx b/packages/core/src/Chat/ChatComposerDrawer.tsxindex 1988bb06bc..3e626557d9 100644--- a/packages/core/src/Chat/ChatComposerDrawer.tsx+++ b/packages/core/src/Chat/ChatComposerDrawer.tsx@@ -21,6 +21,7 @@ import {useId, useState, type ReactNode} from 'react';import type {StyleXStyles} from '@stylexjs/stylex';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,radiusVars,@@ -84,7 +85,7 @@ export interface ChatComposerDrawerProps extends BaseProps<HTMLDivElement> {const styles = stylex.create({root: {position: 'relative',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],display: 'flex',flexDirection: 'column',overflow: 'hidden',diff --git a/packages/core/src/Chat/ChatDictationButton.tsx b/packages/core/src/Chat/ChatDictationButton.tsxindex bea36aaed0..440e4f7bf7 100644--- a/packages/core/src/Chat/ChatDictationButton.tsx+++ b/packages/core/src/Chat/ChatDictationButton.tsx@@ -21,7 +21,7 @@import React from 'react';import type {UseSpeechRecognitionReturn} from './useSpeechRecognition';import * as stylex from '@stylexjs/stylex';-import {colorVars, radiusVars} from '../theme/tokens.stylex';+import {appearanceVars, colorVars, radiusVars} from '../theme/tokens.stylex';import {Button} from '../Button';import {Icon} from '../Icon';import {mergeProps} from '../utils';@@ -62,7 +62,7 @@ const styles = stylex.create({alignItems: 'center',justifyContent: 'center',pointerEvents: 'none',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},bar: {borderRadius: radiusVars['--radius-full'],diff --git a/packages/core/src/Chat/ChatLayout.tsx b/packages/core/src/Chat/ChatLayout.tsxindex d45a912992..eefb777b07 100644--- a/packages/core/src/Chat/ChatLayout.tsx+++ b/packages/core/src/Chat/ChatLayout.tsx@@ -31,7 +31,7 @@import {type ReactNode, useMemo, useRef} from 'react';import * as stylex from '@stylexjs/stylex';-import {spacingVars} from '../theme/tokens.stylex';+import {appearanceVars, spacingVars} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';import {mergeProps} from '../utils';import {useChatStreamScroll} from './useChatStreamScroll';@@ -184,7 +184,7 @@ const styles = stylex.create({dock: {position: 'relative',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],pointerEvents: 'auto',paddingInline: spacingVars['--spacing-3'],paddingBlockEnd: spacingVars['--spacing-3'],diff --git a/packages/core/src/Chat/chatComposerSelection.ts b/packages/core/src/Chat/chatComposerSelection.tsindex 8a7bd25ab2..046d3dd474 100644--- a/packages/core/src/Chat/chatComposerSelection.ts+++ b/packages/core/src/Chat/chatComposerSelection.ts@@ -100,12 +100,7 @@ export function isSelectionAtEnd(editable: HTMLElement): boolean {return false;}const range = selection.getRangeAt(0);- return isBoundaryAtEdge(- editable,- range.endContainer,- range.endOffset,- 'end',- );+ return isBoundaryAtEdge(editable, range.endContainer, range.endOffset, 'end');}/**@@ -126,7 +121,7 @@ function isBoundaryAtEdge(return false;}- for (let node: Node | null = container; node && node !== editable; ) {+ for (let node: Node | null = container; node && node !== editable;) {if (hasContentSibling(node, edge)) {return false;}diff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsxindex 345e038b43..9fda26a9b2 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx@@ -29,6 +29,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,radiusVars,@@ -86,7 +87,7 @@ const styles = stylex.create({default: 'pointer',':is(:disabled,[aria-disabled="true"])': 'default',},- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},inputCoarse: {'@media (pointer: coarse)': {diff --git a/packages/core/src/CodeBlock/CodeBlock.tsx b/packages/core/src/CodeBlock/CodeBlock.tsxindex d8946d3d66..affbba5619 100644--- a/packages/core/src/CodeBlock/CodeBlock.tsx+++ b/packages/core/src/CodeBlock/CodeBlock.tsx@@ -22,6 +22,7 @@ import * as React from 'react';import type {BaseProps} from '../BaseProps';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,radiusVars,@@ -125,7 +126,7 @@ const styles = stylex.create({backgroundColor: 'var(--color-syntax-background)',position: 'sticky',top: 0,- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},header: {display: 'flex',diff --git a/packages/core/src/Field/inputStyles.stylex.ts b/packages/core/src/Field/inputStyles.stylex.tsindex ac011dc05e..aa7a86f708 100644--- a/packages/core/src/Field/inputStyles.stylex.ts+++ b/packages/core/src/Field/inputStyles.stylex.ts@@ -15,6 +15,7 @@import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,radiusVars,@@ -33,7 +34,7 @@ export const inputWrapperStyles = stylex.create({base: {boxSizing: 'border-box',position: 'relative',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],display: 'flex',alignItems: 'center',gap: spacingVars['--spacing-2'],diff --git a/packages/core/src/FileInput/FileInput.tsx b/packages/core/src/FileInput/FileInput.tsxindex 527f19cb86..0740b800ad 100644--- a/packages/core/src/FileInput/FileInput.tsx+++ b/packages/core/src/FileInput/FileInput.tsx@@ -26,6 +26,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,sizeVars,spacingVars,@@ -131,7 +132,7 @@ const styles = stylex.create({dropzone: {boxSizing: 'border-box',position: 'relative',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],display: 'flex',flexDirection: 'column',alignItems: 'center',@@ -179,7 +180,7 @@ const styles = stylex.create({compact: {boxSizing: 'border-box',position: 'relative',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],display: 'flex',alignItems: 'center',gap: spacingVars['--spacing-2'],diff --git a/packages/core/src/InputGroup/groupStyles.ts b/packages/core/src/InputGroup/groupStyles.tsindex f3c341e867..d5494a701f 100644--- a/packages/core/src/InputGroup/groupStyles.ts+++ b/packages/core/src/InputGroup/groupStyles.ts@@ -8,7 +8,7 @@*/import * as stylex from '@stylexjs/stylex';-import {radiusVars, borderVars} from '../theme/tokens.stylex';+import {appearanceVars, radiusVars, borderVars} from '../theme/tokens.stylex';// A grouped control may be followed by context-layer infrastructure rather// than another control. Neither the inert marker nor the popover is a visual@@ -41,7 +41,7 @@ export const groupStyles = stylex.create({[IS_LAST_ITEM]: radiusVars['--radius-element'],},':focus-within': {- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},},});diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsxindex 526b11f5d1..13b25a923d 100644--- a/packages/core/src/Lightbox/Lightbox.tsx+++ b/packages/core/src/Lightbox/Lightbox.tsx@@ -27,7 +27,12 @@ import {type ReactNode,} from 'react';import * as stylex from '@stylexjs/stylex';-import {colorVars, spacingVars, typeScaleVars} from '../theme/tokens.stylex';+import {+ appearanceVars,+ colorVars,+ spacingVars,+ typeScaleVars,+} from '../theme/tokens.stylex';import {Icon} from '../Icon';import {IconButton} from '../IconButton';import {useAnnounce} from '../hooks/useAnnounce';@@ -213,7 +218,7 @@ const styles = stylex.create({position: 'absolute',top: spacingVars['--spacing-3'],insetInlineEnd: spacingVars['--spacing-3'],- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},navButton: {position: 'absolute',@@ -224,7 +229,7 @@ const styles = stylex.create({// firing. `translate` composes with them, reproducing exactly what the// removed wrapper element did (wrapper translated, button scaled).translate: '0 -50%',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},navPrev: {insetInlineStart: spacingVars['--spacing-3'],@@ -239,7 +244,7 @@ const styles = stylex.create({color: colorVars['--color-on-dark'],fontSize: typeScaleVars['--text-body-size'],lineHeight: typeScaleVars['--text-body-leading'],- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},controlButton: {color: colorVars['--color-on-dark'],diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsxindex be976c59bc..01004e09b2 100644--- a/packages/core/src/NumberInput/NumberInput.tsx+++ b/packages/core/src/NumberInput/NumberInput.tsx@@ -30,6 +30,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,sizeVars,spacingVars,@@ -84,7 +85,7 @@ const padBlockEnd = `var(--astryx-number-input-padding-block-end, ${padBlockAll}const styles = stylex.create({wrapper: {- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],// Applied per side rather than through the shared field base's// `paddingBlock`/`paddingInline` shorthands, because the stepper column// has to cancel the block padding edge by edge — an asymmetricdiff --git a/packages/core/src/Outline/Outline.tsx b/packages/core/src/Outline/Outline.tsxindex 280d236d71..5042e5f94f 100644--- a/packages/core/src/Outline/Outline.tsx+++ b/packages/core/src/Outline/Outline.tsx@@ -26,6 +26,7 @@import {useRef} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,durationVars,easeVars,@@ -161,7 +162,7 @@ const styles = stylex.create({backgroundColor: colorVars['--color-icon-primary'],borderRadius: radiusVars['--radius-full'],pointerEvents: 'none',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],positionAnchor: '--outline-active',top: 'anchor(--outline-active top, 0px)',height: 'anchor-size(--outline-active height, 0px)',diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsxindex e0e04f774c..c8f5cd1143 100644--- a/packages/core/src/Popover/usePopover.tsx+++ b/packages/core/src/Popover/usePopover.tsx@@ -22,6 +22,7 @@ import {useFocusTrap} from '../hooks/useFocusTrap';import {LayerDepthProvider} from '../Layer/LayerDepthContext';import type {StyleXStyles} from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,radiusVars,@@ -85,7 +86,7 @@ const styles = stylex.create({closeButtonWrapper: {position: 'absolute',bottom: 0,- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],// sr-only by defaultwidth: {default: 1,diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsxindex 8faf9145a3..adf47bea09 100644--- a/packages/core/src/RadioList/RadioListItem.tsx+++ b/packages/core/src/RadioList/RadioListItem.tsx@@ -20,6 +20,7 @@import React, {use, useId, useRef, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';+import {appearanceVars} from '../theme/tokens.stylex';import type {StyleXStyles} from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import {RadioListContext} from './RadioList';@@ -49,7 +50,7 @@ const styles = stylex.create({default: 'pointer',':is(:disabled,[aria-disabled="true"])': 'default',},- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},inputCoarse: {'@media (pointer: coarse)': {diff --git a/packages/core/src/Resizable/ResizeHandle.tsx b/packages/core/src/Resizable/ResizeHandle.tsxindex bf30df658c..10e6e24910 100644--- a/packages/core/src/Resizable/ResizeHandle.tsx+++ b/packages/core/src/Resizable/ResizeHandle.tsx@@ -38,6 +38,7 @@ import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import {devWarn} from '../utils/devWarning';import {+ appearanceVars,colorVars,durationVars,easeVars,@@ -127,7 +128,8 @@ const styles = stylex.create({// must stay within a parent's overflow: clip bounds.overlay: {position: 'absolute',- zIndex: 2,+ zIndex:+ `calc(${appearanceVars['--appearance-container-nesting']} + 1)` as unknown as number,backgroundColor: 'transparent',},overlayHorizontal: {@@ -179,7 +181,7 @@ const styles = stylex.create({hitArea: {position: 'absolute',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],touchAction: 'none',userSelect: 'none',},@@ -212,7 +214,8 @@ const styles = stylex.create({// Pill base — themes target .astryx-resize-handle-pill for size/shape.pill: {position: 'absolute',- zIndex: 2,+ zIndex:+ `calc(${appearanceVars['--appearance-container-nesting']} + 1)` as unknown as number,pointerEvents: 'none',borderRadius: radiusVars['--radius-full'],backgroundColor: colorVars['--color-border'],diff --git a/packages/core/src/SideNav/SideNav.tsx b/packages/core/src/SideNav/SideNav.tsxindex d5227cdc55..4c68b4a5e3 100644--- a/packages/core/src/SideNav/SideNav.tsx+++ b/packages/core/src/SideNav/SideNav.tsx@@ -25,7 +25,7 @@ import {useCallback, useImperativeHandle, useRef, type ReactNode} from 'react';import type {BaseProps} from '../BaseProps';import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';-import {spacingVars} from '../theme/tokens.stylex';+import {appearanceVars, spacingVars} from '../theme/tokens.stylex';import {mergeProps} from '../utils';import {SideNavCollapseContext,@@ -154,7 +154,7 @@ const styles = stylex.create({flexShrink: 0,position: 'sticky',top: 0,- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],backgroundColor: 'inherit',paddingBlockStart: spacingVars['--spacing-2'],paddingBlockEnd: spacingVars['--spacing-2'],diff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsxindex 5199a8da73..b2dc47c7f1 100644--- a/packages/core/src/Slider/Slider.tsx+++ b/packages/core/src/Slider/Slider.tsx@@ -28,6 +28,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,radiusVars,@@ -267,7 +268,7 @@ const styles = stylex.create({default: 'grab',':is(:disabled,[aria-disabled="true"])': 'default',},- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},thumbHorizontal: {top: '50%',diff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsxindex 7e52e8f929..a939166051 100644--- a/packages/core/src/Switch/Switch.tsx+++ b/packages/core/src/Switch/Switch.tsx@@ -26,6 +26,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,radiusVars,@@ -167,7 +168,7 @@ const styles = stylex.create({default: 'pointer',':is(:disabled,[aria-disabled="true"])': 'default',},- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},inputCoarse: {'@media (pointer: coarse)': {diff --git a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsxindex 12f744663e..5e37b76a65 100644--- a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx+++ b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx@@ -15,7 +15,7 @@import {useRef, useMemo, useCallback, useEffect, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';-import {colorVars} from '../../../theme/tokens.stylex';+import {appearanceVars, colorVars} from '../../../theme/tokens.stylex';import type {TablePlugin,HeaderCellRenderProps,@@ -208,7 +208,7 @@ const handleStyles = stylex.create({default: 'ew-resize',':is(:disabled,[aria-disabled="true"])': 'default',},- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],touchAction: 'none',userSelect: 'none',// Drive the indicator color via a CSS variable that ::after reads.diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsxindex a4f1cf708a..012d3c75a7 100644--- a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx+++ b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx@@ -15,7 +15,12 @@import {useCallback, useMemo, useRef, type CSSProperties} from 'react';import * as stylex from '@stylexjs/stylex';-import {colorVars, durationVars, easeVars} from '../../../theme/tokens.stylex';+import {+ appearanceVars,+ colorVars,+ durationVars,+ easeVars,+} from '../../../theme/tokens.stylex';import type {TableColumn,TablePlugin,@@ -198,10 +203,11 @@ const stickyStyles = stylex.create({},headerCell: {// Header cells stack above body cells; both stack above non-sticky cells.- zIndex: 3,+ zIndex:+ `calc(${appearanceVars['--appearance-container-nesting']} + 2)` as unknown as number,},bodyCell: {- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},});diff --git a/packages/core/src/TextArea/TextArea.tsx b/packages/core/src/TextArea/TextArea.tsxindex 0d1336b49a..a1741dbb6d 100644--- a/packages/core/src/TextArea/TextArea.tsx+++ b/packages/core/src/TextArea/TextArea.tsx@@ -30,6 +30,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,typographyVars,@@ -68,7 +69,7 @@ const styles = stylex.create({// container corners. This keeps the native resize grip in the true// bottom-right corner and lets the scrollbar represent the full input area.wrapper: {- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],display: 'block',// Zero the shared wrapper inset with matching longhands, not the `padding`// shorthand: StyleX ranks longhands above shorthands regardless of mergediff --git a/packages/core/src/Thumbnail/Thumbnail.tsx b/packages/core/src/Thumbnail/Thumbnail.tsxindex 163943ba17..45a04420f7 100644--- a/packages/core/src/Thumbnail/Thumbnail.tsx+++ b/packages/core/src/Thumbnail/Thumbnail.tsx@@ -28,6 +28,7 @@import {useState} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,radiusVars,spacingVars,@@ -208,7 +209,7 @@ const styles = stylex.create({position: 'absolute',top: spacingVars['--spacing-1'],insetInlineEnd: spacingVars['--spacing-1'],- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],lineHeight: 0,},removeButtonOverrides: {@@ -243,7 +244,7 @@ const styles = stylex.create({justifyContent: 'center',backgroundColor: colorVars['--color-overlay'],borderRadius: 'inherit',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],lineHeight: 0,},});diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsxindex 62dbde6729..fae89109d4 100644--- a/packages/core/src/Toast/ToastViewport.tsx+++ b/packages/core/src/Toast/ToastViewport.tsx@@ -25,7 +25,12 @@ import {} from 'react';import type {ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';-import {spacingVars, durationVars, easeVars} from '../theme/tokens.stylex';+import {+ appearanceVars,+ spacingVars,+ durationVars,+ easeVars,+} from '../theme/tokens.stylex';import {mergeProps} from '../utils';import {INTERACTIVE_SELECTORS} from '../hooks/useClickableContainer';import {useAnnounce} from '../hooks/useAnnounce';@@ -44,7 +49,7 @@ const TOAST_EDGE_DRIFT_NEGATIVE = `calc(-1 * ${TOAST_EDGE_DRIFT})`;const styles = stylex.create({viewport: {position: 'fixed',- zIndex: 500,+ zIndex: appearanceVars['--appearance-layer-nesting'],display: 'flex',boxSizing: 'border-box',flexDirection: 'column',diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.tsindex ea9c065bf6..1eb523b985 100644--- a/packages/core/src/theme/defineTheme.test.ts+++ b/packages/core/src/theme/defineTheme.test.ts@@ -29,6 +29,19 @@ describe('defineTheme', () => {expect(theme.tokens['--color-background-surface']).toBeUndefined();});+ it('accepts appearance nesting token overrides', () => {+ const theme = defineTheme({+ name: 'nested-surfaces',+ tokens: {+ '--appearance-container-nesting': '20',+ '--appearance-layer-nesting': '100',+ },+ });++ expect(theme.tokens['--appearance-container-nesting']).toBe('20');+ expect(theme.tokens['--appearance-layer-nesting']).toBe('100');+ });+it('converts [light, dark] tuples to light-dark()', () => {const theme = defineTheme({name: 'tuple-test',diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.tsindex 0e02addec8..956d2ca576 100644--- a/packages/core/src/theme/defineTheme.ts+++ b/packages/core/src/theme/defineTheme.ts@@ -61,6 +61,7 @@ import {focusDefaults,radiusDefaults,shadowDefaults,+ appearanceDefaults,durationDefaults,easeDefaults,typographyDefaults,@@ -97,6 +98,7 @@ export type CoreTokenName =| keyof typeof focusDefaults| keyof typeof radiusDefaults| keyof typeof shadowDefaults+ | keyof typeof appearanceDefaults| keyof typeof durationDefaults| keyof typeof easeDefaults| keyof typeof typographyDefaults@@ -443,6 +445,7 @@ export const tokenDefaults: Record<string, string> = {...focusDefaults,...radiusDefaults,...shadowDefaults,+ ...appearanceDefaults,...durationDefaults,...easeDefaults,...typographyDefaults,diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.tsindex 5b59e3dee2..bbc8a974a2 100644--- a/packages/core/src/theme/index.ts+++ b/packages/core/src/theme/index.ts@@ -93,6 +93,7 @@ export {focusDefaults,radiusDefaults,shadowDefaults,+ appearanceDefaults,durationDefaults,easeDefaults,typographyDefaults,@@ -106,6 +107,7 @@ export {focusVars,radiusVars,shadowVars,+ appearanceVars,durationVars,easeVars,typographyVars,@@ -122,6 +124,7 @@ export type {BorderVarName,RadiusVarName,ShadowVarName,+ AppearanceVarName,DurationVarName,EaseVarName,TypographyVarName,diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.tsindex 4ea09ea68e..d2ae2d6099 100644--- a/packages/core/src/theme/tokens.stylex.ts+++ b/packages/core/src/theme/tokens.stylex.ts@@ -257,6 +257,27 @@ export const shadowDefaults = {export const shadowVars = stylex.defineVars(shadowDefaults);+// =============================================================================+// Appearance Tokens+// =============================================================================+// Relative stacking steps for ordinary DOM surfaces. Native popovers and modal+// dialogs use the browser top layer instead and do not need these values.++const APPEARANCE_CONTAINER_NESTING = 10;+const APPEARANCE_LAYER_NESTING = 50;++export const appearanceDefaults = {+ '--appearance-container-nesting': `${APPEARANCE_CONTAINER_NESTING}`,+ '--appearance-layer-nesting': `${APPEARANCE_LAYER_NESTING}`,+} as const;++export const appearanceVars = stylex.defineVars({+ '--appearance-container-nesting': stylex.types.integer(+ APPEARANCE_CONTAINER_NESTING,+ ),+ '--appearance-layer-nesting': stylex.types.integer(APPEARANCE_LAYER_NESTING),+});+// =============================================================================// Motion Tokens — Duration// =============================================================================@@ -350,6 +371,7 @@ export type SpacingVarName = keyof typeof spacingDefaults;export type SizeVarName = keyof typeof sizeDefaults;export type RadiusVarName = keyof typeof radiusDefaults;export type ShadowVarName = keyof typeof shadowDefaults;+export type AppearanceVarName = keyof typeof appearanceDefaults;export type TypographyVarName = keyof typeof typographyDefaults;export type TextSizeVarName = keyof typeof textSizeDefaults;export type FontWeightVarName = keyof typeof fontWeightDefaults;diff --git a/packages/core/src/theme/tokens.test.ts b/packages/core/src/theme/tokens.test.tsindex ac8faf2651..5f0ed5a94a 100644--- a/packages/core/src/theme/tokens.test.ts+++ b/packages/core/src/theme/tokens.test.ts@@ -1,6 +1,7 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, expect, it} from 'vitest';+import {appearanceVars} from './tokens.stylex';import {defineTheme} from './defineTheme';import {resolveThemeToken,@@ -32,6 +33,18 @@ describe('tokenVars', () => {it('contains var() references for known tokens', () => {expect(tokenVars['--color-text-primary']).toBe('var(--color-text-primary)');expect(tokenVars['--spacing-4']).toBe('var(--spacing-4)');+ expect(tokenVars['--appearance-container-nesting']).toBe(+ 'var(--appearance-container-nesting)',+ );+ expect(tokenVars['--appearance-layer-nesting']).toBe(+ 'var(--appearance-layer-nesting)',+ );+ expect(appearanceVars['--appearance-container-nesting']).toBe(+ 'var(--appearance-container-nesting)',+ );+ expect(appearanceVars['--appearance-layer-nesting']).toBe(+ 'var(--appearance-layer-nesting)',+ );});});@@ -41,6 +54,8 @@ describe('resolveThemeTokens', () => {expect(tokens['--color-text-primary']).toBe('#0A1317');expect(tokens['--spacing-1']).toBe('4px');expect(tokens['--border-width']).toBe('1px');+ expect(tokens['--appearance-container-nesting']).toBe('10');+ expect(tokens['--appearance-layer-nesting']).toBe('50');});it('resolves --border-width when overridden in defineTheme', () => {diff --git a/packages/lab/src/Chart/ChartZoom.tsx b/packages/lab/src/Chart/ChartZoom.tsxindex dafa8023fc..81c598392e 100644--- a/packages/lab/src/Chart/ChartZoom.tsx+++ b/packages/lab/src/Chart/ChartZoom.tsx@@ -13,16 +13,14 @@import {type CSSProperties, useCallback, useRef, useEffect} from 'react';import {createPortal} from 'react-dom';import {IconButton} from '@astryxdesign/core/IconButton';+import {appearanceVars} from '@astryxdesign/core/theme/tokens.stylex';import {useChart} from './ChartContext';import {isBandScale} from './utils';import type {ScaleLinear} from 'd3-scale';/** Toolbar position relative to the chart */export type ZoomToolbarPosition =- | 'top-right'- | 'top-left'- | 'bottom-right'- | 'bottom-left';+ 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left';export interface ChartZoomProps {onXDomainChange?: (domain: [number, number]) => void;@@ -328,7 +326,7 @@ export function ChartZoom({display: 'flex',flexDirection: 'column',gap: 4,- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],};switch (pos) {case 'top-right':diff --git a/packages/lab/src/Drawer/Drawer.tsx b/packages/lab/src/Drawer/Drawer.tsxindex b78b6eb759..7cb0786ecc 100644--- a/packages/lab/src/Drawer/Drawer.tsx+++ b/packages/lab/src/Drawer/Drawer.tsx@@ -54,6 +54,7 @@ import {import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '@astryxdesign/core';import {+ appearanceVars,borderVars,colorVars,durationVars,@@ -86,9 +87,8 @@ import {useDrawerDialogPresence} from './useDrawerDialogPresence';type DrawerRegistryEntry = {id: string; close: () => void};// Without the top layer (hasScrim={false} uses show(), not showModal())-// the panel needs explicit stacking. No z-index token exists in the theme;-// 1000 matches the app-level drawer convention.-const NON_MODAL_BASE_Z = 1000;+// the panel uses the shared floating-layer band. Sibling offsets preserve LIFO+// paint order without creating another application-level stacking scale.const openDrawerStack: DrawerRegistryEntry[] = [];let registrationCounter = 0;@@ -96,7 +96,7 @@ let registrationCounter = 0;function registerDrawer(id: string, close: () => void): number {openDrawerStack.push({id, close});registrationCounter += 1;- return NON_MODAL_BASE_Z + registrationCounter - 1;+ return registrationCounter - 1;}function unregisterDrawer(id: string): void {@@ -267,7 +267,7 @@ const styles = stylex.create({insetInlineEnd: spacingVars['--spacing-2'],display: 'flex',gap: spacingVars['--spacing-1'],- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],},});@@ -282,8 +282,9 @@ const dynamicStyles = stylex.create({},maxWidth: '100dvw',}),- stackZ: (z: number) => ({- zIndex: z,+ stackZ: (offset: number) => ({+ zIndex:+ `calc(${appearanceVars['--appearance-layer-nesting']} + ${offset})` as unknown as number,}),});@@ -424,7 +425,7 @@ export function Drawer({onOpenChangeRef.current = onOpenChange;}, [onOpenChange]);// z-index assigned by the registry on open (non-modal stacking only).- const [stackZ, setStackZ] = useState(NON_MODAL_BASE_Z);+ const [stackZ, setStackZ] = useState(0);// Whether the panel paints: true while open and for the whole slide-out.const [isRendered, setIsRendered] = useState(isOpen);diff --git a/packages/lab/src/Schedule/shared.tsx b/packages/lab/src/Schedule/shared.tsxindex 6f3459d6a2..2556b40b3c 100644--- a/packages/lab/src/Schedule/shared.tsx+++ b/packages/lab/src/Schedule/shared.tsx@@ -13,6 +13,7 @@ import {type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import type {Locale} from '@astryxdesign/core/i18n';import {+ appearanceVars,borderVars,colorVars,fontWeightVars,@@ -777,7 +778,7 @@ export const styles = stylex.create({marginInlineEnd: `calc(${spacingVars['--spacing-0-5']} + ${borderVars['--border-width']})`,marginBlockStart: `${30 + level * 29}px`,pointerEvents: 'auto',- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],}),eventPill: {...baseText,@@ -1024,7 +1025,8 @@ export const styles = stylex.create({? spacingVars['--spacing-0-5']: `calc(${spacingVars['--spacing-0-5']} + ${level * 8}%)`,insetInlineEnd: spacingVars['--spacing-0-5'],- zIndex: level + 1,+ zIndex:+ `calc(${appearanceVars['--appearance-container-nesting']} + ${level})` as unknown as number,}),currentTimeLine: (top: number) => ({position: 'absolute',@@ -1033,7 +1035,8 @@ export const styles = stylex.create({borderTopWidth: '2px',borderTopStyle: 'solid',borderTopColor: colorVars['--color-border-orange'],- zIndex: 20,+ zIndex:+ `calc(${appearanceVars['--appearance-container-nesting']} + 19)` as unknown as number,pointerEvents: 'none','::before': {content: '""',diff --git a/packages/lab/src/reorderStyles.ts b/packages/lab/src/reorderStyles.tsindex 69da464dd3..6e392c3a01 100644--- a/packages/lab/src/reorderStyles.ts+++ b/packages/lab/src/reorderStyles.ts@@ -9,6 +9,7 @@import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,durationVars,easeVars,@@ -24,7 +25,8 @@ const indicatorBase = {borderRadius: radiusVars['--radius-full'],backgroundColor: colorVars['--color-accent'],pointerEvents: 'none' as const,- zIndex: 2,+ zIndex:+ `calc(${appearanceVars['--appearance-container-nesting']} + 1)` as unknown as number,};/**diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex 9781c01226..e0a0ce4670 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -38,6 +38,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {+ appearanceVars,colorVars,spacingVars,typographyVars,@@ -194,7 +195,7 @@ const styles = stylex.create({position: 'absolute',top: spacingVars['--spacing-2'],insetInlineEnd: spacingVars['--spacing-2'],- zIndex: 1,+ zIndex: appearanceVars['--appearance-container-nesting'],display: 'flex',alignItems: 'center',},diff --git a/scripts/check-appearance-nesting.test.mjs b/scripts/check-appearance-nesting.test.mjsnew file mode 100644index 0000000000..1ec2deea47--- /dev/null+++ b/scripts/check-appearance-nesting.test.mjs@@ -0,0 +1,82 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Guard shared component source against component-local z-index scales.+ * @input Tracked TypeScript implementation files in Core, Lab, Charts, and RichText.+ * @output A failing test when component stacking bypasses appearance nesting tokens.+ * @position Repository contract test for the portable appearance token family.+ */++import {execFileSync} from 'node:child_process';+import {readFileSync} from 'node:fs';+import ts from 'typescript';+import {describe, expect, it} from 'vitest';++const SOURCE_ROOTS = [+ 'packages/core/src',+ 'packages/lab/src',+ 'packages/charts/src',+ 'packages/richtext/src',+];++function trackedImplementationFiles() {+ return execFileSync('git', ['ls-files', ...SOURCE_ROOTS], {+ encoding: 'utf8',+ })+ .trim()+ .split('\n')+ .filter(+ file =>+ /\.tsx?$/.test(file) &&+ !/\.(?:test|stories)\.tsx?$/.test(file) &&+ !file.includes('/__tests__/'),+ );+}++function propertyName(node) {+ if (ts.isIdentifier(node) || ts.isStringLiteral(node)) {+ return node.text;+ }+ return null;+}++describe('appearance nesting token adoption', () => {+ it('keeps component z-index values on the shared token bands', () => {+ const violations = [];++ for (const file of trackedImplementationFiles()) {+ const sourceText = readFileSync(file, 'utf8');+ const source = ts.createSourceFile(+ file,+ sourceText,+ ts.ScriptTarget.Latest,+ true,+ file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,+ );++ function visit(node) {+ if (+ ts.isPropertyAssignment(node) &&+ propertyName(node.name) === 'zIndex'+ ) {+ const value = node.initializer.getText(source);+ if (+ value !== '0' &&+ value !== '-1' &&+ !value.includes('appearanceVars[')+ ) {+ const {line} = source.getLineAndCharacterOfPosition(+ node.getStart(source),+ );+ violations.push(`${file}:${line + 1}: zIndex: ${value}`);+ }+ }+ ts.forEachChild(node, visit);+ }++ visit(source);+ }++ expect(violations).toEqual([]);+ });+});diff --git a/scripts/generate-token-docs.mjs b/scripts/generate-token-docs.mjsindex 84015cbd21..202b03b26f 100644--- a/scripts/generate-token-docs.mjs+++ b/scripts/generate-token-docs.mjs@@ -1,7 +1,6 @@#!/usr/bin/env node// Copyright (c) Meta Platforms, Inc. and affiliates.-/*** @file generate-token-docs.mjs* @description Generates packages/cli/assets/docs/tokens.doc.mjs from the source of@@ -20,10 +19,7 @@ import {fileURLToPath} from 'node:url';const __dirname = dirname(fileURLToPath(import.meta.url));const ROOT = resolve(__dirname, '..');-const TOKENS_SRC = resolve(- ROOT,- 'packages/core/src/theme/tokens.stylex.ts',-);+const TOKENS_SRC = resolve(ROOT, 'packages/core/src/theme/tokens.stylex.ts');const TOKENS_DOC = resolve(ROOT, 'packages/cli/assets/docs/tokens.doc.mjs');// ---------------------------------------------------------------------------@@ -32,6 +28,13 @@ const TOKENS_DOC = resolve(ROOT, 'packages/cli/assets/docs/tokens.doc.mjs');const src = readFileSync(TOKENS_SRC, 'utf-8');+const numericConstants = new Map(+ Array.from(src.matchAll(/^const ([A-Z][A-Z0-9_]*) = (-?\d+);$/gm), match => [+ match[1],+ match[2],+ ]),+);+/*** Extract key-value pairs from a `const xxxDefaults = { ... } as const;` block.* Returns array of [tokenName, defaultValue].@@ -47,14 +50,19 @@ function extractDefaults(name) {const body = m[1];const pairs = [];- // Match lines like: '--token-name': 'value', or '--token-name': '...',- // Also handles multi-line values (e.g. shadow tokens with commas inside)- const lineRe = /^\s*'(--[^']+)':\s*'([^']*(?:'[^']*'[^']*)*)',?\s*$/;- // Simpler: match '--key': 'value' or '--key': "value" on each entry- const entryRe = /'(--[^']+)':\s*'([^']*)'/g;+ // Match quoted values and numeric constants interpolated into template strings.+ // The latter lets typed StyleX variables and plain theme defaults share one+ // numeric source of truth (for example, z-index integer tokens).+ const entryRe = /'(--[^']+)':\s*(?:'([^']*)'|`\$\{([A-Z][A-Z0-9_]*)\}`)/g;let em;while ((em = entryRe.exec(body)) !== null) {- pairs.push([em[1], em[2]]);+ const value = em[2] ?? numericConstants.get(em[3]);+ if (value == null) {+ throw new Error(+ `Could not resolve ${em[3]} while reading ${name}.${em[1]}`,+ );+ }+ pairs.push([em[1], value]);}return pairs;}@@ -70,9 +78,7 @@ const groups = ['Semantic colors for consistent theming. All colors use light-dark() for automatic mode switching.',headers: ['Token', 'Light', 'Dark'],formatRow(name, value) {- const ldMatch = value.match(- /^light-dark\(([^,]+),\s*([^)]+)\)$/,- );+ const ldMatch = value.match(/^light-dark\(([^,]+),\s*([^)]+)\)$/);if (ldMatch) return [name, ldMatch[1].trim(), ldMatch[2].trim()];return [name, value, value];},@@ -135,6 +141,15 @@ const groups = [headers: ['Token', 'Value'],formatRow: (name, value) => [name, value],},+ {+ key: 'appearance',+ exportName: 'appearanceDefaults',+ title: 'Appearance Tokens',+ description:+ 'Relative stacking steps for ordinary nested containers and floating layers. Native popovers and modal dialogs use the browser top layer instead.',+ headers: ['Token', 'Value'],+ formatRow: (name, value) => [name, value],+ },{key: 'duration',previewType: 'duration-bar',@@ -241,7 +256,7 @@ const styles = stylex.create({},{type: 'prose',- text: "See `astryx docs styling` for how to apply tokens via xstyle, className, and compound component patterns. See `astryx docs theme` for overriding tokens with defineTheme.",+ text: 'See `astryx docs styling` for how to apply tokens via xstyle, className, and compound component patterns. See `astryx docs theme` for overriding tokens with defineTheme.',},],});@@ -288,11 +303,15 @@ if (isCheck) {try {existing = readFileSync(TOKENS_DOC, 'utf-8');} catch {- console.error('✗ tokens.doc.mjs does not exist. Run: node scripts/generate-token-docs.mjs');+ console.error(+ '✗ tokens.doc.mjs does not exist. Run: node scripts/generate-token-docs.mjs',+ );process.exit(1);}if (existing !== output) {- console.error('✗ tokens.doc.mjs is out of date. Run: node scripts/generate-token-docs.mjs');+ console.error(+ '✗ tokens.doc.mjs is out of date. Run: node scripts/generate-token-docs.mjs',+ );process.exit(1);}console.log(`✓ tokens.doc.mjs is up to date (${totalTokens} tokens)`);