An open source design system that's fully customizable and agent ready
TypeScript
feat(lint): flag div/span wrappers that only style an Astryx component (#4758)
Cindy Zhang5c851ad1dc34
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex 9a99620973..9eb396b8c2 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -28,6 +28,18 @@ until they merge to `main`.the generated capability reference in`internal/stylex-capabilities/CAPABILITIES.md` (mirrored in the `STYLEX-CAPS`block of `CLAUDE.md`).+- **Style Astryx components directly — no styling-only wrappers.** Every+ component extends `BaseProps`, so it takes `xstyle`. A `<div>`/`<span>` added+ only to carry styles around a component is not a neutral extra node: it takes+ the component out of its parent's flex/grid child relationship, which is how+ the pagination carets lost their centering (#4752). Point at `xstyle` —+ `<Icon icon="chevronsLeft" xstyle={rtlStyles.mirror} />`, not+ `<span {...stylex.props(rtlStyles.mirror)}><Icon … /></span>`. A wrapper that+ does something the child cannot — establishes a flex/grid _container_, pads+ around the child's border box, carries semantics, behavior, or a `ref` — is+ fine. `@astryx/no-style-only-wrapper` catches the mechanical cases, but it+ runs as a warning while existing sites are migrated, so review still owns new+ ones.- **Semantic tokens only.** No hardcoded color, spacing, radius, or shadowvalues; components stay theme-agnostic.- **TypeScript strict**, functional components with `forwardRef`, exported propdiff --git a/.github/instructions/packages.instructions.md b/.github/instructions/packages.instructions.mdindex f06ebad2af..dc0acd0d37 100644--- a/.github/instructions/packages.instructions.md+++ b/.github/instructions/packages.instructions.md@@ -447,7 +447,19 @@ and the Design review section above), or to add `hidden: true` until it does.Flag an added wrapper when a lighter path exists:- _Styling:_ components extend `BaseProps` (they take `xstyle`), so apply styledirectly — `<Divider xstyle={hasOutline && styles.titleDivider} />` — instead- of wrapping the component in a styled `<div>`.+ of wrapping the component in a styled `<div>`. This is the shape that shipped+ the off-center pagination carets (#4752): the mirror span put an extra+ element between the button's flex centering and the `Icon`, and moving the+ same style onto `<Icon xstyle={rtlStyles.mirror} />` fixed it. `@astryx/no-style-only-wrapper`+ reports the mechanical cases (a `div`/`span` whose only attributes are+ styles, wrapping a single Astryx component); it is a warning while the+ existing sites are migrated, so treat a **new** one as a review finding+ rather than assuming lint blocks it. The wrapper is legitimate when it does+ something the child cannot: establishing a flex/grid **container** (moving+ `display: flex` onto the child would restyle the child's own content),+ padding around the child's border box, or carrying semantics/behavior+ (`role`, `aria-*`, a `ref`, an event handler). Say which one applies rather+ than deleting the node reflexively.- _Behavior:_ reach for the behavior **hook** or **prop** the system alreadyexposes rather than a wrapper component. E.g. a tooltip is available via the`tooltip` prop / `useTooltip` hook, and there are hooks for many behaviorsdiff --git a/eslint.config.js b/eslint.config.jsindex 2ff50e4a76..ed3dcd0288 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -313,6 +313,9 @@ export default defineConfig("@typescript-eslint/no-non-null-assertion": "off","@typescript-eslint/consistent-type-assertions": "off","react-compiler/react-compiler": "off",+ // Test harnesses wrap components in sized/positioned <div>s to set up a+ // scenario; that scaffolding is not shipped DOM.+ "@astryx/no-style-only-wrapper": "off",},},// Non-production code — allow console.log for demos, tools, and examplesdiff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.mdindex c3e31bfaa8..4511e2c366 100644--- a/internal/eslint-plugin-astryx/README.md+++ b/internal/eslint-plugin-astryx/README.md@@ -54,6 +54,50 @@ const styles = stylex.create({});```+### `@astryx/no-style-only-wrapper`++Flags a `<div>`/`<span>` that exists only to style a single Astryx component.+Every component extends `BaseProps`, so it takes `xstyle` — the wrapper adds a+DOM node that takes the component out of its parent's flex/grid child+relationship (this is what knocked the pagination carets off-center in #4752).++**Bad:**++```tsx+<span {...stylex.props(rtlStyles.mirror)}>+ <Icon icon="chevronsLeft" /> {/* ❌ wrapper exists only to carry a style */}+</span>+```++**Good:**++```tsx+<Icon icon="chevronsLeft" xstyle={rtlStyles.mirror} /> {/* ✅ */}+```++The rule only fires when dropping the wrapper preserves behavior, so it stays+quiet on wrappers that do real work:++| Wrapper | Reported? |+| --------------------------------------------------------------------- | --------- |+| Only style attributes (`stylex.props`, `className`) | ✅ yes |+| `role`, `aria-*`, `data-*`, `ref`, a handler, `{...rest}` | ❌ no |+| More than one child, or a non-Astryx / host child | ❌ no |+| Styles include `display`, flex/grid container props, `gap`, `padding` | ❌ no |+| Child renders no root element (`Tooltip`, providers) | ❌ no |++Style objects imported from another module are read from that module, so+`import {rtlStyles} from '../utils'` is classified as accurately as a local+`stylex.create()` (see `stylex-style-source.js`).++**Options:** `wrapperElements`, `componentSources`, `allowComponents`,+`allowFiles`.++**Suggestion (not auto-fix):** for the unambiguous shape — a lone+`{...stylex.props(…)}` over a child with no `xstyle` — the rule offers a+rewrite that moves the styles onto the child. Removing a node can shift layout,+so it is never applied by `--fix`.+### `@astryx/require-letter-spacing`Recommends adding `letterSpacing` when `fontSize` is defined (common design pattern for badges, labels).diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.jsindex e23d593b0f..689d9a9c6b 100644--- a/internal/eslint-plugin-astryx/index.js+++ b/internal/eslint-plugin-astryx/index.js@@ -9,6 +9,7 @@* - boolean-prop-naming: Enforces is/has prefix on boolean props in *Props interfaces* - docblock-example-format: Enforces @example blocks use ``` fenced code on a separate line* - no-raw-paragraph: Disallows components from rendering a <p> by default (render <div> so any content composes)+ * - no-style-only-wrapper: Disallows div/span wrappers that only style a single Astryx component (use xstyle)** Philosophy: Strict for agents (CI), lenient for humans (local dev)* - "strict" config: All rules as errors - use in CI/agent environments@@ -19,6 +20,7 @@ import booleanPropNamingRule from './boolean-prop-naming.js';import presentationalComponentRule from './presentational-component.js';import docblockExampleFormatRule from './docblock-example-format.js';import noStylexNullOverrideRule from './no-stylex-null-override.js';+import noStyleOnlyWrapperRule from './no-style-only-wrapper.js';import noReactIntrospectionRule from './no-react-introspection.js';import noClassnameClobberRule from './no-classname-clobber.js';import noHardcodedAnchorRule from './no-hardcoded-anchor.js';@@ -236,6 +238,7 @@ const plugin = {'presentational-component': presentationalComponentRule,'docblock-example-format': docblockExampleFormatRule,'no-stylex-null-override': noStylexNullOverrideRule,+ 'no-style-only-wrapper': noStyleOnlyWrapperRule,'no-react-introspection': noReactIntrospectionRule,'no-classname-clobber': noClassnameClobberRule,'no-hardcoded-anchor': noHardcodedAnchorRule,@@ -264,6 +267,12 @@ plugin.configs.strict = {'@astryx/presentational-component': 'error','@astryx/docblock-example-format': 'error','@astryx/no-stylex-null-override': 'error',+ // Migration in progress: ~25 wrappers in packages/core predate this rule+ // (Carousel, Lightbox, MobileNav, Pagination, PowerSearch, Switch, TopNav,+ // Table/rowExpansion). Warn in both tiers until they move to xstyle, then+ // flip to 'error' here to prevent regressions — the same path+ // no-physical-properties took.+ '@astryx/no-style-only-wrapper': 'warn','@astryx/no-react-introspection': 'error','@astryx/no-classname-clobber': 'error','@astryx/no-hardcoded-anchor': 'error',@@ -291,6 +300,7 @@ plugin.configs.recommended = {'@astryx/presentational-component': 'error','@astryx/docblock-example-format': 'warn','@astryx/no-stylex-null-override': 'warn',+ '@astryx/no-style-only-wrapper': 'warn','@astryx/no-react-introspection': 'error','@astryx/no-classname-clobber': 'error','@astryx/no-hardcoded-anchor': 'warn',diff --git a/internal/eslint-plugin-astryx/no-style-only-wrapper.js b/internal/eslint-plugin-astryx/no-style-only-wrapper.jsnew file mode 100644index 0000000000..6d1b5c8a3e--- /dev/null+++ b/internal/eslint-plugin-astryx/no-style-only-wrapper.js@@ -0,0 +1,528 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-style-only-wrapper.js+ * @description Disallow a `<div>`/`<span>` that exists only to style a single+ * Astryx component — style the component directly via `xstyle`.+ *+ * Every public component extends `BaseProps`, so it takes `xstyle`+ * (`@astryx/require-base-props` enforces that). Wrapping one in a styled host+ * element to position or transform it adds a DOM node that is not part of the+ * component contract: it drops the component out of its parent's+ * flex/grid child relationship, can break centering and alignment, and gives+ * themes a node they cannot reach.+ *+ * Bad:+ * <span {...stylex.props(rtlStyles.mirror)}>+ * <Icon icon="chevronsLeft" />+ * </span>+ *+ * Good:+ * <Icon icon="chevronsLeft" xstyle={rtlStyles.mirror} />+ *+ * Scope — the rule only fires when removing the wrapper is a behavior-preserving+ * move, so it stays quiet on wrappers that are doing real work:+ * - the wrapper carries only style attributes (a `stylex.props()` spread,+ * `className`, `style`, and optionally `key`). Anything else — `ref`,+ * `role`, `aria-*`, `data-*`, an event handler, another spread — means the+ * element has a job beyond styling.+ * - it has exactly one child, a JSX element imported from Astryx.+ * - the styles it applies contain no *structural* property (`display`, the+ * flex/grid container properties, `gap`, `padding`). Those change the+ * child's own formatting context rather than just its box, so the wrapper+ * is not redundant. Style objects imported from another module are read+ * from that module (see `stylex-style-source.js`); on the rare style the+ * rule still cannot resolve it reports, since a wrapper carrying an opaque+ * style is exactly the shape that motivated this rule.+ *+ * Components that render no root element of their own (providers, overlays)+ * have nowhere to put `xstyle`; they are exempt via `allowComponents`.+ */++import {resolveImportedStyleProperties} from './stylex-style-source.js';++/**+ * Style properties whose effect depends on the wrapper existing as its own+ * box: they set up the formatting context *inside* the element (so moving them+ * onto the child would restyle the child's own content), or they add space+ * around the child's border box that child-side padding cannot reproduce.+ */+const STRUCTURAL_PROPERTIES = new Set([+ // Formatting context+ 'display',+ // Flex container+ 'flexDirection',+ 'flexWrap',+ 'flexFlow',+ 'justifyContent',+ 'justifyItems',+ 'alignItems',+ 'alignContent',+ 'placeItems',+ 'placeContent',+ // Grid container+ 'grid',+ 'gridTemplate',+ 'gridTemplateColumns',+ 'gridTemplateRows',+ 'gridTemplateAreas',+ 'gridAutoFlow',+ 'gridAutoColumns',+ 'gridAutoRows',+ // Multi-column+ 'columns',+ 'columnCount',+ // Gaps between children+ 'gap',+ 'rowGap',+ 'columnGap',+ // Space around the child's border box+ 'padding',+ 'paddingTop',+ 'paddingBottom',+ 'paddingLeft',+ 'paddingRight',+ 'paddingBlock',+ 'paddingBlockStart',+ 'paddingBlockEnd',+ 'paddingInline',+ 'paddingInlineStart',+ 'paddingInlineEnd',+]);++/**+ * Components with no root DOM element to receive `xstyle` — providers and+ * overlay/portal components. Mirrors the "no meaningful root DOM element"+ * entries in shared.js COMPONENT_RULE_ALLOWED.+ */+const DEFAULT_ALLOW_COMPONENTS = [+ 'Tooltip',+ 'Popover',+ 'HoverCard',+ 'Overlay',+ 'Toast',+ 'ToastViewport',+ 'LayerProvider',+ 'LinkProvider',+ 'MediaTheme',+ 'InternationalizationProvider',+ 'Portal',+ 'Slot',+];++/** Attributes that only carry styling, so a wrapper holding them is redundant. */+const STYLE_ATTRIBUTES = new Set(['className', 'style']);++/** `key` is bookkeeping, not a job — it moves to the child with the element. */+const NEUTRAL_ATTRIBUTES = new Set(['key']);++function isStylexPropsCall(node) {+ return (+ node?.type === 'CallExpression' &&+ node.callee?.type === 'MemberExpression' &&+ node.callee.object?.name === 'stylex' &&+ node.callee.property?.name === 'props'+ );+}++/** Root identifier of a JSX name: `Icon` → Icon, `Card.Body` → Card. */+function jsxNameRoot(nameNode) {+ let current = nameNode;+ while (current?.type === 'JSXMemberExpression') {+ current = current.object;+ }+ return current?.type === 'JSXIdentifier' ? current.name : null;+}++/** Full JSX name as written, for the report message. */+function jsxNameText(nameNode) {+ if (nameNode?.type === 'JSXIdentifier') {+ return nameNode.name;+ }+ if (nameNode?.type === 'JSXMemberExpression') {+ return `${jsxNameText(nameNode.object)}.${nameNode.property.name}`;+ }+ return 'component';+}++/** Children that render nothing: whitespace-only text and comment expressions. */+function isIgnorableChild(child) {+ if (child.type === 'JSXText') {+ return child.value.trim() === '';+ }+ if (child.type === 'JSXExpressionContainer') {+ return child.expression?.type === 'JSXEmptyExpression';+ }+ return false;+}++const rule = {+ meta: {+ type: 'suggestion',+ docs: {+ description:+ 'Disallow div/span wrappers that only style a single Astryx component — use the xstyle prop',+ category: 'Best Practices',+ recommended: true,+ },+ hasSuggestions: true,+ messages: {+ styleOnlyWrapper:+ '<{{wrapper}}> exists only to style <{{component}}>. Astryx components ' ++ 'extend BaseProps, so pass the styles to <{{component}}> via xstyle and ' ++ 'drop the wrapper — an extra DOM node changes the parent\'s flex/grid ' ++ 'child relationship and can break alignment.',+ moveToXstyle: 'Move the styles onto <{{component}}> via xstyle',+ },+ schema: [+ {+ type: 'object',+ properties: {+ wrapperElements: {+ type: 'array',+ items: {type: 'string'},+ description: 'Host elements treated as candidate wrappers.',+ },+ componentSources: {+ type: 'array',+ items: {type: 'string'},+ description:+ 'Regex patterns for import sources whose components take xstyle.',+ },+ allowComponents: {+ type: 'array',+ items: {type: 'string'},+ description:+ 'Components exempt from the rule (no root element for xstyle).',+ },+ allowFiles: {+ type: 'array',+ items: {type: 'string'},+ description:+ 'Substring match on the filename — grandfathers files that ' ++ 'predate the rule and still need migrating.',+ },+ },+ additionalProperties: false,+ },+ ],+ },++ create(context) {+ const options = context.options[0] ?? {};+ const allowFiles = options.allowFiles ?? [];+ const filename = context.filename ?? context.getFilename();+ if (allowFiles.some((pattern) => filename.includes(pattern))) {+ return {};+ }++ const wrapperElements = new Set(options.wrapperElements ?? ['div', 'span']);+ const componentSources = (+ options.componentSources ?? ['^@astryxdesign/', '^@xds/', '^\\.\\.?/']+ ).map((pattern) => new RegExp(pattern));+ const allowComponents = new Set(+ options.allowComponents ?? DEFAULT_ALLOW_COMPONENTS,+ );++ /** Local name → true when imported from a source that ships xstyle components. */+ const astryxImports = new Set();+ /** Local name of a `stylex.create()` result → its style-key → property names. */+ const stylexCreateProperties = new Map();+ /** Local name → the module it was imported from, for cross-file styles. */+ const importedBindings = new Map();+ /** JSX elements to check once the whole file (imports + styles) is known. */+ const candidates = [];++ function isAstryxComponent(nameNode) {+ const root = jsxNameRoot(nameNode);+ return root != null && astryxImports.has(root);+ }++ /**+ * Property names for `<binding>.<key>`, looking in this file first and+ * then in the module the binding was imported from.+ */+ function lookupStyleKey(binding, key) {+ if (key == null) {+ return null;+ }+ const local = stylexCreateProperties.get(binding);+ if (local != null) {+ return local.get(key) ?? null;+ }+ const imported = importedBindings.get(binding);+ if (imported == null) {+ return null;+ }+ return resolveImportedStyleProperties(+ context.filename ?? context.getFilename(),+ imported.source,+ imported.name,+ key,+ );+ }++ /**+ * Property names a style expression applies, or null when the expression+ * cannot be resolved to a `stylex.create()` entry — locally or in the+ * module it was imported from.+ */+ function resolveStyleProperties(expression) {+ // `styles.root`+ if (+ expression.type === 'MemberExpression' &&+ !expression.computed &&+ expression.object?.type === 'Identifier'+ ) {+ return lookupStyleKey(+ expression.object.name,+ expression.property.name ?? expression.property.value,+ );+ }+ // `styles.variant(size)` — a dynamic style function, same key lookup.+ if (+ expression.type === 'CallExpression' &&+ expression.callee?.type === 'MemberExpression' &&+ !expression.callee.computed &&+ expression.callee.object?.type === 'Identifier'+ ) {+ return lookupStyleKey(+ expression.callee.object.name,+ expression.callee.property.name ?? expression.callee.property.value,+ );+ }+ // `cond && styles.root` / `cond ? styles.a : styles.b` — union of branches.+ if (expression.type === 'LogicalExpression') {+ return resolveStyleProperties(expression.right);+ }+ if (expression.type === 'ConditionalExpression') {+ const consequent = resolveStyleProperties(expression.consequent);+ const alternate = resolveStyleProperties(expression.alternate);+ if (consequent == null || alternate == null) {+ return null;+ }+ return [...consequent, ...alternate];+ }+ if (expression.type === 'ArrayExpression') {+ const all = [];+ for (const element of expression.elements) {+ if (element == null) continue;+ const resolved = resolveStyleProperties(element);+ if (resolved == null) {+ return null;+ }+ all.push(...resolved);+ }+ return all;+ }+ return null;+ }++ function hasStructuralStyles(styleExpressions) {+ return styleExpressions.some((expression) => {+ const properties = resolveStyleProperties(expression);+ // Unresolvable styles (imported objects) are treated as non-structural:+ // the wrapper still looks purely decorative from here.+ if (properties == null) {+ return false;+ }+ return properties.some((name) => STRUCTURAL_PROPERTIES.has(name));+ });+ }++ return {+ ImportDeclaration(node) {+ const source = node.source.value;+ if (typeof source !== 'string') {+ return;+ }+ for (const specifier of node.specifiers) {+ const local = specifier.local?.name;+ if (!local) continue;+ if (specifier.type === 'ImportSpecifier') {+ importedBindings.set(local, {+ source,+ name: specifier.imported?.name ?? local,+ });+ } else if (specifier.type === 'ImportDefaultSpecifier') {+ importedBindings.set(local, {source, name: 'default'});+ }+ }+ if (!componentSources.some((pattern) => pattern.test(source))) {+ return;+ }+ for (const specifier of node.specifiers) {+ if (specifier.local?.name) {+ astryxImports.add(specifier.local.name);+ }+ }+ },++ // Record `const styles = stylex.create({key: {prop: ...}})` so the rule+ // can tell a decorative wrapper from a layout container.+ VariableDeclarator(node) {+ if (+ node.id?.type !== 'Identifier' ||+ node.init?.type !== 'CallExpression' ||+ node.init.callee?.type !== 'MemberExpression' ||+ node.init.callee.object?.name !== 'stylex' ||+ node.init.callee.property?.name !== 'create'+ ) {+ return;+ }+ const definition = node.init.arguments[0];+ if (definition?.type !== 'ObjectExpression') {+ return;+ }+ const byKey = new Map();+ for (const styleEntry of definition.properties) {+ if (styleEntry.type !== 'Property') continue;+ const key = styleEntry.key?.name ?? styleEntry.key?.value;+ if (key == null) continue;+ // A dynamic style is an arrow function returning the style object.+ let body = styleEntry.value;+ if (+ body?.type === 'ArrowFunctionExpression' &&+ body.body?.type === 'ObjectExpression'+ ) {+ body = body.body;+ }+ if (body?.type !== 'ObjectExpression') {+ byKey.set(key, []);+ continue;+ }+ byKey.set(+ key,+ body.properties+ .filter((property) => property.type === 'Property')+ .map((property) => property.key?.name ?? property.key?.value)+ .filter((name) => name != null),+ );+ }+ stylexCreateProperties.set(node.id.name, byKey);+ },++ // Collected, not checked inline: `stylex.create()` usually sits at the+ // bottom of a component file, so the style table is only complete once+ // the whole program has been walked.+ JSXElement(node) {+ candidates.push(node);+ },++ 'Program:exit'() {+ const sourceCode = context.sourceCode ?? context.getSourceCode();++ function checkElement(node) {+ const opening = node.openingElement;+ if (+ opening.name?.type !== 'JSXIdentifier' ||+ !wrapperElements.has(opening.name.name)+ ) {+ return;+ }++ // Every attribute must be styling or bookkeeping, and at least one+ // must actually carry style.+ const styleExpressions = [];+ let carriesStyle = false;+ for (const attribute of opening.attributes) {+ if (attribute.type === 'JSXSpreadAttribute') {+ if (!isStylexPropsCall(attribute.argument)) {+ return; // {...rest} — the wrapper forwards props, leave it alone.+ }+ carriesStyle = true;+ styleExpressions.push(...attribute.argument.arguments);+ continue;+ }+ const name = attribute.name?.name;+ if (typeof name !== 'string') {+ return;+ }+ if (STYLE_ATTRIBUTES.has(name)) {+ carriesStyle = true;+ continue;+ }+ if (!NEUTRAL_ATTRIBUTES.has(name)) {+ return; // ref, role, aria-*, onClick, … — the wrapper has a job.+ }+ }+ if (!carriesStyle) {+ return;+ }++ const children = node.children.filter(+ (child) => !isIgnorableChild(child),+ );+ if (children.length !== 1) {+ return;+ }+ const child = children[0];+ if (child.type !== 'JSXElement') {+ return;+ }++ const childName = child.openingElement.name;+ if (!isAstryxComponent(childName)) {+ return;+ }+ const componentName = jsxNameText(childName);+ if (allowComponents.has(jsxNameRoot(childName))) {+ return;+ }++ if (hasStructuralStyles(styleExpressions)) {+ return;+ }++ const data = {wrapper: opening.name.name, component: componentName};+ const report = {node, messageId: 'styleOnlyWrapper', data};++ // Offer a rewrite only for the unambiguous shape: a lone+ // `{...stylex.props(x)}` over a child with no xstyle of its own.+ const onlyStylexSpread =+ opening.attributes.length === 1 &&+ opening.attributes[0].type === 'JSXSpreadAttribute';+ const childHasXstyle = child.openingElement.attributes.some(+ (attribute) =>+ attribute.type === 'JSXSpreadAttribute' ||+ attribute.name?.name === 'xstyle',+ );+ if (onlyStylexSpread && !childHasXstyle && styleExpressions.length) {+ const styleText = styleExpressions+ .map((expression) => sourceCode.getText(expression))+ .join(', ');+ const xstyleValue =+ styleExpressions.length === 1+ ? `xstyle={${styleText}}`+ : `xstyle={[${styleText}]}`;+ report.suggest = [+ {+ messageId: 'moveToXstyle',+ data,+ fix(fixer) {+ const childText = sourceCode.getText(child);+ const insertAt = child.openingElement.name.range[1];+ const offset = insertAt - child.range[0];+ const rewritten =+ childText.slice(0, offset) ++ ` ${xstyleValue}` ++ childText.slice(offset);+ return fixer.replaceText(node, rewritten);+ },+ },+ ];+ }++ context.report(report);+ }++ // Walk every JSX element in the file.+ for (const node of candidates) {+ checkElement(node);+ }+ },+ };+ },+};++export default rule;diff --git a/internal/eslint-plugin-astryx/no-style-only-wrapper.test.mjs b/internal/eslint-plugin-astryx/no-style-only-wrapper.test.mjsnew file mode 100644index 0000000000..fa4a3d8780--- /dev/null+++ b/internal/eslint-plugin-astryx/no-style-only-wrapper.test.mjs@@ -0,0 +1,234 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file no-style-only-wrapper.test.mjs+ * @description Tests for the no-style-only-wrapper ESLint rule.+ */++import {RuleTester} from 'eslint';+import tseslint from 'typescript-eslint';+import noStyleOnlyWrapperRule from './no-style-only-wrapper.js';++const ruleTester = new RuleTester({+ languageOptions: {+ parser: tseslint.parser,+ parserOptions: {+ ecmaFeatures: {jsx: true},+ sourceType: 'module',+ },+ },+});++/** Preamble shared by most cases: an Astryx import plus a local style table. */+const setup = `+import * as stylex from '@stylexjs/stylex';+import {Icon} from '../Icon';+const styles = stylex.create({+ mirror: {transform: 'scaleX(-1)'},+ offset: {marginInlineStart: 4},+ row: {display: 'flex', alignItems: 'center'},+ padded: {padding: 8},+});+`;++// RuleTester registers its own describe/it blocks internally, so it+// must run at the top level. Vitest 4 forbids calling suite functions+// (describe/it) from inside another it() callback.+ruleTester.run('no-style-only-wrapper', noStyleOnlyWrapperRule, {+ valid: [+ // The component is styled directly — the shape the rule is steering toward.+ {code: `${setup} const a = <Icon icon="x" xstyle={styles.mirror} />;`},++ // No styles on the wrapper: it is grouping, not styling.+ {code: `${setup} const a = <span><Icon icon="x" /></span>;`},++ // More than one child — a real layout container.+ {+ code: `${setup} const a = <div {...stylex.props(styles.offset)}><Icon icon="a" /><Icon icon="b" /></div>;`,+ },++ // Text alongside the component.+ {+ code: `${setup} const a = <span {...stylex.props(styles.offset)}>label <Icon icon="x" /></span>;`,+ },++ // Structural styles: display/flex set up the child's formatting context,+ // so the wrapper is not redundant.+ {+ code: `${setup} const a = <div {...stylex.props(styles.row)}><Icon icon="x" /></div>;`,+ },+ // Padding around the child's border box cannot move onto the child.+ {+ code: `${setup} const a = <div {...stylex.props(styles.padded)}><Icon icon="x" /></div>;`,+ },+ // Structural style reached through a conditional still counts.+ {+ code: `${setup} const a = <div {...stylex.props(isWide && styles.row)}><Icon icon="x" /></div>;`,+ },++ // The wrapper does more than style: semantics, behavior, identity, refs.+ {+ code: `${setup} const a = <span aria-hidden="true" {...stylex.props(styles.mirror)}><Icon icon="x" /></span>;`,+ },+ {+ code: `${setup} const a = <div role="status" {...stylex.props(styles.mirror)}><Icon icon="x" /></div>;`,+ },+ {+ code: `${setup} const a = <div onClick={fn} {...stylex.props(styles.mirror)}><Icon icon="x" /></div>;`,+ },+ {+ code: `${setup} const a = <div ref={ref} {...stylex.props(styles.mirror)}><Icon icon="x" /></div>;`,+ },+ {+ code: `${setup} const a = <div data-testid="t" {...stylex.props(styles.mirror)}><Icon icon="x" /></div>;`,+ },+ // A forwarding wrapper — the spread may carry anything.+ {+ code: `${setup} const a = <div {...rest} {...stylex.props(styles.mirror)}><Icon icon="x" /></div>;`,+ },++ // Host-element children have no xstyle prop to move the styles to.+ {+ code: `${setup} const a = <span {...stylex.props(styles.mirror)}><svg /></span>;`,+ },+ // Neither do components from outside Astryx.+ {+ code: `import * as stylex from '@stylexjs/stylex';+import {Chart} from 'third-party';+const styles = stylex.create({offset: {marginTop: 4}});+const a = <div {...stylex.props(styles.offset)}><Chart /></div>;`,+ },+ // Components that render no root element (portals/providers) have nowhere+ // to put xstyle.+ {+ code: `import * as stylex from '@stylexjs/stylex';+import {Tooltip} from '../Tooltip';+const styles = stylex.create({offset: {marginTop: 4}});+const a = <div {...stylex.props(styles.offset)}><Tooltip label="x" /></div>;`,+ },++ // Only wrapper elements are candidates.+ {+ code: `${setup} const a = <section {...stylex.props(styles.mirror)}><Icon icon="x" /></section>;`,+ },++ // Expression children are not resolvable to a component.+ {+ code: `${setup} const a = <div {...stylex.props(styles.mirror)}>{icon}</div>;`,+ },+ // Nor are fragments.+ {+ code: `${setup} const a = <div {...stylex.props(styles.mirror)}><><Icon icon="x" /></></div>;`,+ },++ // Opting a component out via options.+ {+ code: `${setup} const a = <div {...stylex.props(styles.mirror)}><Icon icon="x" /></div>;`,+ options: [{allowComponents: ['Icon']}],+ },+ ],++ invalid: [+ // The motivating case: an RTL mirror on a display wrapper instead of the+ // Icon (facebook/astryx#4752).+ {+ code: `${setup} const a = <span {...stylex.props(styles.mirror)}><Icon icon="chevronsLeft" /></span>;`,+ errors: [+ {+ messageId: 'styleOnlyWrapper',+ data: {wrapper: 'span', component: 'Icon'},+ suggestions: [+ {+ messageId: 'moveToXstyle',+ output: `${setup} const a = <Icon xstyle={styles.mirror} icon="chevronsLeft" />;`,+ },+ ],+ },+ ],+ },++ // Several style arguments collapse into an xstyle array.+ {+ code: `${setup} const a = <div {...stylex.props(styles.offset, isSm && styles.mirror)}><Icon icon="x" /></div>;`,+ errors: [+ {+ messageId: 'styleOnlyWrapper',+ suggestions: [+ {+ messageId: 'moveToXstyle',+ output: `${setup} const a = <Icon xstyle={[styles.offset, isSm && styles.mirror]} icon="x" />;`,+ },+ ],+ },+ ],+ },++ // Styles the rule cannot resolve (imported style objects) still read as+ // decorative — this is the shape #4752 actually shipped.+ {+ code: `import * as stylex from '@stylexjs/stylex';+import {Icon} from '../Icon';+import {rtlStyles} from '../utils';+const a = <span {...stylex.props(rtlStyles.mirror)}><Icon icon="chevronsRight" /></span>;`,+ errors: [+ {+ messageId: 'styleOnlyWrapper',+ suggestions: [+ {+ messageId: 'moveToXstyle',+ output: `import * as stylex from '@stylexjs/stylex';+import {Icon} from '../Icon';+import {rtlStyles} from '../utils';+const a = <Icon xstyle={rtlStyles.mirror} icon="chevronsRight" />;`,+ },+ ],+ },+ ],+ },++ // className-only wrappers are the same anti-pattern.+ {+ code: `${setup} const a = <div className={cls}><Icon icon="x" /></div>;`,+ errors: [{messageId: 'styleOnlyWrapper', suggestions: []}],+ },++ // A key rides along with the element, so it does not excuse the wrapper —+ // but the rewrite is left to the author.+ {+ code: `${setup} const a = items.map((item) => (+ <span key={item.id} {...stylex.props(styles.offset)}><Icon icon={item.icon} /></span>+));`,+ errors: [{messageId: 'styleOnlyWrapper', suggestions: []}],+ },++ // Namespaced components resolve through their root import.+ {+ code: `import * as stylex from '@stylexjs/stylex';+import {Card} from '@astryxdesign/core';+const styles = stylex.create({offset: {marginTop: 4}});+const a = <div {...stylex.props(styles.offset)}><Card.Body /></div>;`,+ errors: [+ {+ messageId: 'styleOnlyWrapper',+ data: {wrapper: 'div', component: 'Card.Body'},+ suggestions: [+ {+ messageId: 'moveToXstyle',+ output: `import * as stylex from '@stylexjs/stylex';+import {Card} from '@astryxdesign/core';+const styles = stylex.create({offset: {marginTop: 4}});+const a = <Card.Body xstyle={styles.offset} />;`,+ },+ ],+ },+ ],+ },++ // A child that already has xstyle is still over-wrapped; merging the two+ // is the author's call, so no suggestion.+ {+ code: `${setup} const a = <div {...stylex.props(styles.offset)}><Icon icon="x" xstyle={styles.mirror} /></div>;`,+ errors: [{messageId: 'styleOnlyWrapper', suggestions: []}],+ },+ ],+});diff --git a/internal/eslint-plugin-astryx/stylex-style-source.js b/internal/eslint-plugin-astryx/stylex-style-source.jsnew file mode 100644index 0000000000..7b0cc4abd2--- /dev/null+++ b/internal/eslint-plugin-astryx/stylex-style-source.js@@ -0,0 +1,313 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file stylex-style-source.js+ * @description Reads the CSS property names behind a `stylex.create()` style+ * key, including when the style object lives in another module.+ *+ * Rules that reason about *what* a style does (rather than where it is used)+ * need the property names, and Astryx components routinely import their styles+ * from a shared module (`../utils` → `rtlStyles`, `./shared` → `styles`). ESLint+ * only ever hands a rule one file, so this module does the cross-file lookup+ * itself: a text scan for `const <name> = stylex.create({...})`, brace-balanced+ * so nested conditional values and dynamic (arrow-function) styles come out+ * right. Barrel re-exports (`export {rtlStyles} from './rtlStyles'`) are+ * followed.+ *+ * It is deliberately a scanner, not a parser: no second toolchain in the lint+ * path, and an unparseable file simply resolves to `null` (unknown), which+ * callers must handle.+ */++import {existsSync, readFileSync, statSync} from 'node:fs';+import {dirname, resolve} from 'node:path';++const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs'];+const MAX_REEXPORT_DEPTH = 4;++/** path → Map<exportName, Map<styleKey, string[]>> | null */+const moduleCache = new Map();++/**+ * Index of the character after the object literal that starts at `start`+ * (which must be the opening brace), skipping strings, template literals and+ * comments. Returns -1 when the braces never balance.+ */+function endOfObject(text, start) {+ let depth = 0;+ for (let i = start; i < text.length; i++) {+ const char = text[i];+ if (char === '/' && text[i + 1] === '/') {+ i = text.indexOf('\n', i);+ if (i === -1) return -1;+ continue;+ }+ if (char === '/' && text[i + 1] === '*') {+ i = text.indexOf('*/', i + 2);+ if (i === -1) return -1;+ i++;+ continue;+ }+ if (char === "'" || char === '"' || char === '`') {+ const quote = char;+ i++;+ while (i < text.length && text[i] !== quote) {+ if (text[i] === '\\') i++;+ i++;+ }+ continue;+ }+ if (char === '{') {+ depth++;+ } else if (char === '}') {+ depth--;+ if (depth === 0) {+ return i + 1;+ }+ }+ }+ return -1;+}++/**+ * Top-level `key: value` pairs of the object literal `text` (braces included),+ * as `[keyText, valueText]`. Spread elements are skipped.+ */+function topLevelEntries(text) {+ const entries = [];+ let depth = 0;+ let keyStart = -1;+ let key = null;+ let valueStart = -1;++ for (let i = 0; i < text.length; i++) {+ const char = text[i];++ if (char === '/' && text[i + 1] === '/') {+ i = text.indexOf('\n', i);+ if (i === -1) break;+ continue;+ }+ if (char === '/' && text[i + 1] === '*') {+ i = text.indexOf('*/', i + 2);+ if (i === -1) break;+ i++;+ continue;+ }+ if (char === "'" || char === '"' || char === '`') {+ const quote = char;+ const start = i;+ i++;+ while (i < text.length && text[i] !== quote) {+ if (text[i] === '\\') i++;+ i++;+ }+ if (depth === 1 && key === null && keyStart === -1) {+ keyStart = start;+ }+ continue;+ }++ if (char === '{' || char === '[' || char === '(') {+ depth++;+ if (depth === 1) {+ keyStart = -1;+ key = null;+ }+ continue;+ }+ if (char === '}' || char === ']' || char === ')') {+ if (depth === 1 && key !== null && valueStart !== -1) {+ entries.push([key, text.slice(valueStart, i).trim()]);+ key = null;+ valueStart = -1;+ }+ depth--;+ continue;+ }++ if (depth !== 1) {+ continue;+ }++ if (char === ':' && key === null && keyStart !== -1) {+ key = text+ .slice(keyStart, i)+ .trim()+ .replace(/^['"`]|['"`]$/g, '');+ valueStart = i + 1;+ keyStart = -1;+ continue;+ }+ if (char === ',' && key !== null) {+ entries.push([key, text.slice(valueStart, i).trim()]);+ key = null;+ valueStart = -1;+ keyStart = -1;+ continue;+ }+ if (key === null && keyStart === -1 && !/[\s,]/.test(char)) {+ keyStart = i;+ }+ }++ return entries;+}++/**+ * CSS property names a style-key object applies. Conditional groups keyed by a+ * pseudo-selector or at-rule (`:hover`, `@media …`) contribute the properties+ * nested inside them.+ */+function propertiesOf(objectText) {+ const properties = [];+ for (const [key, value] of topLevelEntries(objectText)) {+ if ((key.startsWith(':') || key.startsWith('@')) && value.startsWith('{')) {+ properties.push(...propertiesOf(value));+ continue;+ }+ properties.push(key);+ }+ return properties;+}++/** The object literal a style key maps to, unwrapping a dynamic style function. */+function styleObjectText(valueText) {+ if (valueText.startsWith('{')) {+ return valueText;+ }+ // Dynamic style: `(size) => ({...})`+ const arrow = valueText.indexOf('=>');+ if (arrow !== -1) {+ const body = valueText.slice(arrow + 2).trim();+ const inner = body.startsWith('(') ? body.slice(1).trim() : body;+ if (inner.startsWith('{')) {+ return inner;+ }+ }+ return null;+}++/**+ * Every `stylex.create()` binding in a source text.+ *+ * @param {string} text Module source.+ * @returns {Map<string, Map<string, string[]>>} binding name → style key → CSS+ * property names.+ */+export function extractStylexStyleProperties(text) {+ const byBinding = new Map();+ const declaration = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*stylex\s*\.\s*create\s*\(/g;+ let match;++ while ((match = declaration.exec(text)) !== null) {+ const braceStart = text.indexOf('{', declaration.lastIndex - 1);+ if (braceStart === -1) continue;+ const braceEnd = endOfObject(text, braceStart);+ if (braceEnd === -1) continue;++ const byKey = new Map();+ for (const [key, value] of topLevelEntries(text.slice(braceStart, braceEnd))) {+ const objectText = styleObjectText(value);+ byKey.set(key, objectText == null ? [] : propertiesOf(objectText));+ }+ byBinding.set(match[1], byKey);+ }++ return byBinding;+}++function resolveModulePath(fromFile, source) {+ const base = resolve(dirname(fromFile), source);+ for (const candidate of [+ base,+ ...EXTENSIONS.map((extension) => base + extension),+ ...EXTENSIONS.map((extension) => resolve(base, `index${extension}`)),+ ]) {+ if (existsSync(candidate) && statSync(candidate).isFile()) {+ return candidate;+ }+ }+ return null;+}++function readModule(path) {+ if (moduleCache.has(path)) {+ return moduleCache.get(path);+ }+ let text = null;+ try {+ text = readFileSync(path, 'utf-8');+ } catch {+ moduleCache.set(path, null);+ return null;+ }+ const result = {text, bindings: extractStylexStyleProperties(text)};+ moduleCache.set(path, result);+ return result;+}++/** `export {a, b as c} from './x'` → the source for a given exported name. */+function findReExportSource(text, exportedName) {+ const reExport = /export\s*{([^}]*)}\s*from\s*['"]([^'"]+)['"]/g;+ let match;+ while ((match = reExport.exec(text)) !== null) {+ for (const clause of match[1].split(',')) {+ const [original, alias] = clause.split(/\s+as\s+/).map((s) => s.trim());+ const exposed = alias ?? original;+ if (exposed === exportedName) {+ return {source: match[2], name: original};+ }+ }+ }+ return null;+}++/**+ * CSS property names for `<exportName>.<styleKey>` in the module `source`+ * resolves to, relative to `fromFile`.+ *+ * @returns {string[] | null} `null` when the module, the binding, or the key+ * cannot be resolved — the caller decides what an unknown style means.+ */+export function resolveImportedStyleProperties(+ fromFile,+ source,+ exportName,+ styleKey,+ depth = 0,+) {+ if (depth > MAX_REEXPORT_DEPTH || !source.startsWith('.') || !fromFile) {+ return null;+ }+ const path = resolveModulePath(fromFile, source);+ if (path == null) {+ return null;+ }+ const module = readModule(path);+ if (module == null) {+ return null;+ }++ const byKey = module.bindings.get(exportName);+ if (byKey != null) {+ return byKey.get(styleKey) ?? null;+ }++ const reExport = findReExportSource(module.text, exportName);+ if (reExport != null) {+ return resolveImportedStyleProperties(+ path,+ reExport.source,+ reExport.name,+ styleKey,+ depth + 1,+ );+ }+ return null;+}++/** Test seam: the module cache is process-wide and long-lived in an editor. */+export function clearStyleModuleCache() {+ moduleCache.clear();+}diff --git a/internal/eslint-plugin-astryx/stylex-style-source.test.mjs b/internal/eslint-plugin-astryx/stylex-style-source.test.mjsnew file mode 100644index 0000000000..b926e1afdd--- /dev/null+++ b/internal/eslint-plugin-astryx/stylex-style-source.test.mjs@@ -0,0 +1,180 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file stylex-style-source.test.mjs+ * @description Tests for the cross-file stylex style reader.+ */++import {mkdtempSync, mkdirSync, writeFileSync} from 'node:fs';+import {tmpdir} from 'node:os';+import {join} from 'node:path';+import {describe, expect, it, beforeEach} from 'vitest';+import {+ clearStyleModuleCache,+ extractStylexStyleProperties,+ resolveImportedStyleProperties,+} from './stylex-style-source.js';++beforeEach(() => {+ clearStyleModuleCache();+});++describe('extractStylexStyleProperties', () => {+ it('reads the property names of each style key', () => {+ const bindings = extractStylexStyleProperties(`+ const styles = stylex.create({+ root: {display: 'flex', gap: 4},+ offset: {marginTop: 8},+ });+ `);+ expect([...bindings.keys()]).toEqual(['styles']);+ expect(bindings.get('styles').get('root')).toEqual(['display', 'gap']);+ expect(bindings.get('styles').get('offset')).toEqual(['marginTop']);+ });++ it('keeps the outer property of a conditional value', () => {+ const bindings = extractStylexStyleProperties(`+ export const rtlStyles = stylex.create({+ mirror: {+ transform: {default: null, ':is([dir="rtl"] *)': 'scaleX(-1)'},+ },+ });+ `);+ expect(bindings.get('rtlStyles').get('mirror')).toEqual(['transform']);+ });++ it('descends into pseudo-selector and at-rule groups', () => {+ const bindings = extractStylexStyleProperties(`+ const styles = stylex.create({+ button: {+ color: 'red',+ ':hover': {display: 'none'},+ '@media (hover: hover)': {opacity: 1},+ },+ });+ `);+ expect(bindings.get('styles').get('button')).toEqual([+ 'color',+ 'display',+ 'opacity',+ ]);+ });++ it('unwraps dynamic styles', () => {+ const bindings = extractStylexStyleProperties(`+ const styles = stylex.create({+ span: (start, end) => ({+ gridColumnStart: start,+ gridColumnEnd: end,+ }),+ });+ `);+ expect(bindings.get('styles').get('span')).toEqual([+ 'gridColumnStart',+ 'gridColumnEnd',+ ]);+ });++ it('is not confused by braces inside strings and comments', () => {+ const bindings = extractStylexStyleProperties(`+ const styles = stylex.create({+ // a comment with a { brace+ quirk: {+ content: '"{"',+ /* block comment } */+ width: 10,+ },+ });+ `);+ expect(bindings.get('styles').get('quirk')).toEqual(['content', 'width']);+ });++ it('records every stylex.create binding in the module', () => {+ const bindings = extractStylexStyleProperties(`+ const a = stylex.create({x: {color: 'red'}});+ export const b = stylex.create({y: {margin: 0}});+ `);+ expect([...bindings.keys()]).toEqual(['a', 'b']);+ });++ it('returns nothing for a module with no styles', () => {+ expect(extractStylexStyleProperties('export const x = 1;').size).toBe(0);+ });+});++describe('resolveImportedStyleProperties', () => {+ /** Builds a throwaway module tree and returns its root directory. */+ function fixture(files) {+ const root = mkdtempSync(join(tmpdir(), 'astryx-style-source-'));+ for (const [name, content] of Object.entries(files)) {+ const path = join(root, name);+ mkdirSync(join(path, '..'), {recursive: true});+ writeFileSync(path, content, 'utf-8');+ }+ return root;+ }++ it('reads a style object out of a sibling module', () => {+ const root = fixture({+ 'Component.tsx': '',+ 'styles.ts': `export const shared = stylex.create({+ pill: {borderRadius: 8, padding: 4},+ });`,+ });+ expect(+ resolveImportedStyleProperties(+ join(root, 'Component.tsx'),+ './styles',+ 'shared',+ 'pill',+ ),+ ).toEqual(['borderRadius', 'padding']);+ });++ it('follows a barrel re-export, including a rename', () => {+ const root = fixture({+ 'Component.tsx': '',+ 'utils/index.ts': `export {rtlStyles} from './rtlStyles';+export {other as helpers} from './helpers';`,+ 'utils/rtlStyles.ts': `export const rtlStyles = stylex.create({+ mirror: {transform: 'scaleX(-1)'},+ });`,+ 'utils/helpers.ts': `export const other = stylex.create({+ pad: {padding: 2},+ });`,+ });+ expect(+ resolveImportedStyleProperties(+ join(root, 'Component.tsx'),+ './utils',+ 'rtlStyles',+ 'mirror',+ ),+ ).toEqual(['transform']);+ expect(+ resolveImportedStyleProperties(+ join(root, 'Component.tsx'),+ './utils',+ 'helpers',+ 'pad',+ ),+ ).toEqual(['padding']);+ });++ it('returns null for an unknown key, module, or bare specifier', () => {+ const root = fixture({+ 'Component.tsx': '',+ 'styles.ts': `export const shared = stylex.create({pill: {padding: 4}});`,+ });+ const from = join(root, 'Component.tsx');+ expect(+ resolveImportedStyleProperties(from, './styles', 'shared', 'missing'),+ ).toBeNull();+ expect(+ resolveImportedStyleProperties(from, './nope', 'shared', 'pill'),+ ).toBeNull();+ expect(+ resolveImportedStyleProperties(from, 'some-package', 'shared', 'pill'),+ ).toBeNull();+ });+});