@comet/admin-generator 8.0.0-beta.1 → 8.0.0-beta.3

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 (29) hide show
  1. package/lib/commands/generate/generate-command.d.ts +25 -17
  2. package/lib/commands/generate/generate-command.js +12 -37
  3. package/lib/commands/generate/generateForm/generateComponentFormField.js +7 -3
  4. package/lib/commands/generate/generateForm/generateFields.js +2 -3
  5. package/lib/commands/generate/generateForm/generateForm.js +6 -6
  6. package/lib/commands/generate/generateForm/generateFormField.js +12 -16
  7. package/lib/commands/generate/generateForm/generateFormLayout.js +1 -2
  8. package/lib/commands/generate/generateForm/getForwardedGqlArgs.js +1 -2
  9. package/lib/commands/generate/generateGrid/findInputObjectType.js +1 -2
  10. package/lib/commands/generate/generateGrid/generateGqlFieldList.d.ts +2 -3
  11. package/lib/commands/generate/generateGrid/generateGqlFieldList.js +5 -6
  12. package/lib/commands/generate/generateGrid/generateGrid.js +42 -35
  13. package/lib/commands/generate/generateGrid/getForwardedGqlArgs.js +1 -2
  14. package/lib/commands/generate/generateGrid/getPropsForFilterProp.js +1 -2
  15. package/lib/commands/generate/utils/camelCaseToHumanReadable.js +1 -2
  16. package/lib/commands/generate/utils/convertConfigImport.d.ts +5 -0
  17. package/lib/commands/generate/utils/convertConfigImport.js +14 -0
  18. package/lib/commands/generate/utils/findMutationType.js +2 -3
  19. package/lib/commands/generate/utils/findQueryType.js +1 -2
  20. package/lib/commands/generate/utils/findRootBlocks.js +1 -2
  21. package/lib/commands/generate/utils/generateImportsCode.js +1 -2
  22. package/lib/commands/generate/utils/runtimeTypeGuards.d.ts +20 -0
  23. package/lib/commands/generate/utils/runtimeTypeGuards.js +22 -0
  24. package/lib/commands/generate/utils/tsMorphHelper.d.ts +4 -0
  25. package/lib/commands/generate/utils/tsMorphHelper.js +199 -0
  26. package/lib/commands/generate/utils/writeGenerated.js +38 -11
  27. package/package.json +18 -12
  28. package/lib/commands/generate/generateGrid/combinationColumn.d.ts +0 -43
  29. package/lib/commands/generate/generateGrid/combinationColumn.js +0 -151
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.convertConfigImport = convertConfigImport;
4
+ // generated code is one level below config, this function converts relative imports to go one level up
5
+ function convertConfigImport(imprt) {
6
+ let importPath = imprt.import;
7
+ if (importPath.startsWith("../")) {
8
+ importPath = `../${importPath}`;
9
+ }
10
+ else if (importPath.startsWith("./")) {
11
+ importPath = `.${importPath}`;
12
+ }
13
+ return { name: imprt.name, importPath };
14
+ }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findMutationTypeOrThrow = exports.findMutationType = void 0;
3
+ exports.findMutationType = findMutationType;
4
+ exports.findMutationTypeOrThrow = findMutationTypeOrThrow;
4
5
  function findMutationType(mutationName, schema) {
5
6
  if (!schema.__schema.mutationType)
6
7
  throw new Error("Schema has no Mutation type");
@@ -9,11 +10,9 @@ function findMutationType(mutationName, schema) {
9
10
  throw new Error("Can't find Mutation type in gql schema");
10
11
  return queryType.fields.find((field) => field.name === mutationName);
11
12
  }
12
- exports.findMutationType = findMutationType;
13
13
  function findMutationTypeOrThrow(mutationName, schema) {
14
14
  const ret = findMutationType(mutationName, schema);
15
15
  if (!ret)
16
16
  throw new Error(`Can't find Mutation ${mutationName} in gql schema`);
17
17
  return ret;
18
18
  }
19
- exports.findMutationTypeOrThrow = findMutationTypeOrThrow;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findQueryTypeOrThrow = void 0;
3
+ exports.findQueryTypeOrThrow = findQueryTypeOrThrow;
4
4
  function findQueryType(queryName, schema) {
5
5
  const queryType = schema.__schema.types.find((type) => type.name === schema.__schema.queryType.name);
6
6
  if (!queryType)
@@ -16,4 +16,3 @@ function findQueryTypeOrThrow(queryName, schema) {
16
16
  throw new Error(`Can't find query ${queryName} in gql schema`);
17
17
  return ret;
18
18
  }
19
- exports.findQueryTypeOrThrow = findQueryTypeOrThrow;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.findRootBlocks = void 0;
3
+ exports.findRootBlocks = findRootBlocks;
4
4
  const fs_1 = require("fs");
5
5
  const fallbackLibraryBlocks = {
6
6
  AnchorBlock: "@comet/cms-admin",
@@ -64,4 +64,3 @@ function findRootBlocks({ gqlType, targetDirectory }, schema) {
64
64
  });
65
65
  return ret;
66
66
  }
67
- exports.findRootBlocks = findRootBlocks;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateImportsCode = void 0;
3
+ exports.generateImportsCode = generateImportsCode;
4
4
  // generate imports code and filter duplicates
5
5
  function generateImportsCode(imports) {
6
6
  const importsNameToPath = new Map(); // name -> importPath
@@ -24,4 +24,3 @@ function generateImportsCode(imports) {
24
24
  .join("\n");
25
25
  return importsString;
26
26
  }
27
- exports.generateImportsCode = generateImportsCode;
@@ -0,0 +1,20 @@
1
+ type GeneratorConfigImport = {
2
+ name: string;
3
+ import: string;
4
+ };
5
+ /**
6
+ * Type Guard used by generator runtime for places where runtime vs. configtime types mismatch
7
+ */
8
+ export declare function isGeneratorConfigImport(value: unknown): value is GeneratorConfigImport;
9
+ type GeneratorConfigCode = {
10
+ code: string;
11
+ imports: {
12
+ name: string;
13
+ import: string;
14
+ }[];
15
+ };
16
+ /**
17
+ * Type Guard used by generator runtime for places where runtime vs. configtime types mismatch
18
+ */
19
+ export declare function isGeneratorConfigCode(value: unknown): value is GeneratorConfigCode;
20
+ export {};
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isGeneratorConfigImport = isGeneratorConfigImport;
4
+ exports.isGeneratorConfigCode = isGeneratorConfigCode;
5
+ /**
6
+ * Type Guard used by generator runtime for places where runtime vs. configtime types mismatch
7
+ */
8
+ function isGeneratorConfigImport(value) {
9
+ if (value && typeof value === "object" && "import" in value && "name" in value) {
10
+ return true;
11
+ }
12
+ return false;
13
+ }
14
+ /**
15
+ * Type Guard used by generator runtime for places where runtime vs. configtime types mismatch
16
+ */
17
+ function isGeneratorConfigCode(value) {
18
+ if (value && typeof value === "object" && "code" in value && "imports" in value) {
19
+ return true;
20
+ }
21
+ return false;
22
+ }
@@ -0,0 +1,4 @@
1
+ import { type SourceFile } from "ts-morph";
2
+ import { type GeneratorConfig } from "../generate-command";
3
+ export declare function morphTsSource(path: string): SourceFile;
4
+ export declare function configsFromSourceFile(sourceFile: SourceFile): Record<string, GeneratorConfig>;
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.morphTsSource = morphTsSource;
4
+ exports.configsFromSourceFile = configsFromSourceFile;
5
+ const ts_morph_1 = require("ts-morph");
6
+ const project = new ts_morph_1.Project({
7
+ tsConfigFilePath: "tsconfig.json",
8
+ skipAddingFilesFromTsConfig: true,
9
+ });
10
+ function morphTsSource(path) {
11
+ let tsSource = project.getSourceFile(path);
12
+ if (!tsSource)
13
+ tsSource = project.addSourceFileAtPath(path);
14
+ return tsSource;
15
+ }
16
+ const supportedImportPaths = [
17
+ "[type=grid].columns.filterOperators",
18
+ "[type=grid].columns.block",
19
+ "[type=grid].columns.component",
20
+ // TODO implement in generator "[type=grid].columns.renderCell",
21
+ //support in up to 5 levels of nested fields (eg. fieldSet)
22
+ ...Array.from(Array(5).keys()).map((i) => `[type=form]${".fields".repeat(i + 1)}.validate`),
23
+ ...Array.from(Array(5).keys()).map((i) => `[type=form]${".fields".repeat(i + 1)}.block`),
24
+ ...Array.from(Array(5).keys()).map((i) => `[type=form]${".fields".repeat(i + 1)}.component`),
25
+ ];
26
+ const supportedInlineCodePaths = [
27
+ // TODO implement in generator "[type=grid].columns.filterOperators",
28
+ "[type=grid].columns.renderCell",
29
+ //support in up to 5 levels of nested fields (eg. fieldSet)
30
+ ...Array.from(Array(5).keys()).map((i) => `[type=form]${".fields".repeat(i + 1)}.validate`),
31
+ ];
32
+ function configsFromSourceFile(sourceFile) {
33
+ const configs = {}; //GeneratorConfig is not fully correct (runtime vs config mismatch), we work around that using type guards
34
+ for (const [name, declarations] of Array.from(sourceFile.getExportedDeclarations().entries())) {
35
+ //console.log(name);
36
+ if (declarations.length != 1) {
37
+ throw new Error(`Expected exactly one declaration for ${name}`);
38
+ }
39
+ const config = exportedDeclarationToJson(declarations[0]);
40
+ //console.dir(config, { depth: 10 });
41
+ configs[name] = config;
42
+ }
43
+ return configs;
44
+ }
45
+ function findUsedImports(node) {
46
+ const imports = [];
47
+ node.getDescendantsOfKind(ts_morph_1.SyntaxKind.Identifier).forEach((identifier) => {
48
+ var _a;
49
+ for (const referencedSymbol of identifier.findReferences()) {
50
+ for (const reference of referencedSymbol.getReferences()) {
51
+ const referenceNode = reference.getNode();
52
+ const importDeclaration = referenceNode.getFirstAncestorByKind(ts_morph_1.SyntaxKind.ImportDeclaration);
53
+ if (importDeclaration) {
54
+ for (const namedImport of importDeclaration.getNamedImports()) {
55
+ if (((_a = (namedImport.getAliasNode() || namedImport.getNameNode())) === null || _a === void 0 ? void 0 : _a.getText()) == referenceNode.getText()) {
56
+ imports.push({
57
+ name: namedImport.getNameNode().getText(),
58
+ import: importDeclaration.getModuleSpecifierValue(),
59
+ });
60
+ }
61
+ }
62
+ }
63
+ }
64
+ }
65
+ });
66
+ return imports;
67
+ }
68
+ function getTypePropertyFromObjectLiteral(node) {
69
+ for (const property of node.getProperties()) {
70
+ if (property.getKind() == ts_morph_1.SyntaxKind.PropertyAssignment) {
71
+ const propertyAssignment = property;
72
+ if (propertyAssignment.getName() == "type") {
73
+ const propertyAssignmentInitializer = propertyAssignment.getInitializer();
74
+ if ((propertyAssignmentInitializer === null || propertyAssignmentInitializer === void 0 ? void 0 : propertyAssignmentInitializer.getKind()) == ts_morph_1.SyntaxKind.StringLiteral) {
75
+ return propertyAssignmentInitializer.getLiteralValue();
76
+ }
77
+ }
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
83
+ function astExpressionToJson(node, path) {
84
+ var _a;
85
+ if (node.getKind() == ts_morph_1.SyntaxKind.ObjectLiteralExpression) {
86
+ if (path == "") {
87
+ // first entry of path is the type, then property names (. separated) are added
88
+ const typeProperty = getTypePropertyFromObjectLiteral(node);
89
+ path = typeProperty ? `[type=${typeProperty}]` : "";
90
+ }
91
+ const ret = {};
92
+ for (const property of node.getProperties()) {
93
+ if (property.getKind() == ts_morph_1.SyntaxKind.PropertyAssignment) {
94
+ const propertyAssignment = property;
95
+ const propertyAssignmentInitializer = propertyAssignment.getInitializer();
96
+ if (propertyAssignmentInitializer) {
97
+ ret[propertyAssignment.getName()] = astExpressionToJson(propertyAssignmentInitializer, `${path}.${propertyAssignment.getName()}`);
98
+ }
99
+ else {
100
+ throw new Error(`Initializer is required for propertyAssignment '${propertyAssignment.getName()}'`);
101
+ }
102
+ }
103
+ else {
104
+ throw new Error(`Unsupported ObjectLiteralExpression property Kind ${property.getKindName()}`);
105
+ }
106
+ }
107
+ return ret;
108
+ }
109
+ else if (node.getKind() == ts_morph_1.SyntaxKind.StringLiteral) {
110
+ return node.getLiteralValue();
111
+ }
112
+ else if (node.getKind() == ts_morph_1.SyntaxKind.NumericLiteral) {
113
+ return node.getLiteralValue();
114
+ }
115
+ else if (node.getKind() == ts_morph_1.SyntaxKind.FalseKeyword) {
116
+ return false;
117
+ }
118
+ else if (node.getKind() == ts_morph_1.SyntaxKind.TrueKeyword) {
119
+ return true;
120
+ }
121
+ else if (node.getKind() == ts_morph_1.SyntaxKind.BinaryExpression) {
122
+ //what is this?
123
+ return node.getText();
124
+ }
125
+ else if (node.getKind() == ts_morph_1.SyntaxKind.ArrowFunction) {
126
+ if (supportedInlineCodePaths.includes(path)) {
127
+ const body = node.getBody();
128
+ return {
129
+ code: node.getText(),
130
+ imports: findUsedImports(body),
131
+ };
132
+ }
133
+ else {
134
+ throw new Error(`Inline Function is not allowed here and calling the function is not supported: ${path}`);
135
+ }
136
+ }
137
+ else if (node.getKind() == ts_morph_1.SyntaxKind.ArrayLiteralExpression) {
138
+ const ret = [];
139
+ for (const element of node.getElements()) {
140
+ ret.push(astExpressionToJson(element, path));
141
+ }
142
+ return ret;
143
+ }
144
+ else if (node.getKind() == ts_morph_1.SyntaxKind.Identifier) {
145
+ for (const referencedSymbol of node.findReferences()) {
146
+ for (const reference of referencedSymbol.getReferences()) {
147
+ const referenceNode = reference.getNode();
148
+ const importDeclaration = referenceNode.getFirstAncestorByKind(ts_morph_1.SyntaxKind.ImportDeclaration);
149
+ const variableDeclaration = referenceNode.getFirstAncestorByKind(ts_morph_1.SyntaxKind.VariableDeclaration);
150
+ if (importDeclaration) {
151
+ for (const namedImport of importDeclaration.getNamedImports()) {
152
+ if (((_a = (namedImport.getAliasNode() || namedImport.getNameNode())) === null || _a === void 0 ? void 0 : _a.getText()) == referenceNode.getText()) {
153
+ if (supportedImportPaths.includes(path)) {
154
+ return {
155
+ name: namedImport.getNameNode().getText(),
156
+ import: importDeclaration.getModuleSpecifierValue(),
157
+ };
158
+ }
159
+ else {
160
+ throw new Error(`Following the import is not supported: ${path} ${namedImport.getText()}`);
161
+ }
162
+ }
163
+ }
164
+ }
165
+ else if (variableDeclaration) {
166
+ if (variableDeclaration.getName() == node.getText()) {
167
+ const variableInitializer = variableDeclaration.getInitializer();
168
+ if (variableInitializer) {
169
+ return astExpressionToJson(variableInitializer, path);
170
+ }
171
+ else {
172
+ throw new Error(`Initializer is required for variableDeclaration '${variableDeclaration.getName()}'`);
173
+ }
174
+ }
175
+ }
176
+ }
177
+ }
178
+ throw new Error(`Unsupported identifier '${node.getText()}', only imports and are variable declarations with initializer are supported`);
179
+ }
180
+ else {
181
+ throw new Error(`Unsupported expression Kind ${node.getKindName()}`);
182
+ }
183
+ }
184
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
185
+ function exportedDeclarationToJson(node) {
186
+ if (node.getKind() == ts_morph_1.SyntaxKind.VariableDeclaration) {
187
+ const variableDeclaration = node;
188
+ const initializer = variableDeclaration.getInitializer();
189
+ if (initializer) {
190
+ return astExpressionToJson(initializer, "");
191
+ }
192
+ else {
193
+ throw new Error(`Initializer is required for variableDeclaration '${variableDeclaration.getName()}'`);
194
+ }
195
+ }
196
+ else {
197
+ throw new Error(`Unsupported declaration kind '${node.getKindName()}'`);
198
+ }
199
+ }
@@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
15
15
  }) : function(o, v) {
16
16
  o["default"] = v;
17
17
  });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
25
35
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
36
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
37
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -31,8 +41,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
31
41
  step((generator = generator.apply(thisArg, _arguments || [])).next());
32
42
  });
