@comet/admin-generator 8.17.1 → 9.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/bin/admin-generator.mjs +3 -0
  2. package/dist/adminGenerator.d.mts +1 -0
  3. package/dist/adminGenerator.mjs +4441 -0
  4. package/dist/index.d.mts +344 -0
  5. package/dist/index.mjs +4440 -0
  6. package/package.json +31 -21
  7. package/bin/admin-generator.js +0 -8
  8. package/lib/adminGenerator.d.ts +0 -1
  9. package/lib/adminGenerator.js +0 -8
  10. package/lib/commands/generate/config/parseConfig.d.ts +0 -1
  11. package/lib/commands/generate/config/parseConfig.js +0 -72
  12. package/lib/commands/generate/config/transformConfig.d.ts +0 -7
  13. package/lib/commands/generate/config/transformConfig.js +0 -264
  14. package/lib/commands/generate/generate-command.d.ts +0 -340
  15. package/lib/commands/generate/generate-command.js +0 -112
  16. package/lib/commands/generate/generateForm/asyncSelect/generateAsyncSelect.d.ts +0 -26
  17. package/lib/commands/generate/generateForm/asyncSelect/generateAsyncSelect.js +0 -364
  18. package/lib/commands/generate/generateForm/extractErrorEnums.d.ts +0 -16
  19. package/lib/commands/generate/generateForm/extractErrorEnums.js +0 -100
  20. package/lib/commands/generate/generateForm/flatFormFieldsFromFormConfig.d.ts +0 -2
  21. package/lib/commands/generate/generateForm/flatFormFieldsFromFormConfig.js +0 -22
  22. package/lib/commands/generate/generateForm/formField/findIntrospectionFieldType.d.ts +0 -6
  23. package/lib/commands/generate/generateForm/formField/findIntrospectionFieldType.js +0 -22
  24. package/lib/commands/generate/generateForm/formField/options.d.ts +0 -24
  25. package/lib/commands/generate/generateForm/formField/options.js +0 -85
  26. package/lib/commands/generate/generateForm/generateComponentFormField.d.ts +0 -5
  27. package/lib/commands/generate/generateForm/generateComponentFormField.js +0 -22
  28. package/lib/commands/generate/generateForm/generateErrorHandling.d.ts +0 -8
  29. package/lib/commands/generate/generateForm/generateErrorHandling.js +0 -24
  30. package/lib/commands/generate/generateForm/generateErrorMessages.d.ts +0 -11
  31. package/lib/commands/generate/generateForm/generateErrorMessages.js +0 -28
  32. package/lib/commands/generate/generateForm/generateFields.d.ts +0 -42
  33. package/lib/commands/generate/generateForm/generateFields.js +0 -87
  34. package/lib/commands/generate/generateForm/generateForm.d.ts +0 -14
  35. package/lib/commands/generate/generateForm/generateForm.js +0 -565
  36. package/lib/commands/generate/generateForm/generateFormField.d.ts +0 -12
  37. package/lib/commands/generate/generateForm/generateFormField.js +0 -368
  38. package/lib/commands/generate/generateForm/generateFormLayout.d.ts +0 -12
  39. package/lib/commands/generate/generateForm/generateFormLayout.js +0 -154
  40. package/lib/commands/generate/generateForm/generateFormValues.d.ts +0 -40
  41. package/lib/commands/generate/generateForm/generateFormValues.js +0 -219
  42. package/lib/commands/generate/generateForm/generateFragmentByFormFragmentFields.d.ts +0 -11
  43. package/lib/commands/generate/generateForm/generateFragmentByFormFragmentFields.js +0 -29
  44. package/lib/commands/generate/generateForm/getForwardedGqlArgs.d.ts +0 -18
  45. package/lib/commands/generate/generateForm/getForwardedGqlArgs.js +0 -79
  46. package/lib/commands/generate/generateGrid/detectMuiXVersion.d.ts +0 -5
  47. package/lib/commands/generate/generateGrid/detectMuiXVersion.js +0 -32
  48. package/lib/commands/generate/generateGrid/findInputObjectType.d.ts +0 -2
  49. package/lib/commands/generate/generateGrid/findInputObjectType.js +0 -15
  50. package/lib/commands/generate/generateGrid/generateGqlFieldList.d.ts +0 -6
  51. package/lib/commands/generate/generateGrid/generateGqlFieldList.js +0 -56
  52. package/lib/commands/generate/generateGrid/generateGrid.d.ts +0 -16
  53. package/lib/commands/generate/generateGrid/generateGrid.js +0 -1017
  54. package/lib/commands/generate/generateGrid/generateGridToolbar.d.ts +0 -15
  55. package/lib/commands/generate/generateGrid/generateGridToolbar.js +0 -90
  56. package/lib/commands/generate/generateGrid/getForwardedGqlArgs.d.ts +0 -13
  57. package/lib/commands/generate/generateGrid/getForwardedGqlArgs.js +0 -59
  58. package/lib/commands/generate/generateGrid/getPropsForFilterProp.d.ts +0 -14
  59. package/lib/commands/generate/generateGrid/getPropsForFilterProp.js +0 -13
  60. package/lib/commands/generate/generateGrid/usableFields.d.ts +0 -14
  61. package/lib/commands/generate/generateGrid/usableFields.js +0 -3
  62. package/lib/commands/generate/utils/camelCaseToHumanReadable.d.ts +0 -1
  63. package/lib/commands/generate/utils/camelCaseToHumanReadable.js +0 -7
  64. package/lib/commands/generate/utils/columnVisibility.d.ts +0 -6
  65. package/lib/commands/generate/utils/columnVisibility.js +0 -2
  66. package/lib/commands/generate/utils/convertConfigImport.d.ts +0 -6
  67. package/lib/commands/generate/utils/convertConfigImport.js +0 -14
  68. package/lib/commands/generate/utils/findMutationType.d.ts +0 -3
  69. package/lib/commands/generate/utils/findMutationType.js +0 -18
  70. package/lib/commands/generate/utils/findQueryType.d.ts +0 -2
  71. package/lib/commands/generate/utils/findQueryType.js +0 -18
  72. package/lib/commands/generate/utils/findRootBlocks.d.ts +0 -8
  73. package/lib/commands/generate/utils/findRootBlocks.js +0 -66
  74. package/lib/commands/generate/utils/generateGqlOperation.d.ts +0 -12
  75. package/lib/commands/generate/utils/generateGqlOperation.js +0 -87
  76. package/lib/commands/generate/utils/generateImportsCode.d.ts +0 -6
  77. package/lib/commands/generate/utils/generateImportsCode.js +0 -31
  78. package/lib/commands/generate/utils/intl.d.ts +0 -20
  79. package/lib/commands/generate/utils/intl.js +0 -44
  80. package/lib/commands/generate/utils/isFieldOptional.d.ts +0 -7
  81. package/lib/commands/generate/utils/isFieldOptional.js +0 -21
  82. package/lib/commands/generate/utils/runtimeTypeGuards.d.ts +0 -20
  83. package/lib/commands/generate/utils/runtimeTypeGuards.js +0 -22
  84. package/lib/commands/generate/utils/writeGenerated.d.ts +0 -1
  85. package/lib/commands/generate/utils/writeGenerated.js +0 -123
  86. package/lib/index.d.ts +0 -2
  87. package/lib/index.js +0 -6
