Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(cli): preserve JSX whitespace when the upgrade codemod renames element tags (#5149)

EJ Hammond12748204bd9b
diff --git a/.changeset/codemod-jsx-rename-whitespace.md b/.changeset/codemod-jsx-rename-whitespace.md
new file mode 100644
index 0000000000..3d31ba8946
--- /dev/null
+++ b/.changeset/codemod-jsx-rename-whitespace.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] The upgrade codemod no longer collapses significant JSX whitespace when it renames an element tag. Renaming `<OldName>` next to text and a `{expression}` (e.g. `hello {name} world`) previously dropped the adjacent space (`hello {name}world`); element-tag renames are now spliced into the output so the surrounding JSX is left untouched.
+
+@ejhammond
diff --git a/packages/cli/assets/codemods/transforms/v0.1.0/__tests__/drop-xds-prefix-imports.test.mjs b/packages/cli/assets/codemods/transforms/v0.1.0/__tests__/drop-xds-prefix-imports.test.mjs
index 2328b0174c..780bb83d2a 100644
--- a/packages/cli/assets/codemods/transforms/v0.1.0/__tests__/drop-xds-prefix-imports.test.mjs
+++ b/packages/cli/assets/codemods/transforms/v0.1.0/__tests__/drop-xds-prefix-imports.test.mjs
@@ -303,4 +303,158 @@ describe('drop-xds-prefix-imports', () => {
expect(output).not.toContain('AstryxButton');
expect(output).not.toContain('XDSButton');
});
+
+ describe('JSX whitespace preservation on element-name rename', () => {
+ it('preserves the space between text and a following {expression} inside return (...)', async () => {
+ const input = [
+ `import {XDSText} from '@xds/core';`,
+ `export function App({name}) {`,
+ ` return (`,
+ ` <XDSText>hello {name} world</XDSText>`,
+ ` );`,
+ `}`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ // Element is renamed...
+ expect(output).toContain('<Text>');
+ expect(output).toContain('</Text>');
+ expect(output).not.toContain('XDSText');
+ // ...and the whitespace around the {expression} survives (the bug
+ // collapsed `{name} world` to `{name}world`).
+ expect(output).toContain('hello {name} world');
+ expect(output).not.toContain('{name}world');
+ });
+
+ it('preserves whitespace with multiple {expressions} adjacent to text', async () => {
+ const input = [
+ `import {XDSText} from '@xds/core';`,
+ `export function App({a, b}) {`,
+ ` return (`,
+ ` <XDSText>involving {a} in the {b} dataset</XDSText>`,
+ ` );`,
+ `}`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ expect(output).toContain('involving {a} in the {b} dataset');
+ expect(output).toContain('<Text>');
+ expect(output).not.toContain('XDSText');
+ });
+
+ it('preserves whitespace across a multi-line JSX body', async () => {
+ const input = [
+ `import {XDSText} from '@xds/core';`,
+ `export function App({a, b}) {`,
+ ` return (`,
+ ` <XDSText>`,
+ ` involving {a} in the {b} dataset`,
+ ` </XDSText>`,
+ ` );`,
+ `}`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ expect(output).toContain('involving {a} in the {b} dataset');
+ expect(output).toContain('<Text>');
+ expect(output).toContain('</Text>');
+ expect(output).not.toContain('XDSText');
+ });
+
+ it('renames both the opening and closing tag of the same element', async () => {
+ const input = [
+ `import {XDSCard} from '@xds/core';`,
+ `export const App = ({n}) => (<XDSCard>value {n} here</XDSCard>);`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ expect(output).toContain('<Card>');
+ expect(output).toContain('</Card>');
+ expect(output).toContain('value {n} here');
+ expect(output).not.toContain('XDSCard');
+ });
+
+ it('preserves whitespace for multiple different elements in one return', async () => {
+ const input = [
+ `import {XDSCard, XDSText, XDSButton} from '@xds/core';`,
+ `export const App = ({n}) => (`,
+ ` <XDSCard>`,
+ ` <XDSText>hello {n} world</XDSText>`,
+ ` <XDSButton>click {n} here</XDSButton>`,
+ ` </XDSCard>`,
+ `);`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ expect(output).toContain('import {Card, Text, Button}');
+ expect(output).toContain('<Card>');
+ expect(output).toContain('hello {n} world');
+ expect(output).toContain('click {n} here');
+ expect(output).not.toContain('XDS');
+ });
+
+ it('renames only the mapped segment of a member-expression tag name, preserving whitespace', async () => {
+ const input = [
+ `import {XDSMenu} from '@xds/core';`,
+ `export const App = ({x}) => (<XDSMenu.Item>pick {x} now</XDSMenu.Item>);`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ // Only the mapped `XDSMenu` segment is renamed; `.Item` is preserved.
+ expect(output).toContain('<Menu.Item>');
+ expect(output).toContain('</Menu.Item>');
+ expect(output).toContain('pick {x} now');
+ expect(output).not.toContain('XDSMenu');
+ });
+
+ it('renames a self-closing element with attributes without altering the attributes', async () => {
+ const input = [
+ `import {XDSButton} from '@xds/core';`,
+ `export const App = () => <XDSButton label="x" onClick={fn} />;`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ expect(output).toContain('<Button label="x" onClick={fn} />');
+ expect(output).not.toContain('XDSButton');
+ });
+
+ it('handles a JSX body with no whitespace to preserve', async () => {
+ const input = [
+ `import {XDSButton} from '@xds/core';`,
+ `export const App = ({label}) => <XDSButton>{label}</XDSButton>;`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ expect(output).toContain('<Button>{label}</Button>');
+ expect(output).not.toContain('XDSButton');
+ });
+
+ it('preserves whitespace when the bare name is aliased on a collision', async () => {
+ const input = [
+ `import {XDSCodeBlock} from '@xds/core/CodeBlock';`,
+ `export function CodeBlock({code}) {`,
+ ` return (<XDSCodeBlock>run {code} now</XDSCodeBlock>);`,
+ `}`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ expect(output).toContain('CodeBlock as AstryxCodeBlock');
+ expect(output).toContain('<AstryxCodeBlock>');
+ expect(output).toContain('</AstryxCodeBlock>');
+ expect(output).toContain('run {code} now');
+ });
+
+ it('keeps a custom local alias on the element tag and preserves whitespace', async () => {
+ const input = [
+ `import {XDSText as Txt} from '@xds/core';`,
+ `export const App = ({n}) => (<Txt>hello {n} world</Txt>);`,
+ ].join('\n');
+ const output = await applyTransform(input);
+ expect(output).toContain('Text as Txt');
+ expect(output).toContain('<Txt>hello {n} world</Txt>');
+ expect(output).not.toContain('XDSText');
+ });
+
+ it('is idempotent: a second pass over already-migrated output is a no-op', async () => {
+ const input = [
+ `import {XDSText} from '@xds/core';`,
+ `export const App = ({n}) => (<XDSText>a {n} b</XDSText>);`,
+ ].join('\n');
+ const once = await applyTransform(input);
+ const twice = await applyTransform(once);
+ expect(twice).toBe(once);
+ expect(once).toContain('a {n} b');
+ });
+ });
});
diff --git a/packages/cli/assets/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs b/packages/cli/assets/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs
index 130f722fa5..97a1dbea36 100644
--- a/packages/cli/assets/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs
+++ b/packages/cli/assets/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs
@@ -346,18 +346,27 @@ export default function transformer(file, api) {
}
// Don't double-rewrite the import specifier we already handled.
if (parent.type === 'ImportSpecifier') return;
+ // JSX element tag names are handled by a source-string splice after
+ // `toSource()` (see renameJsxElementNamesInSource). Mutating them here
+ // would dirty the enclosing JSXElement and make recast collapse whitespace
+ // around adjacent `{expressions}`. Under the tsx parser a JSX tag-name
+ // JSXIdentifier is a subtype of Identifier, so it surfaces in this
+ // `find(j.Identifier)` pass and must be explicitly skipped.
+ if (isJsxElementNameIdentifier(path)) return;
path.node.name = newName;
hasChanges = true;
});
- // JSX element names: <XDSButton> -> <Button>
- root.find(j.JSXIdentifier).forEach((/** @type {any} */ path) => {
- const newName = localRenames.get(path.node.name);
- if (newName) {
- path.node.name = newName;
- hasChanges = true;
- }
- });
+ // JSX element names (`<XDSButton>` -> `<Button>`) are intentionally NOT
+ // renamed via AST mutation here. Mutating a JSXIdentifier in place dirties the
+ // enclosing JSXElement; when that element is the argument of a parenthesized
+ // `return ( <JSX/> )` (i.e. every React component body), recast declines a
+ // surgical child reprint and generically re-prints the whole return argument.
+ // Its generic JSXElement printer drops significant whitespace from JSXText
+ // that sits next to a `{expression}` -- so `hello {name} world` collapses to
+ // `hello {name}world`. Instead we splice the element-name renames directly
+ // into the emitted source string (below), which never re-prints the subtree.
+ // See renameJsxElementNamesInSource for the mechanism.
// 5. Rename TS type references in generic type-argument positions.
//
@@ -413,5 +422,98 @@ export default function transformer(file, api) {
};
renameTypeReferences(root.get().node);
- return hasChanges ? root.toSource() : undefined;
+ if (!hasChanges) return undefined;
+
+ // Emit the AST-based renames, then splice the JSX element-name renames onto
+ // the emitted string (see the note in the JSX section above for why element
+ // names cannot be renamed through the AST without collapsing whitespace).
+ const emitted = root.toSource();
+ return renameJsxElementNamesInSource(j, emitted, localRenames);
+}
+
+/**
+ * Rename JSX element tag names (`<XDSButton>` / `</XDSButton>`) by splicing the
+ * new names directly into the already-emitted source, so recast never re-prints
+ * the surrounding JSX subtree (which would strip whitespace next to
+ * `{expressions}`).
+ *
+ * Spans are computed by re-parsing `source` itself, so the offsets are always
+ * valid against the string we splice into -- no dependency on the original
+ * pre-transform offsets. Splices are applied right-to-left (descending start
+ * offset) so earlier offsets stay valid as we go.
+ *
+ * Only the identifier that IS the element's tag name is renamed:
+ * - `<Foo attr />` -> the `Foo` opening-name only (not `attr`)
+ * - `<Ns.Foo />` / `<Foo.Bar>`-> the specific member-expression identifier that
+ * maps in `renames`; the other part of the member name is preserved
+ *
+ * @param {any} j jscodeshift instance (already bound to the tsx parser)
+ * @param {string} source emitted source to rewrite
+ * @param {Map<string, string>} renames localName -> newLocalName
+ * @returns {string}
+ */
+function renameJsxElementNamesInSource(j, source, renames) {
+ if (renames.size === 0) return source;
+
+ const root = j(source);
+
+ /** @type {Array<{start: number, end: number, name: string}>} */
+ const edits = [];
+
+ root.find(j.JSXIdentifier).forEach((/** @type {any} */ path) => {
+ const node = path.node;
+ const newName = renames.get(node.name);
+ if (!newName || newName === node.name) return;
+
+ // The identifier must BE an element tag name -- the `.name` of a
+ // JSXOpeningElement/JSXClosingElement, or the matching part of a
+ // JSXMemberExpression tag name. Attribute names, attribute values, and the
+ // non-matching half of a member-expression name must be left alone.
+ if (!isJsxElementNameIdentifier(path)) return;
+
+ if (typeof node.start !== 'number' || typeof node.end !== 'number') return;
+ edits.push({start: node.start, end: node.end, name: newName});
+ });
+
+ if (edits.length === 0) return source;
+
+ edits.sort((a, b) => b.start - a.start);
+
+ let out = source;
+ for (const {start, end, name} of edits) {
+ out = out.slice(0, start) + name + out.slice(end);
+ }
+ return out;
+}
+
+/**
+ * Is this JSXIdentifier path the tag name of its element (opening or closing),
+ * as opposed to an attribute name or a namespace/member-expression segment we
+ * should not rename? For member-expression tag names (`<Foo.Bar>`) we accept
+ * the identifier regardless of which segment it is -- the caller only reaches
+ * here for identifiers whose name is in the rename map, and each renamed
+ * identifier maps independently, so `<Foo.Bar>` renames only the segment(s)
+ * that actually map.
+ *
+ * @param {any} path jscodeshift path to a JSXIdentifier
+ * @returns {boolean}
+ */
+function isJsxElementNameIdentifier(path) {
+ const parent = path.parent && path.parent.node;
+ if (!parent) return false;
+
+ if (
+ parent.type === 'JSXOpeningElement' ||
+ parent.type === 'JSXClosingElement'
+ ) {
+ return parent.name === path.node;
+ }
+
+ // `<Foo.Bar>` / `<A.B.C>`: the tag name is a JSXMemberExpression whose
+ // segments are JSXIdentifiers. Rename the specific matching segment only.
+ if (parent.type === 'JSXMemberExpression') {
+ return parent.object === path.node || parent.property === path.node;
+ }
+
+ return false;
}