An open source design system that's fully customizable and agent ready
TypeScript
feat: update icon-only codemod to produce XDSIconButton (#1335)
Cindy Zhang1bda0f4724b9
diff --git a/packages/cli/src/codemods/transforms/v0.0.12/__tests__/add-is-icon-only.test.mjs b/packages/cli/src/codemods/transforms/v0.0.12/__tests__/add-is-icon-only.test.mjsindex 82a333c7c0..04bdb82646 100644--- a/packages/cli/src/codemods/transforms/v0.0.12/__tests__/add-is-icon-only.test.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.12/__tests__/add-is-icon-only.test.mjs@@ -9,24 +9,28 @@ async function applyTransform(source, filePath = 'test.tsx') {}describe('add-is-icon-only', () => {- it('adds isIconOnly to icon-only button', async () => {- const input = '<XDSButton label="Settings" icon={<GearIcon />} variant="ghost" />';- expect(await applyTransform(input)).toContain('isIconOnly');+ it('converts icon-only button to XDSIconButton', async () => {+ const input = `import {XDSButton} from '@xds/core/Button';+<XDSButton label="Settings" icon={<GearIcon />} variant="ghost" />`;+ const output = await applyTransform(input);+ expect(output).toContain('XDSIconButton');+ expect(output).not.toContain('XDSButton');+ expect(output).toContain('@xds/core/IconButton');});it('skips button with JSX children', async () => {const input = '<XDSButton label="Save" icon={<SaveIcon />}>Save</XDSButton>';- expect(await applyTransform(input)).not.toContain('isIconOnly');+ expect(await applyTransform(input)).not.toContain('XDSIconButton');});it('skips button with children prop', async () => {const input = '<XDSButton label="Save" icon={<SaveIcon />} children="Save" />';- expect(await applyTransform(input)).not.toContain('isIconOnly');+ expect(await applyTransform(input)).not.toContain('XDSIconButton');});it('skips button without icon', async () => {const input = '<XDSButton label="Submit" variant="primary" />';- expect(await applyTransform(input)).not.toContain('isIconOnly');+ expect(await applyTransform(input)).not.toContain('XDSIconButton');});it('skips button that already has isIconOnly', async () => {@@ -34,14 +38,22 @@ describe('add-is-icon-only', () => {expect(await applyTransform(input)).toBe(input);});- it('handles multiple buttons', async () => {- const input = '<>\n <XDSButton label="A" icon={<I />} />\n <XDSButton label="B" />\n <XDSButton label="C" icon={<I />} />\n</>';- expect((await applyTransform(input)).match(/isIconOnly/g)).toHaveLength(2);+ it('handles multiple buttons — converts only icon-only ones', async () => {+ const input = `import {XDSButton} from '@xds/core/Button';+<>+ <XDSButton label="A" icon={<I />} />+ <XDSButton label="B" />+ <XDSButton label="C" icon={<I />} />+</>`;+ const output = await applyTransform(input);+ expect((output.match(/XDSIconButton/g) || []).length).toBeGreaterThanOrEqual(2);+ // XDSButton should remain for the non-icon-only one+ expect(output).toContain('XDSButton');});- it('adds isIconOnly to XDSToggleButton', async () => {+ it('does NOT convert XDSToggleButton', async () => {const input = '<XDSToggleButton label="Bold" icon={<B />} value="bold" />';- expect(await applyTransform(input)).toContain('isIconOnly');+ expect(await applyTransform(input)).not.toContain('XDSIconButton');});it('removes redundant children matching label', async () => {@@ -68,7 +80,7 @@ describe('add-is-icon-only', () => {it('skips unrelated components', async () => {const input = '<XDSAvatar icon={<P />} name="U" />';- expect(await applyTransform(input)).not.toContain('isIconOnly');+ expect(await applyTransform(input)).not.toContain('XDSIconButton');});it('returns undefined when no changes needed', async () => {@@ -78,4 +90,43 @@ describe('add-is-icon-only', () => {const result = transform({source: '<XDSButton label="X" />', path: 'test.tsx'}, {jscodeshift: j, stats: () => {}, report: () => {}});expect(result).toBeUndefined();});++ it('removes endContent when converting to XDSIconButton', async () => {+ const input = `import {XDSButton} from '@xds/core/Button';+<XDSButton label="X" icon={<I />} endContent={<Badge />} />`;+ const output = await applyTransform(input);+ expect(output).toContain('XDSIconButton');+ expect(output).not.toContain('endContent');+ });++ it('replaces Button import when no XDSButton usage remains', async () => {+ const input = `import {XDSButton} from '@xds/core/Button';+<XDSButton label="X" icon={<I />} />`;+ const output = await applyTransform(input);+ expect(output).toContain('@xds/core/IconButton');+ expect(output).not.toContain('@xds/core/Button');+ });++ it('keeps Button import when XDSButton still used', async () => {+ const input = `import {XDSButton} from '@xds/core/Button';+<><XDSButton label="A" icon={<I />} /><XDSButton label="B" variant="primary" /></>`;+ const output = await applyTransform(input);+ expect(output).toContain('@xds/core/Button');+ expect(output).toContain('@xds/core/IconButton');+ });++ it('adds XDSIconButton to barrel import', async () => {+ const input = `import {XDSButton, XDSBadge} from '@xds/core';+<XDSButton label="X" icon={<I />} />`;+ const output = await applyTransform(input);+ expect(output).toContain('XDSIconButton');+ expect(output).toContain("from '@xds/core'");+ });++ it('updates closing tag for non-self-closing elements', async () => {+ const input = `import {XDSButton} from '@xds/core/Button';+<XDSButton label="X" icon={<I />}></XDSButton>`;+ const output = await applyTransform(input);+ expect(output).toContain('</XDSIconButton>');+ });});diff --git a/packages/cli/src/codemods/transforms/v0.0.12/add-is-icon-only.mjs b/packages/cli/src/codemods/transforms/v0.0.12/add-is-icon-only.mjsindex 076fcf46ae..109c582710 100644--- a/packages/cli/src/codemods/transforms/v0.0.12/add-is-icon-only.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.12/add-is-icon-only.mjs@@ -1,52 +1,61 @@/**- * @file Codemod: Add isIconOnly prop to icon-only XDSButton and XDSToggleButton- * @see https://github.com/facebookexperimental/xds/issues/1257+ * @file Codemod: Migrate pre-v0.0.12 icon-only XDSButton to XDSIconButton+ * @see https://github.com/facebookexperimental/xds/issues/1321*- * XDSButton and XDSToggleButton now use an explicit `isIconOnly` prop instead- * of inferring icon-only mode from `icon` present + `children` absent.+ * Migration codemod for code written against v0.0.11 or earlier.*- * With the new API, `label` is always rendered as visible text unless- * `isIconOnly={true}` is set. This codemod adds `isIconOnly` to all existing- * icon-only usages so behavior is preserved after the change.+ * Prior to v0.0.12, XDSButton inferred icon-only mode when `icon` was+ * present and no `children` were provided — the label was used as+ * aria-label only and the button rendered as a square icon button.*- * Detection: a JSX element is icon-only when it has:+ * In v0.0.12, that implicit inference is removed. `label` is always+ * rendered as visible text. Without this codemod, existing icon-only+ * buttons will start showing their label text alongside the icon.+ *+ * This codemod converts those implicit icon-only usages to the new+ * explicit `<XDSIconButton>` component, which is always icon-only by+ * design — no boolean prop to forget, visible in JSX, greppable.+ *+ * Detection: a JSX element was implicitly icon-only when it has:* 1. An `icon` prop (any value)* 2. No `children` prop AND no JSX children (self-closing or empty)- * 3. No existing `isIconOnly` prop+ * 3. No existing `isIconOnly` prop (already migrated)*- * This codemod also handles:- * - Object literals passed to components that forward button props- * (e.g., XDSDropdownMenu `button={{ icon: ..., label: ... }}`)+ * Also handles:+ * - Object literals in forwarding components (XDSDropdownMenu, XDSMoreMenu)+ * — these get `isIconOnly: true` since they pass props internally* - Removing redundant `children` that duplicate `label` on icon+text buttons- * (e.g., `<XDSButton label="Save" icon={...}>Save</XDSButton>` → `<XDSButton label="Save" icon={...} />`)+ *+ * Run on demand: `xds upgrade --from 0.0.11 --to 0.0.12 --codemod add-is-icon-only`*/const TARGET_COMPONENTS = new Set(['XDSButton',- 'XDSToggleButton',]);-/** Components whose button-like object props should also be migrated. */+/** Components whose button-like object props get isIconOnly: true added. */const FORWARDING_COMPONENTS = new Set(['XDSDropdownMenu','XDSMoreMenu',]);export const meta = {- title: 'Add isIconOnly to icon-only buttons',+ title: 'Migrate pre-v0.0.12 icon-only buttons to XDSIconButton',description:- 'XDSButton and XDSToggleButton now require explicit `isIconOnly` for icon-only mode. ' +- 'Adds `isIconOnly` to all existing icon-only usages. Also removes redundant children ' +- 'that duplicate the label prop on icon+text buttons.',- pr: '#1257',+ 'Converts implicit icon-only <XDSButton icon={...} label="..." /> (v0.0.11 pattern) ' ++ 'to the explicit <XDSIconButton> component introduced in v0.0.12. ' ++ 'Also adds isIconOnly to forwarding component object configs.',+ pr: '#1321',};export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);let hasChanges = false;+ let needsIconButtonImport = false;+ let hasRemainingXDSButton = false;- // ---- 1. JSX elements: add isIconOnly to icon-only buttons ----+ // ---- 1. JSX elements: convert icon-only XDSButton to XDSIconButton ----root.find(j.JSXOpeningElement).forEach((path) => {const name = path.node.name;const componentName =@@ -79,8 +88,22 @@ export default function transformer(file, api) {if (hasJSXChildren) return;- // This is an icon-only button — add isIconOnly- attrs.push(j.jsxAttribute(j.jsxIdentifier('isIconOnly')));+ // This is an icon-only button — convert to XDSIconButton+ name.name = 'XDSIconButton';++ // Remove endContent prop (XDSIconButton doesn't accept it)+ for (let i = attrs.length - 1; i >= 0; i--) {+ if (attrs[i].type === 'JSXAttribute' && attrs[i].name?.name === 'endContent') {+ attrs.splice(i, 1);+ }+ }++ // Update closing element if present+ if (parent.type === 'JSXElement' && parent.closingElement) {+ parent.closingElement.name.name = 'XDSIconButton';+ }++ needsIconButtonImport = true;hasChanges = true;});@@ -116,13 +139,11 @@ export default function transformer(file, api) {const child = children[0];if (child.type === 'JSXText' && child.value.trim() === labelValue) {- // Remove children, make self-closingpath.node.children = [];path.node.closingElement = null;opening.selfClosing = true;hasChanges = true;}- // Also handle JSXExpressionContainer with a string literalif (child.type === 'JSXExpressionContainer' &&(child.expression.type === 'StringLiteral' || child.expression.type === 'Literal') &&@@ -173,5 +194,81 @@ export default function transformer(file, api) {}});- return hasChanges ? root.toSource() : undefined;+ if (!hasChanges) return undefined;++ // ---- 4. Update imports ----+ // Check if any XDSButton JSX usage remains+ root.find(j.JSXIdentifier, {name: 'XDSButton'}).forEach(() => {+ hasRemainingXDSButton = true;+ });++ if (needsIconButtonImport) {+ // Check if XDSIconButton is already imported+ let alreadyImported = false;+ root.find(j.ImportDeclaration).forEach((path) => {+ if (path.node.specifiers.some(+ (s) => s.type === 'ImportSpecifier' && s.imported.name === 'XDSIconButton',+ )) {+ alreadyImported = true;+ }+ });++ if (!alreadyImported) {+ // If no XDSButton usage remains, replace the Button import+ if (!hasRemainingXDSButton) {+ root.find(j.ImportDeclaration).forEach((path) => {+ const source = path.node.source.value;+ if (source !== '@xds/core/Button') return;+ const specs = path.node.specifiers;+ const btnIdx = specs.findIndex(+ (s) => s.type === 'ImportSpecifier' && s.imported.name === 'XDSButton',+ );+ if (btnIdx === -1) return;++ // Replace XDSButton specifier with XDSIconButton+ specs[btnIdx] = j.importSpecifier(j.identifier('XDSIconButton'));+ path.node.source = j.literal('@xds/core/IconButton');+ alreadyImported = true;+ });+ }++ // For barrel imports, add the specifier+ if (!alreadyImported) {+ root.find(j.ImportDeclaration).forEach((path) => {+ if (alreadyImported) return;+ if (path.node.source.value === '@xds/core') {+ path.node.specifiers.push(+ j.importSpecifier(j.identifier('XDSIconButton')),+ );+ alreadyImported = true;+ }+ });+ }++ // Otherwise add a new import+ if (!alreadyImported) {+ const newImport = j.importDeclaration(+ [j.importSpecifier(j.identifier('XDSIconButton'))],+ j.literal('@xds/core/IconButton'),+ );++ const xdsImports = root+ .find(j.ImportDeclaration)+ .filter((p) => p.node.source.value.startsWith('@xds/'));++ if (xdsImports.length > 0) {+ xdsImports.at(-1).insertAfter(newImport);+ } else {+ const allImports = root.find(j.ImportDeclaration);+ if (allImports.length > 0) {+ allImports.at(-1).insertAfter(newImport);+ } else {+ root.get().node.program.body.unshift(newImport);+ }+ }+ }+ }+ }++ return root.toSource();}diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjsindex 3916cd1af2..bf12520cbd 100644--- a/packages/cli/src/commands/upgrade.mjs+++ b/packages/cli/src/commands/upgrade.mjs@@ -18,6 +18,7 @@* --to <version> Target version (default: latest in registry)* --force Run codemods even if versions appear up to date* --codemod <name> Run a specific transform only (skips version check)+ * --codemod-only Skip version bump + install, run codemods only* --path <dir> Source directory (default: ./src)* --install-deps Auto-install jscodeshift without prompting (for CI/LLM)*/@@ -139,6 +140,7 @@ export function registerUpgrade(program) {.option('--to <version>', 'Target version', latestVersion).option('--force', 'Run codemods even if versions appear up to date', false).option('--codemod <name>', 'Run a specific transform only')+ .option('--codemod-only', 'Skip version bump and install, run codemods only', false).option('--path <dir>', 'Source directory to scan', './src').option('--install-deps', 'Auto-install jscodeshift without prompting', false).option('--list', 'List available codemods', false)@@ -169,6 +171,11 @@ export function registerUpgrade(program) {// the user asked for a specific transform, just run it.const skipVersionCheck = !!options.codemod;+ // --codemod-only skips version bump + install but still uses --from/--to+ // for codemod resolution. Useful for canary testing or running codemods+ // independently of dependency changes.+ const skipBump = options.codemodOnly || skipVersionCheck;+// Detect current version (--from overrides package.json)const currentVersion = options.from ?? detectCurrentVersion();if (!currentVersion && !skipVersionCheck) {@@ -240,7 +247,7 @@ export function registerUpgrade(program) {const receipt = {from: currentVersion, to: targetVersion, codemods: totalTransforms, depsUpdated: [], agentDocsRefreshed: false};// Bump @xds/* deps and install before running codemods- if (options.apply && !skipVersionCheck) {+ if (options.apply && !skipBump) {const result = bumpXdsDeps(targetVersion);if (result && result.bumped.length > 0) {receipt.depsUpdated = result.bumped;