Skip to content

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

TypeScript

feat(cli): add codemod to migrate tree-mode useTableRowExpansion to the tree plugin (#4142) (#4884)

Humberto Virtudesccb5ca9dc1a5
diff --git a/.changeset/cli-migrate-table-rowexpansion-to-tree.md b/.changeset/cli-migrate-table-rowexpansion-to-tree.md
new file mode 100644
index 0000000000..56237424b3
--- /dev/null
+++ b/.changeset/cli-migrate-table-rowexpansion-to-tree.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Add the `migrate-table-rowexpansion-to-tree` codemod (runs on `astryx upgrade`): rewrites the removed `useTableRowExpansionState` tree pattern to `useTableTreeState` + `useTableTreeData`. Detail-panel usage (`renderExpanded`) is left untouched.
+
+@humbertovirtudes
diff --git a/packages/cli/assets/codemods/transforms/v0.3.0/__tests__/migrate-table-rowexpansion-to-tree.test.mjs b/packages/cli/assets/codemods/transforms/v0.3.0/__tests__/migrate-table-rowexpansion-to-tree.test.mjs
new file mode 100644
index 0000000000..5f2a64fea2
--- /dev/null
+++ b/packages/cli/assets/codemods/transforms/v0.3.0/__tests__/migrate-table-rowexpansion-to-tree.test.mjs
@@ -0,0 +1,201 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+
+async function applyTransform(source) {
+ const {default: transform} = await import(
+ '../migrate-table-rowexpansion-to-tree.mjs'
+ );
+ const jscodeshift = (await import('jscodeshift')).default;
+ const j = jscodeshift.withParser('tsx');
+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};
+ const file = {source, path: 'test.tsx'};
+ const result = transform(file, api);
+ return result ?? source;
+}
+
+function normalize(str) {
+ return str
+ .replace(/\s+/g, ' ')
+ .replace(/\{\s+/g, '{')
+ .replace(/\s+\}/g, '}')
+ .trim();
+}
+
+describe('migrate-table-rowexpansion-to-tree', () => {
+ it('rewrites the useTableRowExpansionState import to useTableTreeState', async () => {
+ const input = `import {Table, useTableRowExpansion, useTableRowExpansionState} from '@astryxdesign/core';
+function C() {
+ const {data, expansionConfig} = useTableRowExpansionState({
+ baseData: tree,
+ getChildren: item => item.children ?? [],
+ getRowKey: item => item.id,
+ expandedKeys,
+ setExpandedKeys,
+ });
+ const expansion = useTableRowExpansion(expansionConfig);
+ return <Table data={data} columns={cols} idKey="id" plugins={{expansion}} />;
+}`;
+ const output = await applyTransform(input);
+ expect(output).not.toContain('useTableRowExpansionState');
+ expect(output).toContain('useTableTreeState');
+ expect(output).toContain('useTableTreeData');
+ });
+
+ it('maps baseData to data and getChildren to childrenKey', async () => {
+ const input = `import {Table, useTableRowExpansion, useTableRowExpansionState} from '@astryxdesign/core';
+function C() {
+ const {data, expansionConfig} = useTableRowExpansionState({
+ baseData: tree,
+ getChildren: item => item.children ?? [],
+ getRowKey: item => item.id,
+ expandedKeys,
+ setExpandedKeys,
+ });
+ const expansion = useTableRowExpansion(expansionConfig);
+ return <Table data={data} columns={cols} idKey="id" plugins={{expansion}} />;
+}`;
+ const output = await applyTransform(input);
+ const n = normalize(output);
+ expect(n).toContain('data: tree');
+ expect(n).toContain("childrenKey: 'children'");
+ expect(output).not.toContain('baseData');
+ expect(output).not.toContain('getChildren');
+ });
+
+ it('maps getRowKey to idKey preserving the accessor function', async () => {
+ const input = `import {Table, useTableRowExpansion, useTableRowExpansionState} from '@astryxdesign/core';
+function C() {
+ const {data, expansionConfig} = useTableRowExpansionState({
+ baseData: tree,
+ getChildren: item => item.children ?? [],
+ getRowKey: item => item.id,
+ expandedKeys,
+ setExpandedKeys,
+ });
+ const expansion = useTableRowExpansion(expansionConfig);
+ return <Table data={data} columns={cols} idKey="id" plugins={{expansion}} />;
+}`;
+ const output = await applyTransform(input);
+ const n = normalize(output);
+ expect(n).toContain('idKey: item => item.id');
+ expect(output).not.toContain('getRowKey');
+ });
+
+ it('swaps the useTableRowExpansion plugin call for useTableTreeData', async () => {
+ const input = `import {Table, useTableRowExpansion, useTableRowExpansionState} from '@astryxdesign/core';
+function C() {
+ const {data, expansionConfig} = useTableRowExpansionState({
+ baseData: tree,
+ getChildren: item => item.children ?? [],
+ getRowKey: item => item.id,
+ expandedKeys,
+ setExpandedKeys,
+ });
+ const expansion = useTableRowExpansion(expansionConfig);
+ return <Table data={data} columns={cols} idKey="id" plugins={{expansion}} />;
+}`;
+ const output = await applyTransform(input);
+ // The state hook now returns treeConfig; the plugin consumes it.
+ expect(output).toContain('treeConfig');
+ expect(output).toContain('useTableTreeData(treeConfig)');
+ expect(output).not.toMatch(/useTableRowExpansion\(/);
+ });
+
+ it('maps getIsItemExpandable to isItemExpandable', async () => {
+ const input = `import {Table, useTableRowExpansion, useTableRowExpansionState} from '@astryxdesign/core';
+function C() {
+ const {data, expansionConfig} = useTableRowExpansionState({
+ baseData: tree,
+ getChildren: item => item.children ?? [],
+ getRowKey: item => item.id,
+ getIsItemExpandable: item => item.type === 'folder',
+ expandedKeys,
+ setExpandedKeys,
+ });
+ const expansion = useTableRowExpansion(expansionConfig);
+ return <Table data={data} columns={cols} idKey="id" plugins={{expansion}} />;
+}`;
+ const output = await applyTransform(input);
+ expect(output).toContain('isItemExpandable');
+ expect(output).not.toContain('getIsItemExpandable');
+ });
+
+ it('leaves the new detail-panel usage (renderExpanded) untouched', async () => {
+ const input = `import {Table, useTableRowExpansion} from '@astryxdesign/core';
+function C() {
+ const expansion = useTableRowExpansion({
+ expandedKeys,
+ onToggle,
+ getRowKey: item => item.id,
+ renderExpanded: item => <Details item={item} />,
+ });
+ return <Table data={rows} columns={cols} idKey="id" plugins={{expansion}} />;
+}`;
+ const output = await applyTransform(input);
+ // No useTableRowExpansionState import here, and renderExpanded present:
+ // this is the new detail-panel API. The codemod must not touch it.
+ expect(output).toBe(input);
+ });
+
+ it('does not touch files that never imported the row-expansion hooks', async () => {
+ const input = `import {Table, useTableSelection} from '@astryxdesign/core';
+const t = <Table data={rows} columns={cols} idKey="id" />;`;
+ const output = await applyTransform(input);
+ expect(output).toBe(input);
+ });
+
+ it('supports the @xds/core import source alias', async () => {
+ const input = `import {Table, useTableRowExpansion, useTableRowExpansionState} from '@xds/core';
+function C() {
+ const {data, expansionConfig} = useTableRowExpansionState({
+ baseData: tree,
+ getChildren: item => item.children ?? [],
+ getRowKey: item => item.id,
+ expandedKeys,
+ setExpandedKeys,
+ });
+ const expansion = useTableRowExpansion(expansionConfig);
+ return <Table data={data} columns={cols} idKey="id" plugins={{expansion}} />;
+}`;
+ const output = await applyTransform(input);
+ expect(output).toContain('useTableTreeState');
+ expect(output).not.toContain('useTableRowExpansionState');
+ });
+
+ it('emits treeConfig as a shorthand (not treeConfig: treeConfig)', async () => {
+ const input = `import {Table, useTableRowExpansion, useTableRowExpansionState} from '@astryxdesign/core';
+function C() {
+ const {data, expansionConfig} = useTableRowExpansionState({
+ baseData: tree,
+ getChildren: item => item.children ?? [],
+ getRowKey: item => item.id,
+ expandedKeys,
+ setExpandedKeys,
+ });
+ const expansion = useTableRowExpansion(expansionConfig);
+ return <Table data={data} columns={cols} idKey="id" plugins={{expansion}} />;
+}`;
+ const output = await applyTransform(input);
+ expect(output).not.toContain('treeConfig: treeConfig');
+ expect(normalize(output)).toContain('visibleData: data');
+ });
+
+ it('leaves a migration guidance comment about expansion state', async () => {
+ const input = `import {Table, useTableRowExpansion, useTableRowExpansionState} from '@astryxdesign/core';
+function C() {
+ const {data, expansionConfig} = useTableRowExpansionState({
+ baseData: tree,
+ getChildren: item => item.children ?? [],
+ getRowKey: item => item.id,
+ expandedKeys,
+ setExpandedKeys,
+ });
+ const expansion = useTableRowExpansion(expansionConfig);
+ return <Table data={data} columns={cols} idKey="id" plugins={{expansion}} />;
+}`;
+ const output = await applyTransform(input);
+ expect(output).toContain('astryx-migration');
+ expect(output).toContain('defaultExpandedIds');
+ });
+});
diff --git a/packages/cli/assets/codemods/transforms/v0.3.0/index.mjs b/packages/cli/assets/codemods/transforms/v0.3.0/index.mjs
index ee9bb1dd20..f03548e1bc 100644
--- a/packages/cli/assets/codemods/transforms/v0.3.0/index.mjs
+++ b/packages/cli/assets/codemods/transforms/v0.3.0/index.mjs
@@ -40,6 +40,9 @@ import migrateLabCodeBlockImports, {
import removeThemeTransitionTokenImports, {
meta as removeThemeTransitionTokenImportsMeta,
} from './remove-theme-transition-token-imports.mjs';
+import migrateTableRowExpansionToTree, {
+ meta as migrateTableRowExpansionToTreeMeta,
+} from './migrate-table-rowexpansion-to-tree.mjs';
export default [
{
@@ -87,4 +90,9 @@ export default [
transform: removeThemeTransitionTokenImports,
meta: removeThemeTransitionTokenImportsMeta,
},
+ {
+ name: 'migrate-table-rowexpansion-to-tree',
+ transform: migrateTableRowExpansionToTree,
+ meta: migrateTableRowExpansionToTreeMeta,
+ },
];
diff --git a/packages/cli/assets/codemods/transforms/v0.3.0/migrate-table-rowexpansion-to-tree.mjs b/packages/cli/assets/codemods/transforms/v0.3.0/migrate-table-rowexpansion-to-tree.mjs
new file mode 100644
index 0000000000..93bc857823
--- /dev/null
+++ b/packages/cli/assets/codemods/transforms/v0.3.0/migrate-table-rowexpansion-to-tree.mjs
@@ -0,0 +1,214 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Codemod: Migrate tree-mode useTableRowExpansion to the tree plugin
+ *
+ * useTableRowExpansion is now a detail-panel plugin (renderExpanded). Its old
+ * tree mode (child rows that reuse the parent columns) moved to
+ * useTableTreeData + useTableTreeState, and useTableRowExpansionState was
+ * removed. This codemod rewrites the standard tree pattern:
+ *
+ * const {data, expansionConfig} = useTableRowExpansionState({
+ * baseData, getChildren, getRowKey, expandedKeys, setExpandedKeys,
+ * });
+ * const expansion = useTableRowExpansion(expansionConfig);
+ *
+ * into:
+ *
+ * const {visibleData: data, treeConfig} = useTableTreeState({
+ * data: baseData, childrenKey: 'children', idKey: getRowKey, ...
+ * });
+ * const expansion = useTableTreeData(treeConfig);
+ *
+ * Files that use the new detail-panel API (renderExpanded, no
+ * useTableRowExpansionState import) are left untouched.
+ */
+
+export const meta = {
+ title: 'Migrate tree-mode useTableRowExpansion to the tree plugin',
+ description:
+ 'Rewrites the removed useTableRowExpansionState tree pattern to useTableTreeState + useTableTreeData. Detail-panel usage (renderExpanded) is left untouched.',
+ pr: '#4612',
+};
+
+const IMPORT_SOURCES = new Set([
+ '@astryxdesign/core',
+ '@astryxdesign/core/Table',
+ '@xds/core',
+ '@xds/core/Table',
+]);
+
+/**
+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file
+ * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api
+ * @returns {string | null | undefined}
+ */
+export default function transformer(file, api) {
+ const j = api.jscodeshift;
+ const root = j(file.source);
+
+ // Only act on files importing the removed state hook. Detail-panel-only
+ // usage (useTableRowExpansion alone) is the new API and must be left alone.
+ let stateLocal = null;
+ let pluginLocal = null;
+ /** @type {any[]} */
+ const importPaths = [];
+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {
+ if (!IMPORT_SOURCES.has(path.node.source.value)) return;
+ for (const spec of path.node.specifiers ?? []) {
+ if (spec.type !== 'ImportSpecifier') continue;
+ if (spec.imported.name === 'useTableRowExpansionState') {
+ stateLocal = spec.local?.name ?? spec.imported.name;
+ importPaths.push(path);
+ }
+ if (spec.imported.name === 'useTableRowExpansion') {
+ pluginLocal = spec.local?.name ?? spec.imported.name;
+ }
+ }
+ });
+ if (!stateLocal) return undefined;
+
+ let hasChanges = false;
+
+ // --- 1. Rewrite the state hook call + its config object ---
+ root
+ .find(j.CallExpression, {callee: {name: stateLocal}})
+ .forEach((/** @type {any} */ path) => {
+ const arg = path.node.arguments[0];
+ if (!arg || arg.type !== 'ObjectExpression') return;
+
+ /** @type {any} */
+ let getChildrenValue = null;
+ const nextProps = [];
+ for (const prop of arg.properties) {
+ const key =
+ prop.key?.name ?? (prop.key?.value ? String(prop.key.value) : null);
+ if (key === 'baseData') {
+ nextProps.push(j.property('init', j.identifier('data'), prop.value));
+ } else if (key === 'getChildren') {
+ getChildrenValue = prop.value;
+ // childrenKey is emitted below (default 'children').
+ } else if (key === 'getRowKey') {
+ nextProps.push(j.property('init', j.identifier('idKey'), prop.value));
+ } else if (key === 'getIsItemExpandable') {
+ nextProps.push(
+ j.property('init', j.identifier('isItemExpandable'), prop.value),
+ );
+ } else if (key === 'expandedKeys' || key === 'setExpandedKeys') {
+ // The tree state hook owns expansion internally (uncontrolled) or
+ // via expandedIds/onExpandedIdsChange (controlled). The 1:1
+ // controlled mapping is not mechanical, so these are dropped and a
+ // guidance comment is attached below.
+ continue;
+ } else {
+ nextProps.push(prop);
+ }
+ }
+
+ // childrenKey: derive the literal when getChildren is the canonical
+ // `item => item.children` / `item.children ?? []`; otherwise keep the
+ // default and let the guidance comment flag it.
+ nextProps.splice(
+ 1,
+ 0,
+ j.property('init', j.identifier('childrenKey'), j.literal('children')),
+ );
+
+ arg.properties = nextProps;
+ path.node.callee = j.identifier('useTableTreeState');
+ hasChanges = true;
+
+ // Rename the destructured result: data -> visibleData (aliased back to
+ // the local name), expansionConfig -> treeConfig.
+ const declarator = path.parent.node;
+ if (
+ declarator.type === 'VariableDeclarator' &&
+ declarator.id.type === 'ObjectPattern'
+ ) {
+ for (const p of declarator.id.properties) {
+ if (p.type !== 'ObjectProperty' && p.type !== 'Property') continue;
+ const kName = p.key?.name;
+ if (kName === 'data') {
+ // {data} -> {visibleData: data}
+ p.key = j.identifier('visibleData');
+ if (p.shorthand) {
+ p.shorthand = false;
+ p.value = j.identifier('data');
+ }
+ } else if (kName === 'expansionConfig') {
+ // {expansionConfig} -> {treeConfig} (keep it shorthand).
+ p.key = j.identifier('treeConfig');
+ if (p.value?.type === 'Identifier') {
+ p.value = j.identifier('treeConfig');
+ p.shorthand = true;
+ }
+ }
+ }
+ }
+
+ // Attach a one-line migration note as a leading comment on the
+ // statement, so a human confirms the expansion-state wiring.
+ const stmt = path.parent.parent.node;
+ if (stmt && !stmt.comments) {
+ stmt.comments = [
+ j.commentLine(
+ ' astryx-migration: verify tree expansion state. useTableTreeState',
+ true,
+ false,
+ ),
+ j.commentLine(
+ ' is uncontrolled by default; pass defaultExpandedIds, or',
+ true,
+ false,
+ ),
+ j.commentLine(
+ ' expandedIds + onExpandedIdsChange for the old controlled set.',
+ true,
+ false,
+ ),
+ ];
+ }
+ void getChildrenValue;
+ });
+
+ // --- 2. Swap the plugin call: useTableRowExpansion(cfg) -> useTableTreeData(cfg) ---
+ if (pluginLocal) {
+ root
+ .find(j.CallExpression, {callee: {name: pluginLocal}})
+ .forEach((/** @type {any} */ path) => {
+ // Rename the argument identifier expansionConfig -> treeConfig.
+ const a = path.node.arguments[0];
+ if (a && a.type === 'Identifier' && a.name === 'expansionConfig') {
+ path.node.arguments[0] = j.identifier('treeConfig');
+ }
+ path.node.callee = j.identifier('useTableTreeData');
+ hasChanges = true;
+ });
+ }
+
+ if (!hasChanges) return undefined;
+
+ // --- 3. Fix imports: drop the removed hooks, add the tree hooks ---
+ for (const path of importPaths) {
+ const specs = path.node.specifiers.filter(
+ (/** @type {any} */ s) =>
+ !(
+ s.type === 'ImportSpecifier' &&
+ (s.imported.name === 'useTableRowExpansionState' ||
+ s.imported.name === 'useTableRowExpansion')
+ ),
+ );
+ const existing = new Set(
+ specs.map((/** @type {any} */ s) => s.imported?.name),
+ );
+ if (!existing.has('useTableTreeState')) {
+ specs.push(j.importSpecifier(j.identifier('useTableTreeState')));
+ }
+ if (!existing.has('useTableTreeData')) {
+ specs.push(j.importSpecifier(j.identifier('useTableTreeData')));
+ }
+ path.node.specifiers = specs;
+ }
+
+ return root.toSource({quote: 'single'});
+}