An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): codemod migrating input root styling to container*/control* parts (#7342)
Cindy Zhangfe57f5404b63
diff --git a/.changeset/field-input-styling-codemod.md b/.changeset/field-input-styling-codemod.mdnew file mode 100644index 0000000000..baffdb5f0a--- /dev/null+++ b/.changeset/field-input-styling-codemod.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] `astryx upgrade` runs `migrate-field-input-styling`, which renames root `xstyle`/`className`/`style` on Field-composed inputs to the part they styled before: `controlXstyle`/`controlClassName`/`controlStyle` on TextInput, TextArea, NumberInput, FileInput, DateInput, DateRangeInput, DateTimeInput, TimeInput, Selector, MultiSelector, and ComplexSelector, and `containerXstyle`/`containerClassName`/`containerStyle` on Typeahead, Tokenizer, CheckboxList, RadioList, and Slider. It rewrites JSX written directly on an Astryx import (named, aliased, or namespace). Spreads and wrappers that forward their own styling props are left for manual migration, and a callsite that already sets the target prop gets a TODO instead of a rename.++@cixzhangdiff --git a/packages/cli/assets/codemods/transforms/next/__tests__/migrate-field-input-styling.test.mjs b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-field-input-styling.test.mjsnew file mode 100644index 0000000000..d127cc860e--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/__tests__/migrate-field-input-styling.test.mjs@@ -0,0 +1,108 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import jscodeshift from 'jscodeshift';+import transform from '../migrate-field-input-styling.mjs';++const j = jscodeshift.withParser('tsx');+const api = {jscodeshift: j, stats: () => {}, report: () => {}};++/** @param {string} source */+function apply(source) {+ return transform({source, path: 'test.tsx'}, api) ?? source;+}++describe('migrate-field-input-styling', () => {+ it('moves control-box members to control*', () => {+ const input = `import {TextInput, Selector, DateInput} from '@astryxdesign/core';+const a = <TextInput label="Name" xstyle={styles.input} className="name" style={{width: 200}} />;+const b = <Selector label="Fruit" options={options} xstyle={styles.selector} />;+const c = <DateInput label="Due" className="due" />;`;+ const output = apply(input);+ expect(output).toContain(+ '<TextInput label="Name" controlXstyle={styles.input} controlClassName="name" controlStyle={{width: 200}} />',+ );+ expect(output).toContain('controlXstyle={styles.selector}');+ expect(output).toContain(+ '<DateInput label="Due" controlClassName="due" />',+ );+ });++ it('moves Field-root members to container*', () => {+ const input = `import {Typeahead} from '@astryxdesign/core/Typeahead';+import {RadioList, Slider} from '@astryxdesign/core';+const a = <Typeahead label="Fruit" xstyle={styles.wide} />;+const b = <RadioList label="Plan" style={{marginTop: 8}}>{items}</RadioList>;+const c = <Slider label="Volume" className="volume" value={1} />;`;+ const output = apply(input);+ expect(output).toContain('containerXstyle={styles.wide}');+ expect(output).toContain('containerStyle={{marginTop: 8}}');+ expect(output).toContain('containerClassName="volume"');+ });++ it('moves a Typeahead inside InputGroup to control*, where its root styling painted the surface', () => {+ const input = `import {InputGroup, Typeahead} from '@astryxdesign/core';+const a = (+ <InputGroup label="Produce">+ <Typeahead label="Fruit" className="grouped" />+ </InputGroup>+);+const b = <Typeahead label="Fruit" className="standalone" />;`;+ const output = apply(input);+ expect(output).toContain('controlClassName="grouped"');+ expect(output).toContain('containerClassName="standalone"');+ });++ it('follows aliased and namespace imports', () => {+ const input = `import {TextArea as Notes} from '@astryxdesign/core';+import * as Astryx from '@astryxdesign/core';+const a = <Notes label="Notes" className="notes" />;+const b = <Astryx.Tokenizer label="Tags" xstyle={styles.tags} />;`;+ const output = apply(input);+ expect(output).toContain(+ '<Notes label="Notes" controlClassName="notes" />',+ );+ expect(output).toContain(+ '<Astryx.Tokenizer label="Tags" containerXstyle={styles.tags} />',+ );+ });++ it('leaves unrelated components, other packages, nested JSX, and spreads alone', () => {+ const input = `import {TextInput} from 'some-other-library';+import {Button, NumberInput} from '@astryxdesign/core';+const a = <TextInput className="kept" />;+const b = <Button xstyle={styles.button} />;+const c = <NumberInput label="Qty" {...rest} startIcon={<Icon className="icon" />} />;`;+ expect(apply(input)).toBe(input);+ });++ it('leaves tags whose name is shadowed by a local binding', () => {+ const input = `import {TextInput} from '@astryxdesign/core';+import * as Astryx from '@astryxdesign/core';+function Row({TextInput}) {+ return <TextInput className="kept" />;+}+function Other(Astryx) {+ return <Astryx.Typeahead className="kept" />;+}`;+ expect(apply(input)).toBe(input);+ });++ it('marks a conflict with a TODO instead of dropping a value', () => {+ const input = `import {TextInput} from '@astryxdesign/core';+const a = <TextInput label="Name" className="old" controlClassName="new" />;`;+ const output = apply(input);+ expect(output).toContain('controlClassName="new"');+ expect(output).toContain('className="old"');+ expect(output).toContain('TODO(astryx upgrade)');+ });++ it('is idempotent', () => {+ const input = `import {TextInput, CheckboxList} from '@astryxdesign/core';+const a = <TextInput label="Name" className="old" controlClassName="new" />;+const b = <TextInput label="Email" xstyle={styles.email} />;+const c = <CheckboxList label="Prefs" style={{margin: 4}}>{items}</CheckboxList>;`;+ const once = apply(input);+ expect(apply(once)).toBe(once);+ });+});diff --git a/packages/cli/assets/codemods/transforms/next/index.mjs b/packages/cli/assets/codemods/transforms/next/index.mjsindex d89dc5fcbb..18e02ea216 100644--- a/packages/cli/assets/codemods/transforms/next/index.mjs+++ b/packages/cli/assets/codemods/transforms/next/index.mjs@@ -10,6 +10,9 @@import migrateDeprecatedThemeSurface, {meta as migrateDeprecatedThemeSurfaceMeta,} from './migrate-deprecated-theme-surface.mjs';+import migrateFieldInputStyling, {+ meta as migrateFieldInputStylingMeta,+} from './migrate-field-input-styling.mjs';import validateDataTokenOwnership, {meta as validateDataTokenOwnershipMeta,} from './validate-data-token-ownership.mjs';@@ -25,4 +28,9 @@ export default [transform: validateDataTokenOwnership,meta: validateDataTokenOwnershipMeta,},+ {+ name: 'migrate-field-input-styling',+ transform: migrateFieldInputStyling,+ meta: migrateFieldInputStylingMeta,+ },];diff --git a/packages/cli/assets/codemods/transforms/next/migrate-field-input-styling.mjs b/packages/cli/assets/codemods/transforms/next/migrate-field-input-styling.mjsnew file mode 100644index 0000000000..b7534d8d95--- /dev/null+++ b/packages/cli/assets/codemods/transforms/next/migrate-field-input-styling.mjs@@ -0,0 +1,198 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Migrate root styling on Field-composed inputs to their named parts.+ *+ * Field-composed inputs no longer accept root `xstyle`, `className`, or+ * `style` (family:input-fields FR10). Each rename keeps the element the+ * styling reached before: components whose root styling painted the visual+ * control box move to `controlXstyle`/`controlClassName`/`controlStyle`;+ * components whose root styling reached the Field box move to+ * `containerXstyle`/`containerClassName`/`containerStyle`.+ *+ * Only JSX attributes written directly on an element bound to an Astryx import+ * are renamed (named, aliased, or namespace imports). Spread attributes,+ * wrappers that forward their own props, and unrelated components of the same+ * name are left alone; those callsites fail type-checking and are migrated by+ * hand. When the target attribute is already present, the root attribute gets a+ * TODO instead of a rename so no value is silently dropped.+ */++import {transformProp} from '../../transform-prop.mjs';++export const meta = {+ title: 'Migrate input root styling to container/control parts',+ description:+ 'Renames root `xstyle`/`className`/`style` on Field-composed inputs to the `control*` or `container*` part they styled before.',+ fileExtensions: ['.tsx', '.jsx', '.ts', '.js', '.mjs', '.cjs'],+};++/** Components whose root styling painted the visual control box. */+const CONTROL_COMPONENTS = [+ 'TextInput',+ 'TextArea',+ 'NumberInput',+ 'FileInput',+ 'DateInput',+ 'DateRangeInput',+ 'DateTimeInput',+ 'TimeInput',+ 'Selector',+ 'MultiSelector',+ 'ComplexSelector',+];++/** Components whose root styling reached the Field box. */+const CONTAINER_COMPONENTS = [+ 'Typeahead',+ 'Tokenizer',+ 'CheckboxList',+ 'RadioList',+ 'Slider',+];++/**+ * Field-root members that also render inside InputGroup. There Field is absent+ * and root styling painted the control surface, so it moves to `control*`.+ */+const GROUPED_CONTROL_COMPONENTS = new Set(['Typeahead']);++/** @type {ReadonlyMap<string, 'control' | 'container'>} */+const PART_BY_COMPONENT = new Map([+ ...CONTROL_COMPONENTS.map(name => /** @type {const} */ ([name, 'control'])),+ ...CONTAINER_COMPONENTS.map(+ name => /** @type {const} */ ([name, 'container']),+ ),+]);++const ROOT_STYLE_PROPS = /** @type {const} */ ({+ xstyle: 'Xstyle',+ className: 'ClassName',+ style: 'Style',+});++const PACKAGE_PATTERN = /^@(astryxdesign|xds)\/core(\/[A-Za-z]+)?$/u;++const TODO =+ ' TODO(astryx upgrade): root styling is no longer accepted here; merge it into ';++/** @type {ReadonlyMap<string, ReadonlySet<string>>} */+const COMPONENT_PROPS = new Map(+ [...PART_BY_COMPONENT.keys()].map(name => [+ name,+ new Set(Object.keys(ROOT_STYLE_PROPS)),+ ]),+);++/**+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file+ * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api+ * @returns {string | undefined}+ */+export default function migrateFieldInputStyling(file, api) {+ if (!/xstyle|className|style/u.test(file.source)) return undefined;+ if (![...PART_BY_COMPONENT.keys()].some(name => file.source.includes(name))) {+ return undefined;+ }++ const j = api.jscodeshift;+ const root = j(file.source);+ const matchesImport = (/** @type {string} */ source) =>+ PACKAGE_PATTERN.test(source);++ // Local names that resolve to an Astryx InputGroup (named or namespace).+ /** @type {Set<string>} */+ const inputGroupNames = new Set();+ /** @type {Set<string>} */+ const namespaceNames = new Set();+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {+ const source = path.node.source.value;+ if (path.node.importKind === 'type') return;+ if (typeof source !== 'string' || !matchesImport(source)) return;+ for (const specifier of path.node.specifiers ?? []) {+ if (specifier.importKind === 'type') continue;+ if (+ specifier.type === 'ImportSpecifier' &&+ specifier.imported?.name === 'InputGroup'+ ) {+ inputGroupNames.add(specifier.local?.name ?? 'InputGroup');+ } else if (specifier.type === 'ImportNamespaceSpecifier') {+ namespaceNames.add(specifier.local.name);+ }+ }+ });++ /** @param {any} elementPath a JSXElement path */+ const isInputGroup = elementPath => {+ const name = elementPath.node.openingElement.name;+ let localName;+ if (name.type === 'JSXIdentifier' && inputGroupNames.has(name.name)) {+ localName = name.name;+ } else if (+ name.type === 'JSXMemberExpression' &&+ name.object?.type === 'JSXIdentifier' &&+ name.property?.type === 'JSXIdentifier' &&+ name.property.name === 'InputGroup' &&+ namespaceNames.has(name.object.name)+ ) {+ localName = name.object.name;+ } else {+ return false;+ }+ const scope = elementPath.scope?.lookup(localName);+ return scope?.path.node.type === 'Program';+ };++ /** @param {any} openingPath a JSXOpeningElement path */+ const isInsideInputGroup = openingPath => {+ for (let p = openingPath.parent?.parent; p; p = p.parent) {+ if (p.node.type === 'JSXElement' && isInputGroup(p)) return true;+ }+ return false;+ };++ let changed = false;+ transformProp(+ root,+ j,+ {matchesImport, components: COMPONENT_PROPS},+ (propPath, {component}) => {+ const attribute = propPath.node;+ const openingPath = propPath.parent;+ let part = PART_BY_COMPONENT.get(component);+ if (!part) return;+ if (+ part === 'container' &&+ GROUPED_CONTROL_COMPONENTS.has(component) &&+ isInsideInputGroup(openingPath)+ ) {+ part = 'control';+ }+ const name = /** @type {keyof typeof ROOT_STYLE_PROPS} */ (+ attribute.name.name+ );+ const next = part + ROOT_STYLE_PROPS[name];+ const present = (openingPath.node.attributes ?? []).some(+ (/** @type {any} */ a) =>+ a.type === 'JSXAttribute' && a.name?.name === next,+ );+ if (present) {+ const comment = `${TODO}\`${next}\`. `;+ attribute.comments ??= [];+ if (+ !attribute.comments.some(+ (/** @type {any} */ c) => c.value === comment,+ )+ ) {+ attribute.comments.push(j.commentBlock(comment, true, false));+ changed = true;+ }+ return;+ }+ attribute.name = j.jsxIdentifier(next);+ changed = true;+ },+ );++ return changed ? root.toSource({quote: 'single'}) : undefined;+}diff --git a/packages/core/src/Field/fieldInputFamily.test.tsx b/packages/core/src/Field/fieldInputFamily.test.tsxindex c0d56014f7..174a3e6e9e 100644--- a/packages/core/src/Field/fieldInputFamily.test.tsx+++ b/packages/core/src/Field/fieldInputFamily.test.tsx@@ -15,14 +15,9 @@ const SRC = join(__dirname, '..');// Directories that render <Field> without being a Field-composed input.const NOT_FIELD_INPUTS = new Set(['Field', 'InputGroup', 'FormLayout']);-// Field-composed inputs not yet converted to FR10. Each batch removes its own-// group; keep the comment lines between groups so removals merge cleanly.-const PENDING_FR10 = new Set([- // text batch- // date/time batch- // selector batch- // field-root batch-]);+// Field-composed inputs not yet converted to FR10. Every member is converted;+// typed explicitly so the empty set still accepts string lookups.+const PENDING_FR10: ReadonlySet<string> = new Set<string>();function fieldComposedComponents(): string[] {return readdirSync(SRC)