33
43
  };
44
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
34
47
  Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.writeGenerated = void 0;
48
+ exports.writeGenerated = writeGenerated;
49
+ const chalk_1 = __importDefault(require("chalk"));
36
50
  const eslint_1 = require("eslint");
37
51
  const fs_1 = require("fs");
38
52
  const path = __importStar(require("path"));
@@ -46,12 +60,25 @@ function writeGenerated(filePath, contents) {
46
60
  cwd: process.cwd(),
47
61
  fix: true,
48
62
  });
63
+ // Write not linted generated code into file. This is necessary to avoid linting errors like: Parsing error: file/path/file.tsx was not found by the project service.
64
+ yield fs_1.promises.writeFile(filePath, header + contents);
49
65
  const lintResult = yield eslint.lintText(header + contents, {
50
66
  filePath,
51
67
  });
52
- const output = lintResult[0] && lintResult[0].output ? lintResult[0].output : lintResult[0].source;
53
- yield fs_1.promises.writeFile(filePath, output !== null && output !== void 0 ? output : contents);
68
+ if (lintResult[0].errorCount > 0 || lintResult[0].fatalErrorCount > 0) {
69
+ const errorMessage = lintResult[0].messages
70
+ .map((message) => {
71
+ return message.message;
72
+ })
73
+ .join(".");
74
+ console.error(chalk_1.default.red(`Linting error in ${filePath}: \n${errorMessage}`));
75
+ }
76
+ else if (lintResult[0].output != null) {
77
+ yield fs_1.promises.writeFile(filePath, lintResult[0].output);
78
+ }
79
+ else {
80
+ console.error(chalk_1.default.red("No output from linting"));
81
+ }
54
82
  console.log(`generated ${filePath}`);
