An open source design system that's fully customizable and agent ready
TypeScript
fix(lint): catch unmirrored logical centering (#5864)
nynexman4464be67ed585a0e
diff --git a/eslint.config.js b/eslint.config.jsindex 00865b0c11..4c0523c99d 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -276,6 +276,22 @@ export default defineConfig('@astryx/no-hardcoded-i18n-string': isStrictMode ? 'error' : 'warn',},},+ // Temporary relationship-only exemption for the three known coarse-pointer+ // centering defects. Every other no-physical-properties check remains active.+ // Remove this block when #5170 lands.+ {+ files: [+ 'packages/core/src/CheckboxInput/CheckboxInput.tsx',+ 'packages/core/src/RadioList/RadioListItem.tsx',+ 'packages/core/src/Switch/Switch.tsx',+ ],+ rules: {+ '@astryx/no-physical-properties': [+ 'error',+ {allowLogicalCentering: true},+ ],+ },+ },// What a disabled control says to the pointer is a defect wherever it// ships, so these two rules reach past core: lab components are consumed// the same way, and lab is where the next core component comes from.diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.jsindex da46230d49..65bc7a6897 100644--- a/internal/eslint-plugin-astryx/index.js+++ b/internal/eslint-plugin-astryx/index.js@@ -13,6 +13,8 @@* - no-nullish-jsx-guard: Flags `!= null` JSX render guards for rendered values (use isRenderable so false/''/true slots don't leak an empty element)* - no-raw-intl-locale: Forbids raw Intl formatting/comparison outside the approved i18n infrastructure boundary, navigator.language(s) as a locale source, and date-helper calls without provider locale* - no-unguarded-ime-keydown: Flags an onKeyDown on an editable surface that branches on command keys without an IME composition guard (isImeKeyEvent/isComposing)+ * - no-physical-properties: Flags physical left/right CSS properties and unsafe logical-centering transform pairs+ * - prefer-center-inline: Nudges correct hand-rolled fixed centering toward rtlStyles.centerInline()* - no-classname-clobber: Flags two className sources on one JSX element — a literal className/style beside {...stylex.props()}, or two spreads that each carry a className (the later one silently wins)* - no-hover-on-disabled: Flags a :hover condition that can still match a disabled element (browsers suppress a disabled control's events, not its hover styling)* - require-table-section: Requires TableRow/tr to sit inside TableHeader/TableBody/TableFooter (a row directly inside a table emits <table><tr>, which browsers repair on parse and React does not)@@ -41,6 +43,7 @@ import noRawIntlLocaleRule from './no-raw-intl-locale.js';import noUnguardedImeKeydownRule from './no-unguarded-ime-keydown.js';import noBorderShorthandRule from './no-border-shorthand.js';import noPhysicalPropertiesRule from './no-physical-properties.js';+import preferCenterInlineRule from './prefer-center-inline.js';import focusOutlineKeyboardOnlyRule from './focus-outline-keyboard-only.js';import focusOutlineSharedRule from './focus-outline-shared.js';import noHoverOnDisabledRule from './no-hover-on-disabled.js';@@ -342,6 +345,7 @@ const plugin = {'no-unguarded-ime-keydown': noUnguardedImeKeydownRule,'no-border-shorthand': noBorderShorthandRule,'no-physical-properties': noPhysicalPropertiesRule,+ 'prefer-center-inline': preferCenterInlineRule,'focus-outline-keyboard-only': focusOutlineKeyboardOnlyRule,'focus-outline-shared': focusOutlineSharedRule,'no-hover-on-disabled': noHoverOnDisabledRule,@@ -403,6 +407,8 @@ plugin.configs.strict = {'@astryx/no-border-shorthand': 'error',// RTL physical→logical migration complete; errors to prevent regressions.'@astryx/no-physical-properties': 'error',+ // Correct hand-rolled fixed centering still duplicates shared geometry.+ '@astryx/prefer-center-inline': 'warn',// A focus outline drawn for pointer users is an accessibility defect, and// core is clean — error in both tiers so it stays that way.'@astryx/focus-outline-keyboard-only': 'error',@@ -478,6 +484,8 @@ plugin.configs.recommended = {'@astryx/no-border-shorthand': 'warn',// RTL physical→logical migration complete; errors to prevent regressions.'@astryx/no-physical-properties': 'error',+ // Correct hand-rolled fixed centering still duplicates shared geometry.+ '@astryx/prefer-center-inline': 'warn',// A focus outline drawn for pointer users is an accessibility defect, and// core is clean — error in both tiers so it stays that way.'@astryx/focus-outline-keyboard-only': 'error',diff --git a/internal/eslint-plugin-astryx/no-physical-properties.js b/internal/eslint-plugin-astryx/no-physical-properties.jsindex e138e98e0e..a6c4bcd04c 100644--- a/internal/eslint-plugin-astryx/no-physical-properties.js+++ b/internal/eslint-plugin-astryx/no-physical-properties.js@@ -7,13 +7,17 @@* under RTL; the CSS logical-property equivalents (inline-start/inline-end,* start/end) do, so they're required for correct right-to-left rendering.*- * Two kinds of violation are detected:+ * Three kinds of violation are detected:* 1. KEY-BASED — the object key is itself a banned physical property* (e.g. `marginLeft`, `borderRightColor`, `left`, `borderTopLeftRadius`).* The suggested fix renames the key to the logical equivalent.* 2. VALUE-BASED — the key is fine, but a specific physical VALUE is used* (e.g. `textAlign: 'left'`, `float: 'right'`, `clear: 'left'`). The* suggested fix replaces only the value; the key is left alone.+ * 3. RELATIONSHIP-BASED — a logical 50% inline anchor is paired with a+ * physical horizontal translate under the same conditions, but has no RTL+ * transform counterpart. Each declaration looks safe alone; together they+ * displace the element by its own width under RTL.** EXCEPTION — inline centering: `left: '50%'` paired with a `translate`/* `translateX` in the same style object is a deliberate, direction-symmetric@@ -87,7 +91,7 @@ const PHYSICAL_VALUE_MAP = {clear: { left: 'inline-start', right: 'inline-end' },};-function isInsideStylexCreate(node) {+export function isInsideStylexCreate(node) {let current = node;while (current) {if (@@ -111,6 +115,85 @@ function getStaticValue(node) {return null;}+function getStaticText(node) {+ const value = getStaticValue(node);+ if (value !== null) return value;+ if (node?.type === 'TemplateLiteral') {+ return node.quasis.map((quasi) => quasi.value.raw).join(' ');+ }+ return null;+}++function propertyName(property) {+ return property?.key?.name ?? property?.key?.value ?? null;+}++/**+ * Flatten a StyleX conditional value into its static leaves. `default` is kept+ * in the path here and normalized only when conditions are compared.+ */+function conditionalLeaves(node, path = []) {+ const text = getStaticText(node);+ if (text !== null) return [{path, text}];+ if (node?.type !== 'ObjectExpression') return [];++ return node.properties.flatMap((property) => {+ if (property.type !== 'Property') return [];+ const name = propertyName(property);+ if (typeof name !== 'string') return [];+ return conditionalLeaves(property.value, [...path, name]);+ });+}++function isRtlCondition(condition) {+ return (+ /\[dir\s*=\s*["']rtl["']\]/.test(condition) ||+ /:dir\(\s*rtl\s*\)/.test(condition)+ );+}++function normalizedConditions(path) {+ return path.filter(+ (condition) => condition !== 'default' && !isRtlCondition(condition),+ );+}++function sameConditions(a, b) {+ const left = normalizedConditions(a);+ const right = normalizedConditions(b);+ return (+ left.length === right.length &&+ left.every((condition, index) => condition === right[index])+ );+}++function horizontalTranslate(text) {+ const match = text.match(/\btranslate(?:X)?\s*\(\s*([^,\s)]+)/);+ if (!match) return null;+ const value = match[1];+ return /^[-+]?0(?:[a-z%]*)?$/.test(value) ? null : value;+}++function oppositeTranslations(a, b) {+ if (a === b) return false;+ const simple = /^([-+]?\d+(?:\.\d+)?)([a-z%]*)$/;+ const left = a.match(simple);+ const right = b.match(simple);+ if (!left || !right || left[2] !== right[2]) return true;+ return Number(left[1]) === -Number(right[1]);+}++function siblingProperty(node, keyName) {+ const object = node.parent;+ if (object?.type !== 'ObjectExpression') return null;+ return (+ object.properties.find(+ (property) =>+ property.type === 'Property' && propertyName(property) === keyName,+ ) ?? null+ );+}+/*** Does the given ObjectExpression already contain a Property whose key is* `keyName`? Handles both identifier keys (`marginLeft`) and string-literal@@ -128,35 +211,70 @@ function objectHasKey(objectExpression, keyName) {}/**- * Detects the inline-CENTERING pattern that must NOT be logicalized:- * `left: '50%'` (or `'-50%'`) paired, in the same style object, with a- * `transform` containing a `translate`/`translateX` — the physical anchor and- * the physical translate reference the SAME physical edge, so the pair centers- * symmetrically in both LTR and RTL. Renaming `left` → `insetInlineStart` here- * flips the anchor under RTL while the translate stays physical, breaking the- * centering by the element's own width. Callers should use the shared- * `rtlStyles.centerInline(blockOffset)` helper instead (which owns the one- * sanctioned physical-`left` suppression). Returns true when this Property is- * the `left: '50%'` of such a centering pair.+ * Returns the fixed inline-centering anchor value when a physical `left` and+ * horizontal translate are active under the same StyleX conditions.*/-function isInlineCenteringLeft(node) {- const value = getStaticValue(node.value);- if (value !== '50%' && value !== '-50%') return false;- const obj = node.parent;- if (!obj || obj.type !== 'ObjectExpression') return false;- return obj.properties.some((prop) => {- if (prop.type !== 'Property') return false;- const name = prop.key?.name ?? prop.key?.value;- if (name !== 'transform') return false;- // transform value may be a string literal or a template literal- let text = '';- if (prop.value?.type === 'Literal' && typeof prop.value.value === 'string') {- text = prop.value.value;- } else if (prop.value?.type === 'TemplateLiteral') {- text = prop.value.quasis.map((q) => q.value.raw).join(' ');+function inlineCenteringValue(node) {+ const transform = siblingProperty(node, 'transform');+ if (!transform) return null;+ const transforms = conditionalLeaves(transform.value).filter((leaf) =>+ horizontalTranslate(leaf.text),+ );++ for (const anchor of conditionalLeaves(node.value)) {+ if (anchor.text !== '50%' && anchor.text !== '-50%') continue;+ if (transforms.some((leaf) => sameConditions(anchor.path, leaf.path))) {+ return anchor.text;}- return /\btranslate(X)?\s*\(/.test(text);- });+ }+ return null;+}++/**+ * Returns the broken logical anchor value when a logical 50% inset and physical+ * horizontal translate share a conditional branch without an opposite RTL+ * transform in that branch.+ */+export function logicalCenteringStatuses(node) {+ const transform = siblingProperty(node, 'transform');+ if (!transform) return [];+ const transforms = conditionalLeaves(transform.value)+ .map((leaf) => ({...leaf, horizontal: horizontalTranslate(leaf.text)}))+ .filter((leaf) => leaf.horizontal !== null);+ const statuses = [];++ for (const anchor of conditionalLeaves(node.value)) {+ if (anchor.text !== '50%' && anchor.text !== '-50%') continue;+ const defaults = transforms.filter(+ (leaf) =>+ !leaf.path.some(isRtlCondition) &&+ sameConditions(anchor.path, leaf.path),+ );+ if (defaults.length === 0) continue;++ const rtlTransforms = transforms.filter(+ (leaf) =>+ leaf.path.some(isRtlCondition) &&+ sameConditions(anchor.path, leaf.path),+ );+ const compensated = defaults.every((defaultTransform) =>+ rtlTransforms.some((rtlTransform) =>+ oppositeTranslations(+ defaultTransform.horizontal,+ rtlTransform.horizontal,+ ),+ ),+ );+ statuses.push({compensated, value: anchor.text});+ }+ return statuses;+}++function unmirroredLogicalCenteringValue(node) {+ return (+ logicalCenteringStatuses(node).find((status) => !status.compensated)+ ?.value ?? null+ );}const rule = {@@ -165,9 +283,10 @@ const rule = {fixable: 'code',docs: {description:- 'Disallow physical left/right CSS properties and values inside ' +- 'stylex.create(). Use the CSS logical equivalents ' +- '(inline-start/inline-end, start/end) for RTL support.',+ 'Disallow physical left/right CSS properties and values, plus unsafe ' ++ 'logical-centering transforms, inside stylex.create(). Use logical ' ++ 'properties for directional placement and rtlStyles.centerInline() ' ++ 'for fixed geometric centering.',category: 'Best Practices',recommended: true,},@@ -184,10 +303,24 @@ const rule = {'`left: {{value}}` with a `translate` centers this element — do NOT ' +'rename it to `insetInlineStart` (that breaks centering under RTL). ' +'Use the shared `rtlStyles.centerInline(blockOffset)` helper instead.',+ logicalCenteringTransform:+ '`{{property}}: {{value}}` flips its anchor under RTL, but its paired ' ++ 'horizontal `translate` does not. Use `rtlStyles.centerInline(blockOffset)` ' ++ 'for fixed centering, or add an opposite RTL transform for a variable position.',},- schema: [],+ schema: [+ {+ type: 'object',+ properties: {+ allowLogicalCentering: {type: 'boolean'},+ },+ additionalProperties: false,+ },+ ],},create(context) {+ const allowLogicalCentering =+ context.options[0]?.allowLogicalCentering === true;return {Property(node) {if (!isInsideStylexCreate(node)) return;@@ -201,11 +334,13 @@ const rule = {// Special case: `left: '50%'` + a centering `translate` must NOT be// logicalized (it would break RTL centering). Point at the shared// helper instead, and do NOT autofix.- if (propName === 'left' && isInlineCenteringLeft(node)) {+ const centeringValue =+ propName === 'left' ? inlineCenteringValue(node) : null;+ if (centeringValue !== null) {context.report({node: node.key,messageId: 'inlineCentering',- data: {value: getStaticValue(node.value)},+ data: {value: centeringValue},});return;}@@ -248,6 +383,25 @@ const rule = {return;}+ // RELATIONSHIP-BASED: a logical 50% anchor flips under RTL while a+ // physical horizontal translation does not. Inspect matching nested+ // media/state branches and accept an explicit opposite RTL transform.+ if (+ !allowLogicalCentering &&+ (propName === 'insetInlineStart' ||+ propName === 'insetInlineEnd')+ ) {+ const centeringValue = unmirroredLogicalCenteringValue(node);+ if (centeringValue !== null) {+ context.report({+ node: node.key,+ messageId: 'logicalCenteringTransform',+ data: {property: propName, value: centeringValue},+ });+ return;+ }+ }+// VALUE-BASED: the key is fine, but the value may be physical.const valueMap = PHYSICAL_VALUE_MAP[propName];if (valueMap) {diff --git a/internal/eslint-plugin-astryx/no-physical-properties.test.mjs b/internal/eslint-plugin-astryx/no-physical-properties.test.mjsindex 82d626f73b..5d6b253441 100644--- a/internal/eslint-plugin-astryx/no-physical-properties.test.mjs+++ b/internal/eslint-plugin-astryx/no-physical-properties.test.mjs@@ -31,6 +31,40 @@ ruleTester.run('no-physical-properties', rule, {{code: inStylex(`paddingInlineEnd: 12`)},// Logical inset is fine{code: inStylex(`insetInlineStart: 0`)},+ // A variable-position logical anchor may pair with an explicit RTL transform.+ {+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translate(-50%, -50%)',+ ':is([dir="rtl"] *)': 'translate(50%, -50%)',+ }+ `),+ },+ // The same compensation may live inside the media branch that activates it.+ {+ code: inStylex(`+ insetInlineStart: { default: null, '@media (pointer: coarse)': '50%' },+ transform: {+ default: null,+ '@media (pointer: coarse)': {+ default: 'translate(-50%, -50%)',+ ':is([dir="rtl"] *)': 'translate(50%, -50%)',+ },+ }+ `),+ },+ // A block-only translation does not create the logical-anchor mismatch.+ {code: inStylex(`insetInlineStart: '50%', transform: 'translate(0, -50%)'`)},+ {+ // A narrow config exception may defer this relationship diagnostic while+ // retaining every key/value check in this rule.+ code: inStylex(`+ insetInlineStart: { default: null, '@media (pointer: coarse)': '50%' },+ transform: { default: null, '@media (pointer: coarse)': 'translate(-50%, -50%)' }+ `),+ options: [{allowLogicalCentering: true}],+ },// Logical border longhands are fine{code: inStylex(`borderInlineStartWidth: 1, borderInlineEndColor: 'red'`)},// Logical corner radii are fine@@ -148,6 +182,15 @@ ruleTester.run('no-physical-properties', rule, {{messageId: 'physicalKey', data: {physical: 'left', logical: 'insetInlineStart'}},],},+ {+ // The temporary relationship exemption does not weaken physical-key checks.+ code: inStylex(`left: 0`),+ options: [{allowLogicalCentering: true}],+ output: inStylex(`insetInlineStart: 0`),+ errors: [+ {messageId: 'physicalKey', data: {physical: 'left', logical: 'insetInlineStart'}},+ ],+ },{code: inStylex(`right: 0`),output: inStylex(`insetInlineEnd: 0`),@@ -191,6 +234,87 @@ ruleTester.run('no-physical-properties', rule, {{messageId: 'physicalKey', data: {physical: 'left', logical: 'insetInlineStart'}},],},+ {+ // Conditional physical centering must also point at centerInline rather+ // than being autofixed into the broken logical-anchor form.+ code: inStylex(`+ left: { default: null, '@media (pointer: coarse)': '50%' },+ transform: { default: null, '@media (pointer: coarse)': 'translate(-50%, -50%)' }+ `),+ output: null,+ errors: [{messageId: 'inlineCentering', data: {value: '50%'}}],+ },+ // --- LOGICAL-CENTERING MISMATCH: a logical 50% anchor flips in RTL but a+ // physical horizontal translate does not. These are non-fixing errors. ---+ {+ code: inStylex(`insetInlineStart: '50%', transform: 'translate(-50%, -50%)'`),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringTransform',+ data: {property: 'insetInlineStart', value: '50%'},+ },+ ],+ },+ {+ code: inStylex(`insetInlineEnd: '50%', transform: 'translateX(50%)'`),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringTransform',+ data: {property: 'insetInlineEnd', value: '50%'},+ },+ ],+ },+ {+ // An RTL branch must actually reverse the horizontal translation.+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translate(-50%, -50%)',+ ':is([dir="rtl"] *)': 'translate(-50%, -50%)',+ }+ `),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringTransform',+ data: {property: 'insetInlineStart', value: '50%'},+ },+ ],+ },+ {+ // This is the production shape from CheckboxInput, RadioListItem, and+ // Switch: the bug exists only inside the coarse-pointer branch.+ code: inStylex(`+ insetInlineStart: { default: null, '@media (pointer: coarse)': '50%' },+ transform: { default: null, '@media (pointer: coarse)': 'translate(-50%, -50%)' }+ `),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringTransform',+ data: {property: 'insetInlineStart', value: '50%'},+ },+ ],+ },+ {+ // A nested default transform without an RTL sibling is still broken.+ code: inStylex(`+ insetInlineStart: { default: null, '@media (pointer: coarse)': '50%' },+ transform: {+ default: null,+ '@media (pointer: coarse)': { default: 'translate(-50%, -50%)' },+ }+ `),+ output: null,+ errors: [+ {+ messageId: 'logicalCenteringTransform',+ data: {property: 'insetInlineStart', value: '50%'},+ },+ ],+ },// --- KEY-BASED: corner radii (verify the diagonal mapping) ---{code: inStylex(`borderTopLeftRadius: 4`),diff --git a/internal/eslint-plugin-astryx/prefer-center-inline.js b/internal/eslint-plugin-astryx/prefer-center-inline.jsnew file mode 100644index 0000000000..663c361044--- /dev/null+++ b/internal/eslint-plugin-astryx/prefer-center-inline.js@@ -0,0 +1,49 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file prefer-center-inline.js+ * @description Prefer the shared fixed-centering helper over a correct but+ * hand-rolled logical anchor plus RTL transform reversal.+ */++import {+ isInsideStylexCreate,+ logicalCenteringStatuses,+} from './no-physical-properties.js';++const INLINE_INSETS = new Set(['insetInlineStart', 'insetInlineEnd']);++const rule = {+ meta: {+ type: 'suggestion',+ docs: {+ description:+ 'Prefer rtlStyles.centerInline() for fixed 50% centering instead of a hand-rolled logical anchor and RTL transform pair',+ category: 'Consistency',+ recommended: true,+ url: 'https://github.com/facebook/astryx/issues/5170',+ },+ messages: {+ preferCenterInline:+ 'This fixed 50% centering manually reverses its transform under RTL. ' ++ 'Use `rtlStyles.centerInline(blockOffset)` so the direction-safe geometry ' ++ 'and its rationale live in one shared utility.',+ },+ schema: [],+ },+ create(context) {+ return {+ Property(node) {+ if (!isInsideStylexCreate(node)) return;+ const property = node.key?.name ?? node.key?.value;+ if (!INLINE_INSETS.has(property)) return;+ if (!logicalCenteringStatuses(node).some((status) => status.compensated)) {+ return;+ }+ context.report({node: node.key, messageId: 'preferCenterInline'});+ },+ };+ },+};++export default rule;diff --git a/internal/eslint-plugin-astryx/prefer-center-inline.test.mjs b/internal/eslint-plugin-astryx/prefer-center-inline.test.mjsnew file mode 100644index 0000000000..25d0d2b73a--- /dev/null+++ b/internal/eslint-plugin-astryx/prefer-center-inline.test.mjs@@ -0,0 +1,91 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {RuleTester} from 'eslint';+import rule from './prefer-center-inline.js';++const ruleTester = new RuleTester({+ languageOptions: {ecmaVersion: 2022, sourceType: 'module'},+});++function inStylex(body) {+ return `+ import * as stylex from '@stylexjs/stylex';+ const styles = stylex.create({+ base: { ${body} },+ });+ `;+}++ruleTester.run('prefer-center-inline', rule, {+ valid: [+ {code: inStylex(`insetInlineStart: 0`)},+ // The broken form belongs to no-physical-properties, not this style nudge.+ {+ code: inStylex(+ `insetInlineStart: '50%', transform: 'translate(-50%, -50%)'`,+ ),+ },+ // A non-centering variable position genuinely needs its RTL branch.+ {+ code: inStylex(`+ insetInlineStart: '35%',+ transform: {+ default: 'translateX(-50%)',+ ':is([dir="rtl"] *)': 'translateX(50%)',+ }+ `),+ },+ {+ code: `+ const style = {+ insetInlineStart: '50%',+ transform: {+ default: 'translateX(-50%)',+ ':dir(rtl)': 'translateX(50%)',+ },+ };+ `,+ },+ ],+ invalid: [+ {+ code: inStylex(`+ insetInlineStart: '50%',+ transform: {+ default: 'translate(-50%, -50%)',+ ':is([dir="rtl"] *)': 'translate(50%, -50%)',+ }+ `),+ errors: [{messageId: 'preferCenterInline'}],+ },+ {+ // Exact shape used by closed PR #5192.+ code: inStylex(`+ insetInlineStart: {+ default: null,+ '@media (pointer: coarse)': '50%',+ },+ transform: {+ default: null,+ '@media (pointer: coarse)': {+ default: 'translate(-50%, -50%)',+ ':is([dir="rtl"] *)': 'translate(50%, -50%)',+ },+ }+ `),+ errors: [{messageId: 'preferCenterInline'}],+ },+ {+ code: inStylex(`+ insetInlineEnd: '50%',+ transform: {+ default: 'translateX(50%)',+ ':dir(rtl)': 'translateX(-50%)',+ }+ `),+ errors: [{messageId: 'preferCenterInline'}],+ },+ ],+});++console.log('All tests passed!');