Skip to content

Commit 0b7d2c5

Browse files
committed
codemod -> wrap every fields with a <DataTable.Col source="xxx">
1 parent bf00c46 commit 0b7d2c5

File tree

1 file changed

+72
-3
lines changed

1 file changed

+72
-3
lines changed

packages/ra-core/codemods/replace-Datagrid-DataTable.ts

Lines changed: 72 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,13 @@ module.exports = (file, api: j.API) => {
99
return root.toSource();
1010
}
1111

12-
const continueAfterComponent = replaceComponent(root, j);
13-
if (!continueAfterComponent) {
12+
const continueAfterReplaceDatagrid = replaceDatagrid(root, j);
13+
if (!continueAfterReplaceDatagrid) {
14+
return root.toSource();
15+
}
16+
17+
const continueAfterWrap = wrapChildren(root, j);
18+
if (!continueAfterWrap) {
1419
return root.toSource();
1520
}
1621

@@ -58,7 +63,7 @@ const replaceImport = (root, j) => {
5863
return true;
5964
};
6065

61-
const replaceComponent = (root, j) => {
66+
const replaceDatagrid = (root, j) => {
6267
// Find all instances of Datagrid
6368
const datagridComponents = root.find(j.JSXElement, {
6469
openingElement: {
@@ -88,3 +93,67 @@ const replaceComponent = (root, j) => {
8893

8994
return true;
9095
};
96+
97+
const wrapChildren = (root, j) => {
98+
// Find all instances of Datagrid
99+
const datagridComponents = root.find(j.JSXElement, {
100+
openingElement: {
101+
name: {
102+
type: 'JSXIdentifier',
103+
name: 'DataTable',
104+
},
105+
},
106+
});
107+
if (!datagridComponents.length) {
108+
return false;
109+
}
110+
111+
// For each DataTable component, wrap its children in DataTable.Col
112+
datagridComponents.forEach(dataTableComponent => {
113+
const children = dataTableComponent.value.children.filter(child =>
114+
j.JSXElement.check(child)
115+
);
116+
children.forEach(child => {
117+
wrapChild(root, j, child);
118+
});
119+
});
120+
};
121+
122+
const wrapChild = (root, j, child) => {
123+
// Wrap the child in a DataTable.Col component
124+
const wrappedChild = j.jsxElement(
125+
j.jsxOpeningElement(
126+
j.jsxIdentifier('DataTable.Col'),
127+
[
128+
j.jsxAttribute(
129+
j.jsxIdentifier('source'),
130+
j.stringLiteral(
131+
child.openingElement.attributes.find(
132+
attr =>
133+
j.JSXAttribute.check(attr) &&
134+
attr.name.name === 'source'
135+
)?.value?.value || ''
136+
)
137+
),
138+
],
139+
false
140+
),
141+
j.jsxClosingElement(j.jsxIdentifier('DataTable.Col')),
142+
[j.jsxText('\n'), child, j.jsxText('\n')]
143+
);
144+
145+
// Replace the original child with the wrapped child
146+
root.find(j.JSXElement, {
147+
openingElement: {
148+
name: {
149+
type: 'JSXIdentifier',
150+
name: 'DataTable',
151+
},
152+
},
153+
}).forEach(dataTableComponent => {
154+
dataTableComponent.value.children =
155+
dataTableComponent.value.children.map(c =>
156+
c === child ? wrappedChild : c
157+
);
158+
});
159+
};

0 commit comments

Comments
 (0)