55
83
  });
56
84
  }
57
- exports.writeGenerated = writeGenerated;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@comet/admin-generator",
3
- "version": "8.0.0-beta.1",
3
+ "version": "8.0.0-beta.3",
4
4
  "repository": {
5
5
  "directory": "packages/admin/admin-generator",
6
6
  "type": "git",
@@ -19,35 +19,41 @@
19
19
  "dependencies": {
20
20
  "@graphql-tools/graphql-file-loader": "^7.5.17",
21
21
  "@graphql-tools/load": "^7.8.14",
22
+ "chalk": "^5.4.1",
22
23
  "change-case": "^4.1.2",
23
24
  "commander": "^9.5.0",
24
25
  "glob": "^10.4.5",
25
26
  "graphql": "^16.10.0",
26
27
  "object-path": "^0.11.8",
27
28
  "pluralize": "^8.0.0",
29
+ "ts-morph": "^25.0.1",
28
30
  "ts-node": "^10.9.2"
29
31
  },
30
32
  "devDependencies": {
31
- "@mui/material": "^6.4.6",
32
- "@mui/x-data-grid": "^7.27.2",
33
+ "@mui/material": "^6.4.8",
34
+ "@mui/x-data-grid": "^7.28.0",
33
35
  "@types/jest": "^29.5.14",
34
- "@types/node": "^22.13.8",
36
+ "@types/node": "^22.13.10",
35
37
  "@types/object-path": "^0.11.4",
36
38
  "@types/pluralize": "^0.0.33",
37
- "@types/react": "^18.3.18",
38
- "eslint": "^9.20.1",
39
+ "@types/react": "^18.3.19",
40
+ "eslint": "^9.22.0",
41
+ "final-form": "^4.20.10",
39
42
  "jest": "^29.7.0",
40
43
  "npm-run-all2": "^5.0.2",
41
44
  "prettier": "^3.5.3",
42
45
  "react": "^18.3.1",
43
- "react-intl": "^6.8.9",
46
+ "react-intl": "^7.1.6",
44
47
  "rimraf": "^6.0.1",
45
48
  "ts-jest": "^29.2.6",
46
- "typescript": "^4.9.5",
47
- "@comet/admin": "8.0.0-beta.1",
48
- "@comet/admin-icons": "8.0.0-beta.1",
49
- "@comet/cms-admin": "8.0.0-beta.1",
50
- "@comet/eslint-config": "8.0.0-beta.1"
49
+ "typescript": "^5.7.3",
50
+ "@comet/admin": "8.0.0-beta.3",
51
+ "@comet/admin-icons": "8.0.0-beta.3",
52
+ "@comet/cms-admin": "8.0.0-beta.3",
53
+ "@comet/eslint-config": "8.0.0-beta.3"
54
+ },
55
+ "engines": {
56
+ "node": ">=22.0.0"
51
57
  },
52
58
  "publishConfig": {
53
59
  "access": "public",
@@ -1,43 +0,0 @@
1
- import { type GridColDef } from "@comet/admin";
2
- import { type ComponentProps } from "react";
3
- import { type FormattedNumber } from "react-intl";
4
- import { type BaseColumnConfig, type ImportReference } from "../generate-command";
5
- type AbstractField<FieldName extends string> = {
6
- field: FieldName;
7
- emptyValue?: string;
8
- };
9
- type TextField<FieldName extends string> = AbstractField<FieldName> & {
10
- type: "text";
11
- };
12
- type StaticText = {
13
- type: "static";
14
- text: string;
15
- };
16
- type FormattedNumberPropsForNumberField = Omit<ComponentProps<typeof FormattedNumber>, "value" | "children">;
17
- type NumberField<FieldName extends string> = AbstractField<FieldName> & FormattedNumberPropsForNumberField & {
18
- type: "number";
19
- decimals?: number;
20
- };
21
- type StaticSelectField<FieldName extends string> = AbstractField<FieldName> & {
22
- type: "staticSelect";
23
- values: Array<string | {
24
- value: string | number | boolean;
25
- label: string;
26
- }>;
27
- };
28
- type FormattedMessage<FieldName extends string> = {
29
- type: "formattedMessage";
30
- message: string;
31
- valueFields: Record<string, Field<FieldName>>;
32
- };
33
- type Field<FieldName extends string> = StaticText | FieldName | TextField<FieldName> | NumberField<FieldName> | StaticSelectField<FieldName> | FormattedMessage<FieldName>;
34
- export type GridCombinationColumnConfig<FieldName extends string> = {
35
- type: "combination";
36
- name: string;
37
- primaryText?: Field<FieldName>;
38
- secondaryText?: Field<FieldName>;
39
- filterOperators?: ImportReference;
40
- } & BaseColumnConfig & Pick<GridColDef, "sortBy">;
41
- export declare const getCombinationColumnRenderCell: (column: GridCombinationColumnConfig<string>, messageIdPrefix: string) => string;
42
- export declare const getAllColumnFieldNames: (column: GridCombinationColumnConfig<string>) => string[];
43
- export {};
@@ -1,151 +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.getAllColumnFieldNames = exports.getCombinationColumnRenderCell = void 0;
15
- const intl_1 = require("../utils/intl");
16
- const getTextForCellContent = (textConfig, messageIdPrefix) => {
17
- if (typeof textConfig !== "string" && textConfig.type === "static") {
18
- return {
19
- textContent: (0, intl_1.getFormattedMessageNode)(messageIdPrefix, textConfig.text),
20
- };
21
- }
22
- if (typeof textConfig !== "string" && textConfig.type === "formattedMessage") {
23
- const variableDefinitions = [];
24
- const values = Object.entries(textConfig.valueFields)
25
- .map(([key, value]) => {
26
- const { textContent, variableDefinitions: cellVariableDefinitions } = getTextForCellContent(value, `${messageIdPrefix}.${key}`);
27
- if (cellVariableDefinitions === null || cellVariableDefinitions === void 0 ? void 0 : cellVariableDefinitions.length) {
28
- variableDefinitions.push(...cellVariableDefinitions);
29
- }
30
- return `${key}: ${textContent}`;
31
- })
32
- .join(", ");
33
- return {
34
- textContent: (0, intl_1.getFormattedMessageNode)(messageIdPrefix, textConfig.message, `{${values}}`),
35
- variableDefinitions,
36
- };
37
- }
38
- const emptyText = typeof textConfig !== "string" && "emptyValue" in textConfig
39
- ? (0, intl_1.getFormattedMessageNode)(`${messageIdPrefix}.empty`, textConfig.emptyValue)
40
- : "'-'";
41
- const fieldName = typeof textConfig === "string" ? textConfig : textConfig.field;
42
- const rowValue = `row.${fieldName.replace(/\./g, "?.")}`;
43
- const stringTextContent = `${rowValue} ?? ${emptyText}`;
44
- if (typeof textConfig === "string") {
45
- return {
46
- textContent: stringTextContent,
47
- };
48
- }
49
- if (textConfig.type === "number") {
50
- const { type, decimals: decimalsConfigValue, field, emptyValue } = textConfig, configForFormattedNumberProps = __rest(textConfig, ["type", "decimals", "field", "emptyValue"]);
51
- const hasCurrency = Boolean(textConfig.currency);
52
- const hasUnit = Boolean(textConfig.unit);
53
- const defaultDecimalsProp = hasCurrency && decimalsConfigValue === undefined ? 2 : decimalsConfigValue;
54
- let defaultStyleProp = undefined;
55
- if (hasCurrency) {
56
- defaultStyleProp = '"currency"';
57
- }
58
- else if (hasUnit) {
59
- defaultStyleProp = '"unit"';
60
- }
61
- const formattedNumberProps = {
62
- value: `{${rowValue}}`,
63
- minimumFractionDigits: typeof defaultDecimalsProp !== "undefined" ? `{${defaultDecimalsProp}}` : undefined,
64
- maximumFractionDigits: typeof defaultDecimalsProp !== "undefined" ? `{${defaultDecimalsProp}}` : undefined,
65
- style: typeof defaultStyleProp !== "undefined" ? defaultStyleProp : undefined,
66
- };
67
- Object.entries(configForFormattedNumberProps).forEach(([key, value]) => {
68
- if (typeof value === "string") {
69
- formattedNumberProps[key] = `"${value}"`;
70
- }
71
- else {
72
- formattedNumberProps[key] = `{${value}}`;
73
- }
74
- });
75
- const formattedNumberPropsString = Object.entries(formattedNumberProps)
76
- .map(([key, value]) => {
77
- if (typeof value === "undefined") {
78
- return null;
79
- }
80
- return `${key}=${value}`;
81
- })
82
- .join(" ");
83
- return {
84
- textContent: `typeof ${rowValue} === "undefined" || ${rowValue} === null ? ${emptyText} : <FormattedNumber ${formattedNumberPropsString} />`,
85
- };
86
- }
87
- if (textConfig.type === "staticSelect") {
88
- const labelsVariableName = `${textConfig.field}Labels`;
89
- const labelMapping = textConfig.values
90
- .map((valueOption) => {
91
- const value = typeof valueOption === "string" ? valueOption : valueOption.value;
92
- const label = typeof valueOption === "string" ? valueOption : valueOption.label;
93
- return `${value}: ${(0, intl_1.getFormattedMessageNode)(`${messageIdPrefix}.${value}`, label)}`;
94
- })
95
- .join(", ");
96
- const labelMappingVar = `const ${labelsVariableName}: Record<string, ReactNode> = { ${labelMapping} };`;
97
- const textContent = `(${rowValue} == null ? ${emptyText} : ${labelsVariableName}[` + `\`\${${rowValue}}\`` + `] ?? ${rowValue})`;
98
- return {
99
- textContent,
100
- variableDefinitions: [labelMappingVar],
101
- };
102
- }
103
- return {
104
- textContent: stringTextContent,
105
- };
106
- };
107
- const getCombinationColumnRenderCell = (column, messageIdPrefix) => {
108
- const gridCellContentProps = {};
109
- const allVariableDefinitions = [];
110
- if (column.primaryText) {
111
- const { textContent, variableDefinitions = [] } = getTextForCellContent(column.primaryText, `${messageIdPrefix}.primaryText`);
112
- gridCellContentProps.primaryText = textContent;
113
- allVariableDefinitions.push(...variableDefinitions);
114
- }
115
- if (column.secondaryText) {
116
- const { textContent, variableDefinitions = [] } = getTextForCellContent(column.secondaryText, `${messageIdPrefix}.secondaryText`);
117
- gridCellContentProps.secondaryText = textContent;
118
- allVariableDefinitions.push(...variableDefinitions);
119
- }
120
- const allUniqueVariableDefinitions = Array.from(new Set(allVariableDefinitions));
121
- return `({ row }) => {
122
- ${allUniqueVariableDefinitions.join("\n")}
123
- return <GridCellContent ${Object.entries(gridCellContentProps)
124
- .map(([key, value]) => `${key}={${value}}`)
125
- .join(" ")} />;
126
- }`;
127
- };
128
- exports.getCombinationColumnRenderCell = getCombinationColumnRenderCell;
129
- const getFieldNamesFromText = (textConfig) => {
130
- if (typeof textConfig === "string") {
131
- return [textConfig];
132
- }
133
- if (textConfig.type === "static") {
134
- return [];
135
- }
136
- if (textConfig.type === "formattedMessage") {
137
- return Object.values(textConfig.valueFields).flatMap((value) => getFieldNamesFromText(value));
138
- }
139
- return [textConfig.field];
140
- };
141
- const getAllColumnFieldNames = (column) => {
142
- const fieldNames = [];
143
- if (column.primaryText) {
144
- fieldNames.push(...getFieldNamesFromText(column.primaryText));
145
- }
146
- if (column.secondaryText) {
147
- fieldNames.push(...getFieldNamesFromText(column.secondaryText));
148
- }
149
- return fieldNames.filter((fieldName) => fieldName !== "id");
150
- };
151
- exports.getAllColumnFieldNames = getAllColumnFieldNames;