@@ -1,1017 +0,0 @@
1
- "use strict";
2
- var __rest = (this && this.__rest) || function (s, e) {
3
- var t = {};
4
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
- t[p] = s[p];
6
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
- t[p[i]] = s[p[i]];
10
- }
11
- return t;
12
- };
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.generateGrid = generateGrid;
15
- const pluralize_1 = require("pluralize");
16
- const camelCaseToHumanReadable_1 = require("../utils/camelCaseToHumanReadable");
17
- const convertConfigImport_1 = require("../utils/convertConfigImport");
18
- const findMutationType_1 = require("../utils/findMutationType");
19
- const findQueryType_1 = require("../utils/findQueryType");
20
- const findRootBlocks_1 = require("../utils/findRootBlocks");
21
- const generateGqlOperation_1 = require("../utils/generateGqlOperation");
22
- const generateImportsCode_1 = require("../utils/generateImportsCode");
23
- const intl_1 = require("../utils/intl");
24
- const runtimeTypeGuards_1 = require("../utils/runtimeTypeGuards");
25
- const detectMuiXVersion_1 = require("./detectMuiXVersion");
26
- const findInputObjectType_1 = require("./findInputObjectType");
27
- const generateGqlFieldList_1 = require("./generateGqlFieldList");
28
- const generateGridToolbar_1 = require("./generateGridToolbar");
29
- const getForwardedGqlArgs_1 = require("./getForwardedGqlArgs");
30
- const getPropsForFilterProp_1 = require("./getPropsForFilterProp");
31
- function tsCodeRecordToString(object, spreadAbove) {
32
- return `{${spreadAbove ? `${spreadAbove}` : ""}${Object.entries(object)
33
- .filter(([key, value]) => value !== undefined)
34
- .map(([key, value]) => `${key}: ${value},`)
35
- .join("\n")}}`;
36
- }
37
- function generateGridPropsCode(props) {
38
- if (!props.length)
39
- return { gridPropsTypeCode: "", gridPropsParamsCode: "" };
40
- const uniqueProps = props.reduce((acc, prop) => {
41
- const propWithSameName = acc.find((filteredProps) => filteredProps.name === prop.name);
42
- if (propWithSameName) {
43
- if (propWithSameName.type === prop.type) {
44
- // ignore prop, it's a duplicate. e.g. same prop for mutation and for query
45
- }
46
- else {
47
- throw new Error(`Prop ${prop.name} with same name but different types (${propWithSameName.type} and ${prop.type}) detected.`);
48
- }
49
- }
50
- else {
51
- acc.push(prop);
52
- }
53
- return acc;
54
- }, []);
55
- return {
56
- gridPropsTypeCode: `type Props = {
57
- ${uniqueProps
58
- .map((prop) => `${prop.type.includes("any")
59
- ? `// eslint-disable-next-line @typescript-eslint/no-explicit-any
60
- `
61
- : ``}${prop.name}${prop.optional ? `?` : ``}: ${prop.type};`)
62
- .join("\n")}
63
- };`,
64
- gridPropsParamsCode: `{${uniqueProps.map((prop) => `${prop.name} ${prop.defaultValue ? `= ${prop.defaultValue}` : ""}`).join(", ")}}: Props`,
65
- };
66
- }
67
- const getSortByValue = (sortBy) => {
68
- if (Array.isArray(sortBy)) {
69
- return `[${sortBy.map((i) => `"${i}"`).join(", ")}]`;
70
- }
71
- if (typeof sortBy === "string") {
72
- return `"${sortBy}"`;
73
- }
74
- return sortBy;
75
- };
76
- const getValueOptionsLabelData = (messageId, label) => {
77
- if (typeof label === "string" || (0, intl_1.isFormattedMessageElement)(label)) {
78
- return {
79
- textLabel: (0, intl_1.generateFormattedMessage)({
80
- config: label,
81
- id: messageId,
82
- type: "intlCall",
83
- }),
84
- };
85
- }
86
- const textLabelParts = [];
87
- const gridCellContentProps = {};
88
- if ("primaryText" in label && label.primaryText) {
89
- const primaryMessageId = `${messageId}.primary`;
90
- textLabelParts.push((0, intl_1.generateFormattedMessage)({
91
- config: label.primaryText,
92
- id: primaryMessageId,
93
- type: "intlCall",
94
- }));
95
- gridCellContentProps.primaryText = (0, intl_1.generateFormattedMessage)({
96
- config: label.primaryText,
97
- id: primaryMessageId,
98
- type: "jsx",
99
- });
100
- }
101
- if ("secondaryText" in label && label.secondaryText) {
102
- const secondaryMessageId = `${messageId}.secondary`;
103
- textLabelParts.push((0, intl_1.generateFormattedMessage)({
104
- config: label.secondaryText,
105
- id: secondaryMessageId,
106
- type: "intlCall",
107
- }));
108
- gridCellContentProps.secondaryText = (0, intl_1.generateFormattedMessage)({
109
- config: label.secondaryText,
110
- id: secondaryMessageId,
111
- type: "jsx",
112
- });
113
- }
114
- if ("icon" in label) {
115
- if (typeof label.icon === "string") {
116
- gridCellContentProps.icon = `<${label.icon}Icon />`;
117
- }
118
- else if (typeof label.icon === "object") {
119
- if ("import" in label.icon) {
120
- gridCellContentProps.icon = `<${label.icon.name} />`;
121
- }
122
- else {
123
- const _a = label.icon, { name } = _a, iconProps = __rest(_a, ["name"]);
124
- gridCellContentProps.icon = `<${name}Icon
125
- ${Object.entries(iconProps)
126
- .map(([key, value]) => `${key}="${value}"`)
127
- .join("\n")}
128
- />`;
129
- }
130
- }
131
- }
132
- const gridCellContent = `<GridCellContent
133
- ${Object.entries(gridCellContentProps)
134
- .map(([key, value]) => `${key}={${value}}`)
135
- .join("\n")}
136
- />`;
137
- return {
138
- textLabel: textLabelParts.join(" + ' ' + "),
139
- gridCellContent,
140
- };
141
- };
142
- function queryHasPaging(gridQueryType, gqlIntrospection) {
143
- // Unwrap NON_NULL to get the named return type
144
- let returnType = gridQueryType.type;
145
- if (returnType.kind === "NON_NULL") {
146
- returnType = returnType.ofType;
147
- }
148
- // If the return type is a LIST, there's no pagination wrapper
149
- if (returnType.kind === "LIST") {
150
- return false;
151
- }
152
- // If it's a named OBJECT type, check for nodes and totalCount fields
153
- if (returnType.kind === "OBJECT") {
154
- const typeName = returnType.name;
155
- const objectType = gqlIntrospection.__schema.types.find((type) => type.kind === "OBJECT" && type.name === typeName);
156
- if (objectType) {
157
- const hasNodes = objectType.fields.some((f) => f.name === "nodes");
158
- const hasTotalCount = objectType.fields.some((f) => f.name === "totalCount");
159
- return hasNodes && hasTotalCount;
160
- }
161
- }
162
- return false;
163
- }
164
- function generateGrid({ exportName, baseOutputFilename, targetDirectory, gqlIntrospection, }, config) {
165
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
166
- const gqlType = config.gqlType;
167
- if (!gqlType) {
168
- throw new Error("gqlType is required in grid config");
169
- }
170
- const muiXGridVariant = (0, detectMuiXVersion_1.detectMuiXGridVariant)();
171
- const gqlTypePlural = (0, pluralize_1.plural)(gqlType);
172
- //const title = config.title ?? camelCaseToHumanReadable(gqlType);
173
- const instanceGqlType = gqlType[0].toLowerCase() + gqlType.substring(1);
174
- const instanceGqlTypePlural = gqlTypePlural[0].toLowerCase() + gqlTypePlural.substring(1);
175
- const gridQuery = config.query ? config.query : instanceGqlType != instanceGqlTypePlural ? instanceGqlTypePlural : `${instanceGqlTypePlural}List`;
176
- const gqlDocuments = {};
177
- const imports = [
178
- { name: "FormattedMessage", importPath: "react-intl" },
179
- { name: "FormattedNumber", importPath: "react-intl" },
180
- { name: "useIntl", importPath: "react-intl" },
181
- { name: "ReactNode", importPath: "react" },
182
- { name: "gql", importPath: "@apollo/client" },
183
- { name: "useApolloClient", importPath: "@apollo/client" },
184
- { name: "useQuery", importPath: "@apollo/client" },
185
- { name: "Button", importPath: "@comet/admin" },
186
- { name: "CrudContextMenu", importPath: "@comet/admin" },
187
- { name: "CrudMoreActionsMenu", importPath: "@comet/admin" },
188
- { name: "DataGridToolbar", importPath: "@comet/admin" },
189
- { name: "ExportApi", importPath: "@comet/admin" },
190
- { name: "filterByFragment", importPath: "@comet/admin" },
191
- { name: "GridFilterButton", importPath: "@comet/admin" },
192
- { name: "GridCellContent", importPath: "@comet/admin" },
193
- { name: "GridColDef", importPath: "@comet/admin" },
194
- { name: "dataGridDateTimeColumn", importPath: "@comet/admin" },
195
- { name: "dataGridDateColumn", importPath: "@comet/admin" },
196
- { name: "dataGridIdColumn", importPath: "@comet/admin" },
197
- { name: "dataGridManyToManyColumn", importPath: "@comet/admin" },
198
- { name: "dataGridOneToManyColumn", importPath: "@comet/admin" },
199
- { name: "renderStaticSelectCell", importPath: "@comet/admin" },
200
- { name: "messages", importPath: "@comet/admin" },
201
- { name: "muiGridFilterToGql", importPath: "@comet/admin" },
202
- { name: "StackLink", importPath: "@comet/admin" },
203
- { name: "useStackSwitchApi", importPath: "@comet/admin" },
204
- { name: "FillSpace", importPath: "@comet/admin" },
205
- { name: "Tooltip", importPath: "@comet/admin" },
206
- { name: "useBufferedRowCount", importPath: "@comet/admin" },
207
- { name: "useDataGridExcelExport", importPath: "@comet/admin" },
208
- { name: "usePersistentColumnState", importPath: "@comet/admin" },
209
- { name: "BlockPreviewContent", importPath: "@comet/cms-admin" },
210
- { name: "Alert", importPath: "@mui/material" },
211
- { name: "Box", importPath: "@mui/material" },
212
- { name: "IconButton", importPath: "@mui/material" },
213
- { name: "Typography", importPath: "@mui/material" },
214
- { name: "useTheme", importPath: "@mui/material" },
215
- { name: "Menu", importPath: "@mui/material" },
216
- { name: "MenuItem", importPath: "@mui/material" },
217
- { name: "ListItemIcon", importPath: "@mui/material" },
218
- { name: "ListItemText", importPath: "@mui/material" },
219
- { name: "CircularProgress", importPath: "@mui/material" },
220
- { name: muiXGridVariant.gridComponent, importPath: muiXGridVariant.package },
221
- { name: `${muiXGridVariant.gridComponent}Props`, importPath: muiXGridVariant.package },
222
- { name: "GridLogicOperator", importPath: muiXGridVariant.package },
223
- { name: "GridRenderCellParams", importPath: muiXGridVariant.package },
224
- { name: "GridSlotsComponent", importPath: muiXGridVariant.package },
225
- { name: "GridToolbarProps", importPath: muiXGridVariant.package },
226
- { name: "GridColumnHeaderTitle", importPath: muiXGridVariant.package },
227
- { name: "GridToolbarQuickFilter", importPath: muiXGridVariant.package },
228
- { name: "GridRowOrderChangeParams", importPath: muiXGridVariant.package },
229
- { name: "useMemo", importPath: "react" },
230
- ];
231
- const iconsToImport = ["Add", "Edit", "Info", "Excel"];
232
- const props = [];
233
- const fieldList = (0, generateGqlFieldList_1.generateGqlFieldList)({ columns: config.columns });
234
- // all root blocks including those we don't have columns for (required for copy/paste)
235
- // this is not configured in the grid config, it's just an heuristics
236
- const rootBlocks = (0, findRootBlocks_1.findRootBlocks)({ gqlType, targetDirectory }, gqlIntrospection);
237
- const rootBlockColumns = config.columns.filter((column) => column.type == "block");
238
- rootBlockColumns.forEach((field) => {
239
- if (rootBlocks[String(field.name)]) {
240
- // update rootBlocks if they are also used in columns
241
- const block = field.block;
242
- if ((0, runtimeTypeGuards_1.isGeneratorConfigImport)(block)) {
243
- rootBlocks[String(field.name)].import = block.import;
244
- rootBlocks[String(field.name)].name = block.name;
245
- }
246
- }
247
- });
248
- Object.values(rootBlocks).forEach((block) => {
249
- if ((0, runtimeTypeGuards_1.isGeneratorConfigImport)(block)) {
250
- imports.push((0, convertConfigImport_1.convertConfigImport)(block));
251
- }
252
- });
253
- const gridQueryType = (0, findQueryType_1.findQueryTypeOrThrow)(gridQuery, gqlIntrospection);
254
- const hasPaging = queryHasPaging(gridQueryType, gqlIntrospection);
255
- if (hasPaging) {
256
- imports.push({ name: "useDataGridRemote", importPath: "@comet/admin" });
257
- }
258
- else {
259
- imports.push({ name: "useDataGridUrlState", importPath: "@comet/admin" });
260
- }
261
- const updateMutationType = (0, findMutationType_1.findMutationType)(`update${gqlType}`, gqlIntrospection);
262
- const hasDeleteMutation = !!(0, findMutationType_1.findMutationType)(`delete${gqlType}`, gqlIntrospection);
263
- const hasUpdateMutation = !!updateMutationType;
264
- const allowAdding = (typeof config.add === "undefined" || config.add === true) && !config.readOnly;
265
- const allowEditing = (typeof config.edit === "undefined" || config.edit === true) && !config.readOnly;
266
- const allowDeleting = (typeof config.delete === "undefined" || config.delete === true) && !config.readOnly && hasDeleteMutation;
267
- const allowRowReordering = typeof ((_a = config.rowReordering) === null || _a === void 0 ? void 0 : _a.enabled) !== "undefined" && ((_b = config.rowReordering) === null || _b === void 0 ? void 0 : _b.enabled) && hasUpdateMutation;
268
- const updateInputArg = updateMutationType === null || updateMutationType === void 0 ? void 0 : updateMutationType.args.find((arg) => arg.name === "input");
269
- if (allowRowReordering && updateInputArg) {
270
- const inputType = (0, findInputObjectType_1.findInputObjectType)(updateInputArg, gqlIntrospection);
271
- if (!inputType)
272
- throw new Error("Can't find update input type");
273
- if (!((_c = inputType.inputFields) === null || _c === void 0 ? void 0 : _c.find((field) => field.name === "position"))) {
274
- throw new Error("Position field is needed when using 'rowReordering'");
275
- }
276
- }
277
- const hasRowReorderingOnDragField = allowRowReordering && typeof ((_d = config.rowReordering) === null || _d === void 0 ? void 0 : _d.dragPreviewField) !== "undefined";
278
- if (hasRowReorderingOnDragField &&
279
- !config.columns.find((column) => { var _a; return column.type !== "actions" && (column === null || column === void 0 ? void 0 : column.name) === ((_a = config.rowReordering) === null || _a === void 0 ? void 0 : _a.dragPreviewField); })) {
280
- throw new Error(`rowReorderingOnDragField '${(_e = config.rowReordering) === null || _e === void 0 ? void 0 : _e.dragPreviewField}' must exist in columns`);
281
- }
282
- const forwardRowAction = allowEditing && config.rowActionProp;
283
- const showActionsColumn = allowEditing || allowDeleting;
284
- const showCrudContextMenuInActionsColumn = allowDeleting;
285
- const showEditInActionsColumn = allowEditing && !forwardRowAction;
286
- const defaultActionsColumnWidth = getDefaultActionsColumnWidth(showCrudContextMenuInActionsColumn, showEditInActionsColumn);
287
- let useScopeFromContext = false;
288
- const gqlArgs = [];
289
- {
290
- const forwardedArgs = (0, getForwardedGqlArgs_1.getForwardedGqlArgs)([gridQueryType]);
291
- for (const forwardedArg of forwardedArgs) {
292
- imports.push(...forwardedArg.imports);
293
- if (forwardedArg.gqlArg.name === "scope" && !config.scopeAsProp) {
294
- useScopeFromContext = true;
295
- gqlArgs.push(forwardedArg.gqlArg);
296
- }
297
- else {
298
- props.push(forwardedArg.prop);
299
- gqlArgs.push(forwardedArg.gqlArg);
300
- }
301
- }
302
- }
303
- if (useScopeFromContext) {
304
- imports.push({ name: "useContentScope", importPath: "@comet/cms-admin" });
305
- }
306
- const renderToolbar = (_f = config.toolbar) !== null && _f !== void 0 ? _f : true;
307
- const filterArg = gridQueryType.args.find((arg) => arg.name === "filter");
308
- const hasFilter = !!filterArg && renderToolbar && !allowRowReordering;
309
- let hasFilterProp = false;
310
- let filterFields = [];
311
- if (filterArg) {
312
- const filterType = (0, findInputObjectType_1.findInputObjectType)(filterArg, gqlIntrospection);
313
- if (!filterType)
314
- throw new Error("Can't find filter type");
315
- filterFields = filterType.inputFields.map((f) => f.name.replace(/_/g, "."));
316
- const { hasFilterProp: tempHasFilterProp, imports: filterPropImports, props: filterPropProps, } = (0, getPropsForFilterProp_1.getPropsForFilterProp)({ config, filterType });
317
- hasFilterProp = tempHasFilterProp;
318
- imports.push(...filterPropImports);
319
- props.push(...filterPropProps);
320
- }
321
- const forwardToolbarAction = allowAdding && renderToolbar && config.toolbarActionProp;
322
- if (forwardToolbarAction) {
323
- props.push({ name: "toolbarAction", type: "ReactNode", optional: true });
324
- }
325
- const sortArg = gridQueryType.args.find((arg) => arg.name === "sort");
326
- const hasSort = !!sortArg;
327
- let sortFields = [];
328
- if (sortArg) {
329
- imports.push({ name: "muiGridSortToGql", importPath: "@comet/admin" });
330
- let sortArgType = sortArg.type;
331
- if (sortArgType.kind === "NON_NULL") {
332
- sortArgType = sortArgType.ofType;
333
- }
334
- if (sortArgType.kind !== "LIST") {
335
- throw new Error("Sort argument must be LIST");
336
- }
337
- if (sortArgType.ofType.kind !== "NON_NULL") {
338
- throw new Error("Sort argument must be LIST->NON_NULL");
339
- }
340
- if (sortArgType.ofType.ofType.kind !== "INPUT_OBJECT") {
341
- throw new Error("Sort argument must be LIST->NON_NULL->INPUT_OBJECT");
342
- }
343
- const sortTypeName = sortArgType.ofType.ofType.name;
344
- const sortType = gqlIntrospection.__schema.types.find((type) => type.kind === "INPUT_OBJECT" && type.name === sortTypeName);
345
- if (!sortType)
346
- throw new Error("Can't find sort type");
347
- const sortField = sortType.inputFields.find((i) => i.name == "field");
348
- if (!sortField)
349
- throw new Error("Can't find sortFieldName");
350
- if (sortField.type.kind !== "NON_NULL")
351
- throw new Error("sortField must be NON_NULL");
352
- if (sortField.type.ofType.kind != "ENUM")
353
- throw new Error("sortField must be NON_NULL->ENUM");
354
- const sortFieldEnumName = sortField.type.ofType.name;
355
- const sortInputEnum = gqlIntrospection.__schema.types.find((type) => type.kind === "ENUM" && type.name === sortFieldEnumName);
356
- if (!sortInputEnum)
357
- throw new Error("Can't find sortInputEnum");
358
- sortFields = sortInputEnum.enumValues.map((v) => v.name.replace(/_/g, "."));
359
- if (allowRowReordering && !sortFields.includes("position")) {
360
- throw new Error("Sort argument must include 'position' field for row reordering");
361
- }
362
- }
363
- const hasSearch = gridQueryType.args.some((arg) => arg.name === "search") && !allowRowReordering;
364
- const schemaEntity = gqlIntrospection.__schema.types.find((type) => type.kind === "OBJECT" && type.name === gqlType);
365
- if (!schemaEntity)
366
- throw new Error("didn't find entity in schema types");
367
- const actionsColumnConfig = config.columns.find((column) => column.type === "actions");
368
- const _l = actionsColumnConfig !== null && actionsColumnConfig !== void 0 ? actionsColumnConfig : {}, { component: actionsColumnComponent, type: actionsColumnType, headerName: actionsColumnHeaderName, pinned: actionsColumnPinned = "right", width: actionsColumnWidth = defaultActionsColumnWidth, visible: actionsColumnVisible = undefined,
369
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
370
- queryFields: actionsColumnQueryFields = [] } = _l, // not needed here, but needs to be removed from restActionsColumnConfig because it's directly used in to generate component props in tsCodeRecordToString
371
- restActionsColumnConfig = __rest(_l, ["component", "type", "headerName", "pinned", "width", "visible", "queryFields"]);
372
- if (actionsColumnComponent) {
373
- if (!(0, runtimeTypeGuards_1.isGeneratorConfigImport)(actionsColumnComponent)) {
374
- throw new Error("Unsupported actionsColumnComponent, only imports are supported");
375
- }
376
- imports.push((0, convertConfigImport_1.convertConfigImport)(actionsColumnComponent));
377
- }
378
- const gridNeedsTheme = config.columns.some((column) => typeof column.visible === "string");
379
- const gridColumnFields = config.columns.filter((column) => column.type !== "actions").map((column) => {
380
- var _a;
381
- const type = column.type;
382
- const name = String(column.name);
383
- let gridColumnType = undefined;
384
- let renderCell = undefined;
385
- let valueFormatter = undefined;
386
- let valueGetter = name.includes(".") ? `(params, row) => row.${name.replace(/\./g, "?.")}` : undefined;
387
- let gridType;
388
- let filterOperators;
389
- if (column.type != "virtual" && column.filterOperators) {
390
- if ((0, runtimeTypeGuards_1.isGeneratorConfigImport)(column.filterOperators)) {
391
- imports.push((0, convertConfigImport_1.convertConfigImport)(column.filterOperators));
392
- filterOperators = column.filterOperators.name;
393
- }
394
- else {
395
- throw new Error("Unsupported filterOperators, only imports are supported for now");
396
- }
397
- }
398
- if (type == "dateTime") {
399
- gridColumnType = "...dataGridDateTimeColumn,";
400
- valueGetter = name.includes(".")
401
- ? `(params, row) => row.${name.replace(/\./g, "?.")} && new Date(row.${name.replace(/\./g, "?.")})`
402
- : undefined;
403
- }
404
- else if (type == "date") {
405
- gridColumnType = "...dataGridDateColumn,";
406
- valueGetter = name.includes(".")
407
- ? `(params, row) => row.${name.replace(/\./g, "?.")} && new Date(row.${name.replace(/\./g, "?.")})`
408
- : undefined;
409
- }
410
- else if (type == "number") {
411
- gridType = "number";
412
- const defaultDecimals = column.currency ? 2 : 0;
413
- const decimals = typeof column.decimals === "number" ? column.decimals : defaultDecimals;
414
- const currencyProps = column.currency ? `style="currency" currency="${column.currency}"` : "";
415
- renderCell = `({ value }) => {
416
- return (typeof value === "number") ? <FormattedNumber value={value} ${currencyProps} minimumFractionDigits={${decimals}} maximumFractionDigits={${decimals}} /> : "";
417
- }`;
418
- }
419
- else if (type == "boolean") {
420
- gridType = "boolean";
421
- }
422
- else if (column.type == "block") {
423
- renderCell = `(params) => {
424
- return <BlockPreviewContent block={${column.block.name}} input={params.row.${name}} />;
425
- }`;
426
- }
427
- else if (type == "staticSelect") {
428
- valueFormatter = `(value, row) => row.${name}?.toString()`;
429
- const introspectionField = schemaEntity.fields.find((field) => field.name === name);
430
- if (!introspectionField)
431
- throw new Error(`didn't find field ${name} in gql introspection type ${gqlType}`);
432
- const introspectionFieldType = introspectionField.type.kind === "NON_NULL" ? introspectionField.type.ofType : introspectionField.type;
433
- const enumType = gqlIntrospection.__schema.types.find((t) => t.kind === "ENUM" && t.name === introspectionFieldType.name);
434
- (_a = column.values) === null || _a === void 0 ? void 0 : _a.forEach((value) => {
435
- var _a;
436
- if (typeof value === "object" && typeof value.label === "object" && "icon" in value.label) {
437
- if (typeof value.label.icon === "string") {
438
- iconsToImport.push(value.label.icon);
439
- }
440
- else if (typeof ((_a = value.label.icon) === null || _a === void 0 ? void 0 : _a.name) === "string") {
441
- if ((0, runtimeTypeGuards_1.isGeneratorConfigImport)(value.label.icon)) {
442
- imports.push((0, convertConfigImport_1.convertConfigImport)(value.label.icon));
443
- }
444
- else {
445
- iconsToImport.push(value.label.icon.name);
446
- }
447
- }
448
- }
449
- });
450
- let columnValues = [];
451
- if (column.values) {
452
- columnValues = column.values;
453
- }
454
- else if (enumType) {
455
- columnValues = enumType.enumValues.map((i) => i.name);
456
- }
457
- else {
458
- throw new Error(`Enum type not found`);
459
- }
460
- const values = columnValues.map((value) => {
461
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
462
- return {
463
- value,
464
- label: (0, camelCaseToHumanReadable_1.camelCaseToHumanReadable)(value.toString()),
465
- };
466
- }
467
- else {
468
- return value;
469
- }
470
- });
471
- const valueOptions = `[${values
472
- .map(({ value, label }) => {
473
- const labelData = getValueOptionsLabelData(`${instanceGqlType}.${name}.${value.toString().charAt(0).toLowerCase() + value.toString().slice(1)}`, label);
474
- return `{
475
- value: ${JSON.stringify(value)},
476
- label: ${labelData.textLabel},
477
- ${labelData.gridCellContent !== undefined ? `cellContent: ${labelData.gridCellContent},` : ""}
478
- },`;
479
- })
480
- .join(" ")}]`;
481
- renderCell = `renderStaticSelectCell`;
482
- return {
483
- name,
484
- headerName: column.headerName,
485
- type,
486
- gridType: "singleSelect",
487
- columnType: gridColumnType,
488
- valueOptions,
489
- renderCell,
490
- valueFormatter,
491
- width: column.width,
492
- minWidth: column.minWidth,
493
- maxWidth: column.maxWidth,
494
- flex: column.flex,
495
- headerInfoTooltip: column.headerInfoTooltip,
496
- visible: column.visible !== undefined ? (typeof column.visible == "string" ? `theme.breakpoints.${column.visible}` : "false") : undefined,
497
- pinned: column.pinned,
498
- disableExport: column.disableExport,
499
- };
500
- }
501
- else if (type == "id") {
502
- gridColumnType = "...dataGridIdColumn,";
503
- }
504
- else if (type == "manyToMany") {
505
- gridColumnType = "...dataGridManyToManyColumn,";
506
- }
507
- else if (type == "oneToMany") {
508
- gridColumnType = "...dataGridOneToManyColumn,";
509
- }
510
- if ((column.type == "text" ||
511
- column.type == "number" ||
512
- column.type == "boolean" ||
513
- column.type == "date" ||
514
- column.type == "dateTime" ||
515
- column.type == "virtual" ||
516
- column.type == "id" ||
517
- column.type == "manyToMany" ||
518
- column.type == "oneToMany") &&
519
- column.renderCell) {
520
- if ((0, runtimeTypeGuards_1.isGeneratorConfigCode)(column.renderCell)) {
521
- renderCell = column.renderCell.code;
522
- imports.push(...column.renderCell.imports.map((imprt) => (0, convertConfigImport_1.convertConfigImport)(imprt)));
523
- }
524
- else {
525
- throw new Error(`Unsupported renderCell for column '${name}', only arrow functions are supported`);
526
- }
527
- }
528
- if ((column.type === "manyToMany" || column.type === "oneToMany") && !column.renderCell) {
529
- if (!column.labelField) {
530
- throw new Error(`labelField is required for ${column.type} column '${name}' if no custom renderCell is provided`);
531
- }
532
- renderCell = `({ row }) => <>{row.${column.name}.map((${(0, pluralize_1.singular)(column.name)}) => ${(0, pluralize_1.singular)(column.name)}.${column.labelField}).join(", ")}</>`;
533
- }
534
- //TODO support n:1 relation with singleSelect
535
- return {
536
- name,
537
- fieldName: column.fieldName,
538
- headerName: column.headerName,
539
- type,
540
- gridType,
541
- columnType: gridColumnType,
542
- renderCell,
543
- valueGetter,
544
- filterOperators: filterOperators,
545
- valueFormatter,
546
- width: column.width,
547
- minWidth: column.minWidth,
548
- maxWidth: column.maxWidth,
549
- flex: column.flex,
550
- headerInfoTooltip: column.headerInfoTooltip,
551
- visible: column.visible !== undefined ? (typeof column.visible == "string" ? `theme.breakpoints.${column.visible}` : "false") : undefined,
552
- pinned: column.pinned,
553
- disableExport: column.disableExport,
554
- sortBy: "sortBy" in column ? column.sortBy : undefined,
555
- };
556
- });
557
- iconsToImport.forEach((icon) => {
558
- imports.push({
559
- name: `${icon} as ${icon}Icon`,
560
- importPath: "@comet/admin-icons",
561
- });
562
- });
563
- const fragmentName = (_g = config.fragmentName) !== null && _g !== void 0 ? _g : `${gqlTypePlural}Form`;
564
- if (forwardRowAction) {
565
- props.push({
566
- name: "rowAction",
567
- type: `(params: GridRenderCellParams<GQL${fragmentName}Fragment>) => ReactNode`,
568
- optional: true,
569
- });
570
- props.push({
571
- name: "actionsColumnWidth",
572
- type: `number`,
573
- optional: true,
574
- defaultValue: defaultActionsColumnWidth,
575
- });
576
- props.push({
577
- name: "onRowClick",
578
- type: `${muiXGridVariant.gridComponent}Props["onRowClick"]`,
579
- optional: true,
580
- });
581
- }
582
- if (config.selectionProps) {
583
- props.push({
584
- name: "rowSelectionModel",
585
- type: `${muiXGridVariant.gridComponent}Props["rowSelectionModel"]`,
586
- optional: true,
587
- });
588
- props.push({
589
- name: "onRowSelectionModelChange",
590
- type: `${muiXGridVariant.gridComponent}Props["onRowSelectionModelChange"]`,
591
- optional: true,
592
- });
593
- }
594
- const { gridPropsTypeCode, gridPropsParamsCode } = generateGridPropsCode(props);
595
- const gridToolbarComponentName = `${gqlTypePlural}GridToolbar`;
596
- const dataGridRemoteParameters = config.initialSort || config.queryParamsPrefix || config.initialFilter
597
- ? `{${config.initialSort
598
- ? ` initialSort: [${config.initialSort
599
- .map((item) => {
600
- return `{field: "${item.field}", sort: "${item.sort}"}`;
601
- })
602
- .join(",\n")} ], `
603
- : ""}
604
- ${config.initialFilter
605
- ? `initialFilter:{ ${config.initialFilter.linkOperator
606
- ? `linkOperator: GridLogicOperator.${config.initialFilter.linkOperator === "or" ? "Or" : "And"},`
607
- : ""}
608
- items: [${config.initialFilter.items
609
- .map((item) => {
610
- return `{ field: "${item.field}", operator: "${item.operator}", value: "${item.value}" }`;
611
- })
612
- .join(",\n")} ],},`
613
- : ""}
614
- ${config.queryParamsPrefix ? `queryParamsPrefix: "${config.queryParamsPrefix}",` : ""}
615
- }`
616
- : "";
617
- const code = `import {
618
- GQL${gqlTypePlural}GridQuery,
619
- GQL${gqlTypePlural}GridQueryVariables,
620
- GQL${fragmentName}Fragment,
621
- GQLCreate${gqlType}Mutation,
622
- GQLCreate${gqlType}MutationVariables,
623
- GQLUpdate${gqlType}PositionMutation,
624
- GQLUpdate${gqlType}PositionMutationVariables,
625
- GQLDelete${gqlType}Mutation,
626
- GQLDelete${gqlType}MutationVariables
627
- } from "./${baseOutputFilename}.generated";
628
- ${(0, generateImportsCode_1.generateImportsCode)(imports)}
629
-
630
- const ${instanceGqlTypePlural}Fragment = gql\`
631
- fragment ${fragmentName} on ${gqlType} {
632
- id
633
- ${fieldList}
634
- }
635
- \`;
636
-
637
- const ${instanceGqlTypePlural}Query = gql\`${(0, generateGqlOperation_1.generateGqlOperation)({
638
- type: "query",
639
- operationName: `${gqlTypePlural}Grid`,
640
- rootOperation: gridQuery,
641
- fields: hasPaging ? [`nodes...${fragmentName}`, "totalCount"] : [`...${fragmentName}`],
642
- fragmentVariables: [`\${${instanceGqlTypePlural}Fragment}`],
643
- variables: [
644
- ...gqlArgs
645
- .filter((gqlArg) => gqlArg.queryOrMutationName === gridQueryType.name)
646
- .map((gqlArg) => ({ name: gqlArg.name, type: `${gqlArg.type}!` })),
647
- ...(hasPaging
648
- ? [
649
- {
650
- name: "offset",
651
- type: "Int!",
652
- },
653
- {
654
- name: "limit",
655
- type: "Int!",
656
- },
657
- ]
658
- : []),
659
- ...(hasSort ? [{ name: "sort", type: `[${gqlType}Sort!]` }] : []),
660
- ...(hasSearch ? [{ name: "search", type: "String" }] : []),
661
- ...(filterArg && (hasFilter || hasFilterProp) ? [{ name: "filter", type: `${gqlType}Filter` }] : []),
662
- ],
663
- })}\`;
664
-
665
- ${allowRowReordering
666
- ? `const update${gqlType}PositionMutation = gql\`
667
- mutation Update${gqlType}Position($id: ID!, $input: ${gqlType}UpdateInput!) {
668
- update${gqlType}(id: $id, input: $input) {
669
- id
670
- position
671
- updatedAt
672
- }
673
- }
674
- \`;`
675
- : ""}
676
-
677
- ${allowDeleting
678
- ? `const delete${gqlType}Mutation = gql\`
679
- mutation Delete${gqlType}($id: ID!) {
680
- delete${gqlType}(id: $id)
681
- }
682
- \`;`
683
- : ""}
684
-
685
-
686
- ${renderToolbar
687
- ? (0, generateGridToolbar_1.generateGridToolbar)({
688
- componentName: gridToolbarComponentName,
689
- forwardToolbarAction,
690
- hasSearch,
691
- hasFilter,
692
- allowAdding,
693
- instanceGqlType,
694
- gqlType,
695
- excelExport: config.excelExport,
696
- newEntryText: config.newEntryText,
697
- fragmentName,
698
- })
699
- : ""}
700
-
701
- ${gridPropsTypeCode}
702
-
703
- export function ${gqlTypePlural}Grid(${gridPropsParamsCode}) {
704
- ${showCrudContextMenuInActionsColumn ? "const client = useApolloClient();" : ""}
705
- const intl = useIntl();
706
- const dataGridProps = { ...${hasPaging ? "useDataGridRemote" : "useDataGridUrlState"}(${dataGridRemoteParameters}), ...usePersistentColumnState("${gqlTypePlural}Grid")${config.selectionProps === "multiSelect"
707
- ? `, rowSelectionModel, onRowSelectionModelChange, checkboxSelection: true, keepNonExistentRowsSelected: true`
708
- : config.selectionProps === "singleSelect"
709
- ? `, rowSelectionModel, onRowSelectionModelChange, checkboxSelection: false, keepNonExistentRowsSelected: false, disableRowSelectionOnClick: false`
710
- : ``} };
711
- ${useScopeFromContext ? `const { scope } = useContentScope();` : ""}
712
- ${gridNeedsTheme ? `const theme = useTheme();` : ""}
713
- ${showEditInActionsColumn ? `const stackSwitchApi = useStackSwitchApi();` : ""}
714
-
715
- ${generateHandleRowOrderChange(allowRowReordering, gqlType, instanceGqlTypePlural)}
716
-
717
- ${showEditInActionsColumn
718
- ? `const handleRowClick: ${muiXGridVariant.gridComponent}Props["onRowClick"] = (params) => {
719
- stackSwitchApi.activatePage("edit", params.row.id);
720
- };`
721
- : ""}
722
-
723
- const columns: GridColDef<GQL${fragmentName}Fragment>[] = useMemo(()=>[
724
- ${gridColumnFields
725
- .map((column) => {
726
- const defaultMinWidth = 150;
727
- const defaultColumnFlex = 1;
728
- let minWidth;
729
- let maxWidth;
730
- let tooltipColumnWidth = column.width;
731
- if (typeof column.width === "undefined") {
732
- maxWidth = column.maxWidth;
733
- if (typeof column.minWidth === "undefined" &&
734
- (typeof column.maxWidth === "undefined" || column.maxWidth >= defaultMinWidth)) {
735
- minWidth = defaultMinWidth;
736
- tooltipColumnWidth = defaultMinWidth;
737
- }
738
- else if (typeof column.minWidth !== "undefined") {
739
- minWidth = column.minWidth;
740
- tooltipColumnWidth = column.minWidth;
741
- }
742
- }
743
- let isColumnFilterable = !hasPaging
744
- ? true // local (client side) sorting is always possible (no api support needed)
745
- : filterFields.includes(column.name) || !!column.filterOperators;
746
- if (allowRowReordering) {
747
- //disable filter if rowReordering is enabled
748
- isColumnFilterable = false;
749
- }
750
- if (column.type == "block" && !hasPaging) {
751
- //blocks can't be sorted (client side)
752
- isColumnFilterable = false;
753
- }
754
- let isColumnSortable = !hasPaging
755
- ? true // local (client side) sorting is always possible (no api support needed)
756
- : sortFields.includes(column.name) || !!column.sortBy;
757
- if (allowRowReordering) {
758
- //disable sort if rowReordering is enabled
759
- isColumnSortable = false;
760
- }
761
- if (column.type == "block" && !hasPaging) {
762
- //blocks can't be sorted (client side)
763
- isColumnSortable = false;
764
- }
765
- const columnDefinition = {
766
- field: column.fieldName ? `"${column.fieldName}"` : `"${column.name.replace(/\./g, "_")}"`, // field-name is used for api-filter, and api nests with underscore
767
- renderHeader: column.headerInfoTooltip
768
- ? `() => (
769
- <>
770
- <GridColumnHeaderTitle label={${(0, intl_1.generateFormattedMessage)({
771
- config: column.headerName,
772
- id: `${instanceGqlType}.${column.name}`,
773
- defaultMessage: (0, camelCaseToHumanReadable_1.camelCaseToHumanReadable)(column.name),
774
- type: "intlCall",
775
- })}} columnWidth= {${tooltipColumnWidth}}
776
- />
777
- <Tooltip
778
- title={${(0, intl_1.generateFormattedMessage)({
779
- config: column.headerInfoTooltip,
780
- id: `${instanceGqlType}.${column.name}.tooltip`,
781
- type: "jsx",
782
- })}}
783
- >
784
- <InfoIcon sx={{ marginLeft: 1 }} />
785
- </Tooltip>
786
- </>
787
- )`
788
- : undefined,
789
- headerName: column.headerName === ""
790
- ? `""`
791
- : (0, intl_1.generateFormattedMessage)({
792
- config: column.headerName,
793
- id: `${instanceGqlType}.${column.name}`,
794
- defaultMessage: (0, camelCaseToHumanReadable_1.camelCaseToHumanReadable)(column.name),
795
- type: "intlCall",
796
- }),
797
- type: column.gridType ? `"${column.gridType}"` : undefined,
798
- filterable: isColumnFilterable ? undefined : `false`,
799
- sortable: isColumnSortable ? undefined : `false`,
800
- valueGetter: column.valueGetter,
801
- valueFormatter: column.valueFormatter,
802
- valueOptions: column.valueOptions,
803
- renderCell: column.renderCell,
804
- filterOperators: column.filterOperators,
805
- width: column.width,
806
- flex: column.flex,
807
- pinned: column.pinned && `"${column.pinned}"`,
808
- visible: column.visible,
809
- disableExport: column.disableExport ? "true" : undefined,
810
- };
811
- if ("sortBy" in column && column.sortBy) {
812
- columnDefinition["sortBy"] = getSortByValue(column.sortBy);
813
- }
814
- if (typeof column.width === "undefined") {
815
- columnDefinition.flex = defaultColumnFlex;
816
- columnDefinition.minWidth = minWidth;
817
- columnDefinition.maxWidth = maxWidth;
818
- }
819
- return tsCodeRecordToString(columnDefinition, column.columnType);
820
- })
821
- .join(",\n")},
822
- ${showActionsColumn
823
- ? tsCodeRecordToString(Object.assign(Object.assign({ field: '"actions"', headerName: actionsColumnHeaderName
824
- ? (0, intl_1.generateFormattedMessage)({
825
- config: actionsColumnHeaderName,
826
- id: `${instanceGqlType}.actions`,
827
- type: "intlCall",
828
- })
829
- : `""`, sortable: "false", filterable: "false", type: '"actions"', align: '"right"', pinned: `"${actionsColumnPinned}"`, width: forwardRowAction ? "actionsColumnWidth" : actionsColumnWidth, visible: actionsColumnVisible !== undefined
830
- ? typeof actionsColumnVisible == "string"
831
- ? `theme.breakpoints.${actionsColumnVisible}`
832
- : "false"
833
- : undefined }, restActionsColumnConfig), { headerInfoTooltip: restActionsColumnConfig.headerInfoTooltip
834
- ? (0, intl_1.generateFormattedMessage)({
835
- config: restActionsColumnConfig.headerInfoTooltip,
836
- id: `${instanceGqlType}.actions`,
837
- type: "intlCall",
838
- })
839
- : undefined, disableExport: config.excelExport ? "true" : undefined, renderCell: `(params) => {
840
- return (
841
- <>
842
- ${(actionsColumnComponent === null || actionsColumnComponent === void 0 ? void 0 : actionsColumnComponent.name) ? `<${actionsColumnComponent.name} {...params} />` : ""}${allowEditing
843
- ? forwardRowAction
844
- ? `{rowAction && rowAction(params)}`
845
- : `
846
- <IconButton color="primary" component={StackLink} pageName="edit" payload={params.row.id}>
847
- <EditIcon />
848
- </IconButton>`
849
- : ""}${showCrudContextMenuInActionsColumn
850
- ? `
851
- <CrudContextMenu
852
- ${allowDeleting
853
- ? `
854
- onDelete={async () => {
855
- await client.mutate<GQLDelete${gqlType}Mutation, GQLDelete${gqlType}MutationVariables>({
856
- mutation: delete${gqlType}Mutation,
857
- variables: { id: params.row.id },
858
- });
859
- }}
860
- `
861
- : ""}
862
- refetchQueries={[${instanceGqlTypePlural}Query]}
863
- ${((_h = config.crudContextMenu) === null || _h === void 0 ? void 0 : _h.deleteType) ? `deleteType="${config.crudContextMenu.deleteType}"` : ""}
864
- ${((_j = config.crudContextMenu) === null || _j === void 0 ? void 0 : _j.deleteText) ? `messagesMapping={{ delete: <FormattedMessage id="${instanceGqlType}.crudContextMenu.delete" defaultMessage="${config.crudContextMenu.deleteText}" /> }}` : ""}
865
- />
866
- `
867
- : ""}
868
- </>
869
- );
870
- }` }))
871
- : ""}
872
- ],[intl${gridNeedsTheme ? ", theme" : ""}${showCrudContextMenuInActionsColumn ? ", client" : ""}${forwardRowAction ? ", rowAction, actionsColumnWidth" : ""}]);
873
-
874
- ${hasFilter || hasSearch
875
- ? `const { ${hasFilter ? `filter: gqlFilter, ` : ""}${hasSearch ? `search: gqlSearch, ` : ""} } = muiGridFilterToGql(columns, dataGridProps.filterModel);`
876
- : ""}
877
-
878
- const { data, loading, error } = useQuery<GQL${gqlTypePlural}GridQuery, GQL${gqlTypePlural}GridQueryVariables>(${instanceGqlTypePlural}Query, {
879
- variables: {
880
- ${[
881
- ...gqlArgs.filter((gqlArg) => gqlArg.queryOrMutationName === gridQueryType.name).map((arg) => arg.name),
882
- ...(filterArg
883
- ? hasFilter && hasFilterProp
884
- ? ["filter: filter ? { and: [gqlFilter, filter] } : gqlFilter"]
885
- : hasFilter
886
- ? ["filter: gqlFilter"]
887
- : hasFilterProp
888
- ? ["filter"]
889
- : []
890
- : []),
891
- ...(hasSearch ? ["search: gqlSearch"] : []),
892
- ...(hasSort
893
- ? !allowRowReordering
894
- ? ["sort: muiGridSortToGql(dataGridProps.sortModel, columns)"]
895
- : [`sort: { field: "position", direction: "ASC" }`]
896
- : []),
897
- ...(hasPaging
898
- ? !allowRowReordering
899
- ? [
900
- `offset: dataGridProps.paginationModel.page * dataGridProps.paginationModel.pageSize`,
901
- `limit: dataGridProps.paginationModel.pageSize`,
902
- ]
903
- : // TODO: offset and limit should not be necessary for row reordering but not yet possible to disable in the api generator
904
- [`offset: 0`, `limit: 100`]
905
- : []),
906
- ].join(", ")}
907
- },
908
- });
909
- ${hasPaging ? `const rowCount = useBufferedRowCount(data?.${gridQuery}.totalCount);` : ""}
910
- if (error) throw error;
911
- const rows = ${!allowRowReordering
912
- ? hasPaging
913
- ? `data?.${gridQuery}.nodes`
914
- : `data?.${gridQuery}`
915
- : generateRowReorderingRows(gridQuery, fieldList, (_k = config.rowReordering) === null || _k === void 0 ? void 0 : _k.dragPreviewField)} ?? [];
916
-
917
- ${generateGridExportApi(config.excelExport, gqlTypePlural, instanceGqlTypePlural, gridQuery, gqlArgs, hasPaging)}
918
-
919
- return (
920
- <${muiXGridVariant.gridComponent}
921
- {...dataGridProps}
922
- rows={rows}
923
- ${hasPaging ? `rowCount={rowCount}` : ""}
924
- columns={columns}
925
- loading={loading}
926
- ${renderToolbar
927
- ? `slots={{
928
- toolbar: ${gridToolbarComponentName} as GridSlotsComponent["toolbar"],
929
- }}
930
- ${getDataGridSlotProps(gridToolbarComponentName, forwardToolbarAction, config.excelExport)}`
931
- : ""}
932
- ${allowRowReordering
933
- ? `rowReordering
934
- onRowOrderChange={handleRowOrderChange}
935
- hideFooterPagination`
936
- : ""}
937
- ${config.density ? `density="${config.density}"` : ""}
938
- ${showEditInActionsColumn ? `onRowClick={handleRowClick}` : forwardRowAction ? `onRowClick={onRowClick}` : ""}
939
- />
940
- );
941
- }
942
- `;
943
- return {
944
- code,
945
- gqlDocuments,
946
- };
947
- }
948
- const generateRowReorderingRows = (gridQuery, fieldList, dragPreviewField) => {
949
- const fields = fieldList.split(" ");
950
- const reorderField = dragPreviewField || fields.find((field) => field === "title" || field === "name") || "id";
951
- return `data?.${gridQuery}.nodes.map((node) => ({
952
- ...node,
953
- __reorder__: node.${reorderField}
954
- }))`;
955
- };
956
- const getDefaultActionsColumnWidth = (showCrudContextMenu, showEdit) => {
957
- let numberOfActions = 0;
958
- if (showCrudContextMenu) {
959
- numberOfActions += 1;
960
- }
961
- if (showEdit) {
962
- numberOfActions += 1;
963
- }
964
- const widthOfSingleAction = 32;
965
- const spacingAroundActions = 20;
966
- return numberOfActions * widthOfSingleAction + spacingAroundActions;
967
- };
968
- const getDataGridSlotProps = (componentName, forwardToolbarAction, excelExport) => {
969
- if (!forwardToolbarAction && !excelExport) {
970
- return "";
971
- }
972
- const values = `{
973
- ${forwardToolbarAction ? `toolbarAction,` : ""}
974
- ${excelExport ? `exportApi,` : ""}
975
- } as ${componentName}ToolbarProps`.replace(/\n/g, "");
976
- return `slotProps={{
977
- toolbar: ${values}
978
- }}`;
979
- };
980
- const generateGridExportApi = (excelExport, gqlTypePlural, instanceGqlTypePlural, gridQuery, gqlArgs, hasPaging) => {
981
- if (!excelExport) {
982
- return "";
983
- }
984
- const queryNodeType = hasPaging ? `GQL${gqlTypePlural}GridQuery["${gridQuery}"]["nodes"][0]` : `GQL${gqlTypePlural}GridQuery["${gridQuery}"][0]`;
985
- const variablesType = hasPaging ? `Omit<GQL${gqlTypePlural}GridQueryVariables, "offset" | "limit">` : `GQL${gqlTypePlural}GridQueryVariables`;
986
- const resolveQueryNodes = hasPaging ? `(data) => data.${gridQuery}.nodes` : `(data) => data.${gridQuery}`;
987
- const totalCount = hasPaging ? `data?.${gridQuery}.totalCount ?? 0` : `data?.${gridQuery}.length ?? 0`;
988
- return `const exportApi = useDataGridExcelExport<${queryNodeType}, GQL${gqlTypePlural}GridQuery, ${variablesType}>({
989
- columns,
990
- variables: {
991
- ${[
992
- ...gqlArgs.filter((gqlArg) => gqlArg.queryOrMutationName === gridQuery).map((arg) => arg.name),
993
- `...muiGridFilterToGql(columns, dataGridProps.filterModel)`,
994
- ].join(", ")}
995
- },
996
- query: ${instanceGqlTypePlural}Query,
997
- resolveQueryNodes: ${resolveQueryNodes},
998
- totalCount: ${totalCount},
999
- ${!hasPaging ? `hasPaging: false,` : ""}
1000
- exportOptions: {
1001
- fileName: "${gqlTypePlural}",
1002
- },
1003
- });`;
1004
- };
1005
- const generateHandleRowOrderChange = (allowRowReordering, gqlType, instanceGqlTypePlural) => {
1006
- if (!allowRowReordering) {
1007
- return "";
1008
- }
1009
- return `const handleRowOrderChange = async ({ row: { id }, targetIndex }: GridRowOrderChangeParams) => {
1010
- await client.mutate<GQLUpdate${gqlType}PositionMutation, GQLUpdate${gqlType}PositionMutationVariables>({
1011
- mutation: update${gqlType}PositionMutation,
1012
- variables: { id, input: { position: targetIndex + 1 } },
1013
- awaitRefetchQueries: true,
1014
- refetchQueries: [${instanceGqlTypePlural}Query]
1015
- });
1016
- };`;
1017
- };