easy-mat-ui 0.0.7 → 1.0.1

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.
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validatePage = validatePage;
4
+ exports.generatePage = generatePage;
5
+ const blocks_1 = require("./blocks");
6
+ const catalog_1 = require("./catalog");
7
+ const context_1 = require("./context");
8
+ const naming_1 = require("./naming");
9
+ const table_1 = require("./table");
10
+ const DEFAULT_LIB = 'easy-mat-ui';
11
+ function validateModel(model, where) {
12
+ if (!(0, naming_1.isIdentifier)(model.className))
13
+ throw new Error(`${where}: "${model.className}" is not a valid class name.`);
14
+ if (!model.fields.length)
15
+ throw new Error(`${where}: the model ${model.className} has no field.`);
16
+ const seen = new Set();
17
+ for (const field of model.fields) {
18
+ if (!(0, naming_1.isIdentifier)(field.name))
19
+ throw new Error(`${where}: "${field.name}" is not a valid field name.`);
20
+ if (seen.has(field.name))
21
+ throw new Error(`${where}: the field "${field.name}" is listed twice.`);
22
+ seen.add(field.name);
23
+ }
24
+ if (!model.generate && !model.importPath)
25
+ throw new Error(`${where}: an existing model needs its import path.`);
26
+ }
27
+ /** Throws a readable error when the configuration cannot produce a page. */
28
+ function validatePage(config) {
29
+ const name = (0, naming_1.kebab)(config.name);
30
+ if (!/^[a-z][a-z0-9-]*$/.test(name))
31
+ throw new Error(`The page name "${config.name}" must start with a letter and use letters, digits and hyphens.`);
32
+ if (!config.blocks.length)
33
+ throw new Error('Choose at least one component for the page.');
34
+ if (config.blocks.filter((block) => block.type === 'table').length > 1)
35
+ throw new Error('A page can have only one table.');
36
+ for (const block of config.blocks) {
37
+ const ids = (list) => list.map((item) => item.id).filter(Boolean);
38
+ const unique = (list, what) => {
39
+ if (new Set(list).size !== list.length)
40
+ throw new Error(`${what}: ids must be different.`);
41
+ };
42
+ switch (block.type) {
43
+ case 'chip-nav':
44
+ if (!block.items.length)
45
+ throw new Error('The category buttons need at least one item.');
46
+ unique(ids(block.items), 'Category buttons');
47
+ break;
48
+ case 'segmented':
49
+ if (!block.options.length)
50
+ throw new Error('The segmented control needs at least one option.');
51
+ unique(ids(block.options), 'Segmented control');
52
+ break;
53
+ case 'language-switch':
54
+ if (!block.languages.length)
55
+ throw new Error('The language picker needs at least one language.');
56
+ unique(block.languages.map((language) => language.code), 'Language picker');
57
+ break;
58
+ case 'card-grid':
59
+ if (!block.cards.length)
60
+ throw new Error('The card grid needs at least one card.');
61
+ unique(ids(block.cards), 'Card grid');
62
+ break;
63
+ case 'table':
64
+ validateModel(block.model, 'Table');
65
+ if (block.child)
66
+ validateModel(block.child.model, 'Child table');
67
+ break;
68
+ default:
69
+ break;
70
+ }
71
+ }
72
+ }
73
+ const indentBlock = (text, spaces) => text
74
+ .split('\n')
75
+ .map((line) => (line ? ' '.repeat(spaces) + line : line))
76
+ .join('\n');
77
+ /** Turns a page described as data into the files of an Angular component. Pure: it reads and writes nothing. */
78
+ function generatePage(config) {
79
+ validatePage(config);
80
+ const name = (0, naming_1.kebab)(config.name);
81
+ const lib = config.libPackage || DEFAULT_LIB;
82
+ const root = config.i18nRoot || 'PAGES';
83
+ const ctx = new context_1.Ctx(name.toUpperCase().replace(/-/g, '_'), config.i18n, root, lib);
84
+ const html = [];
85
+ const files = [];
86
+ const topLevel = [];
87
+ const modelClassNames = [];
88
+ let hasTable = false;
89
+ const render = (block) => {
90
+ switch (block.type) {
91
+ case 'page-header':
92
+ return (0, blocks_1.renderPageHeader)(ctx, block);
93
+ case 'stat':
94
+ return (0, blocks_1.renderStat)(ctx, block);
95
+ case 'chip-nav':
96
+ return (0, blocks_1.renderChipNav)(ctx, block);
97
+ case 'segmented':
98
+ return (0, blocks_1.renderSegmented)(ctx, block);
99
+ case 'language-switch':
100
+ return (0, blocks_1.renderLanguageSwitch)(ctx, block);
101
+ case 'card-grid':
102
+ return (0, blocks_1.renderCardGrid)(ctx, block);
103
+ case 'table': {
104
+ hasTable = true;
105
+ const table = (0, table_1.renderTable)(ctx, block, name);
106
+ files.push(table.configFile, ...table.modelFiles);
107
+ topLevel.push(...table.topLevel);
108
+ modelClassNames.push(...table.modelClassNames);
109
+ return table.html;
110
+ }
111
+ }
112
+ };
113
+ for (const block of config.blocks)
114
+ html.push(render(block));
115
+ // A class named like a model would hide it: add "Page".
116
+ const base = (0, naming_1.pascal)(name);
117
+ const className = modelClassNames.includes(base) ? `${base}Page` : base;
118
+ // ---- infrastructure that the blocks asked for ---------------------------------------------------------------------
119
+ if (ctx.needsTranslateService) {
120
+ ctx.imports.add('@angular/core', 'inject');
121
+ ctx.imports.add('@ngx-translate/core', 'TranslateService');
122
+ ctx.infrastructure.push('private readonly translate = inject(TranslateService);');
123
+ }
124
+ if (ctx.usesInstant) {
125
+ ctx.imports.add('@angular/core/rxjs-interop', 'toSignal');
126
+ ctx.imports.add('rxjs', 'map');
127
+ ctx.infrastructure.push('/** Changes with the language: the values that read it are evaluated again. */\nprivate readonly lang = toSignal(this.translate.onLangChange.pipe(map((event) => event.lang)), {\n initialValue: this.translate.currentLang\n});');
128
+ }
129
+ if (ctx.usesPipe) {
130
+ ctx.imports.add('@ngx-translate/core', 'TranslatePipe');
131
+ ctx.componentImports.add('TranslatePipe');
132
+ }
133
+ ctx.imports.add('@angular/core', 'Component');
134
+ // ---- the component ---------------------------------------------------------------------------------------------------
135
+ const componentImports = [...ctx.componentImports].sort((a, b) => a.localeCompare(b));
136
+ const importsList = componentImports.length > 3 ? `[\n${indentBlock(componentImports.join(',\n'), 4)}\n ]` : `[${componentImports.join(', ')}]`;
137
+ const styles = [':host { display: grid; gap: 16px; }', ...ctx.styles];
138
+ const members = [...ctx.infrastructure, ...ctx.members];
139
+ const prefix = config.selectorPrefix || 'app';
140
+ const component = [
141
+ ctx.imports.render(),
142
+ '',
143
+ ...(topLevel.length ? [topLevel.join('\n\n'), ''] : []),
144
+ '@Component({',
145
+ ` selector: '${prefix}-${name}',`,
146
+ ` imports: ${importsList},`,
147
+ ` templateUrl: './${name}.html',`,
148
+ ` styles: \`\n${indentBlock(styles.join('\n'), 4)}\n \``,
149
+ '})',
150
+ `export class ${className} {`,
151
+ members.length ? indentBlock(members.join('\n\n'), 2) : '',
152
+ '}',
153
+ ''
154
+ ].join('\n');
155
+ files.unshift({ path: `${name}.ts`, role: 'component', content: component }, { path: `${name}.html`, role: 'template', content: `${html.join('\n\n')}\n` });
156
+ // ---- notes for the developer -------------------------------------------------------------------------------------
157
+ const warnings = [];
158
+ if (hasTable && !config.i18n) {
159
+ warnings.push('The table of easy-mat-ui reads its labels through ngx-translate: keep provideTranslateService() in your application config (no dictionary is needed).');
160
+ }
161
+ if (hasTable) {
162
+ warnings.push('Add provideEasyPaginatorIntl() to your providers if you want the paginator to follow your language.');
163
+ }
164
+ if (config.blocks.some((block) => block.type === 'language-switch' && block.languages.some((language) => language.flag))) {
165
+ warnings.push('Flags use the flag-icons stylesheet: npm install flag-icons, then add "node_modules/flag-icons/css/flag-icons.min.css" to the styles of angular.json.');
166
+ }
167
+ const table = config.blocks.find((block) => block.type === 'table');
168
+ if (table?.type === 'table' && table.model.generate) {
169
+ // The generic model has fields named item1, item2...; a model written by the developer does not.
170
+ warnings.push(table.model.fields.some((field) => /^item\d+$/.test(field.name))
171
+ ? 'The model and the rows are placeholders (item1, item2...): rename them, or point the table to your own model.'
172
+ : 'The rows are example data: replace them with your own data. The model file was generated from the fields you gave.');
173
+ }
174
+ return {
175
+ className,
176
+ selector: `${prefix}-${name}`,
177
+ files,
178
+ translations: config.i18n ? { ...ctx.translations } : {},
179
+ standardTranslations: config.i18n && hasTable ? { ...catalog_1.STANDARD_TRANSLATIONS } : {},
180
+ warnings
181
+ };
182
+ }
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.isIdentifier = exports.singular = exports.label = exports.title = exports.constant = exports.camel = exports.pascal = exports.kebab = exports.sampleRecords = exports.validatePage = exports.generatePage = void 0;
18
+ __exportStar(require("./types"), exports);
19
+ __exportStar(require("./catalog"), exports);
20
+ var generate_1 = require("./generate");
21
+ Object.defineProperty(exports, "generatePage", { enumerable: true, get: function () { return generate_1.generatePage; } });
22
+ Object.defineProperty(exports, "validatePage", { enumerable: true, get: function () { return generate_1.validatePage; } });
23
+ var table_1 = require("./table");
24
+ Object.defineProperty(exports, "sampleRecords", { enumerable: true, get: function () { return table_1.sampleRecords; } });
25
+ var naming_1 = require("./naming");
26
+ Object.defineProperty(exports, "kebab", { enumerable: true, get: function () { return naming_1.kebab; } });
27
+ Object.defineProperty(exports, "pascal", { enumerable: true, get: function () { return naming_1.pascal; } });
28
+ Object.defineProperty(exports, "camel", { enumerable: true, get: function () { return naming_1.camel; } });
29
+ Object.defineProperty(exports, "constant", { enumerable: true, get: function () { return naming_1.constant; } });
30
+ Object.defineProperty(exports, "title", { enumerable: true, get: function () { return naming_1.title; } });
31
+ Object.defineProperty(exports, "label", { enumerable: true, get: function () { return naming_1.label; } });
32
+ Object.defineProperty(exports, "singular", { enumerable: true, get: function () { return naming_1.singular; } });
33
+ Object.defineProperty(exports, "isIdentifier", { enumerable: true, get: function () { return naming_1.isIdentifier; } });
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ /** Case conversions and quoting used by the generator. No dependency, so it runs in Node and in the browser. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.title = exports.constant = exports.camel = exports.pascal = exports.kebab = void 0;
5
+ exports.label = label;
6
+ exports.quote = quote;
7
+ exports.attributeEscape = attributeEscape;
8
+ exports.isIdentifier = isIdentifier;
9
+ exports.singular = singular;
10
+ const words = (text) => text
11
+ .replace(/([a-z])([A-Z])/g, '$1 $2')
12
+ .split(/[\s_.\-/]+/)
13
+ .filter(Boolean);
14
+ const capitalize = (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
15
+ const kebab = (text) => words(text).map((w) => w.toLowerCase()).join('-');
16
+ exports.kebab = kebab;
17
+ const pascal = (text) => words(text).map(capitalize).join('');
18
+ exports.pascal = pascal;
19
+ const camel = (text) => {
20
+ const value = (0, exports.pascal)(text);
21
+ return value.charAt(0).toLowerCase() + value.slice(1);
22
+ };
23
+ exports.camel = camel;
24
+ const constant = (text) => words(text).map((w) => w.toUpperCase()).join('_');
25
+ exports.constant = constant;
26
+ const title = (text) => words(text).map(capitalize).join(' ');
27
+ exports.title = title;
28
+ /** `isActive` gives "Active", `lastUpdatedDate` gives "Last updated date". */
29
+ function label(field) {
30
+ const text = words(field.replace(/^is(?=[A-Z])/, '')).join(' ').toLowerCase();
31
+ return text.charAt(0).toUpperCase() + text.slice(1);
32
+ }
33
+ /** A TypeScript string literal in single quotes. */
34
+ function quote(text) {
35
+ return `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n')}'`;
36
+ }
37
+ /** Text placed inside a double-quoted HTML attribute. */
38
+ function attributeEscape(text) {
39
+ return text.replace(/&/g, '&').replace(/"/g, '"');
40
+ }
41
+ /** A valid property name for a field or an id: letters, digits, `_` and `$`, not starting with a digit. */
42
+ function isIdentifier(text) {
43
+ return /^[A-Za-z_$][\w$]*$/.test(text);
44
+ }
45
+ /** `stock-items` gives `stock-item`: used to look for a model that matches a page name. */
46
+ function singular(text) {
47
+ const base = (0, exports.kebab)(text).replace(/-management$/, '');
48
+ if (/ies$/.test(base))
49
+ return base.replace(/ies$/, 'y');
50
+ if (/(ss|us)$/.test(base))
51
+ return base;
52
+ return base.replace(/s$/, '');
53
+ }
@@ -0,0 +1,310 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sampleRecords = sampleRecords;
4
+ exports.renderTable = renderTable;
5
+ const naming_1 = require("./naming");
6
+ const keyFieldOf = (model) => model.fields.find((f) => f.name === 'id') ?? model.fields[0];
7
+ /** The link from a child row to its parent, when the model has one. */
8
+ const parentLinkOf = (model) => model.fields.find((f) => f.name === 'parentId');
9
+ const isShown = (model, field, isChild) => field.name !== keyFieldOf(model).name && !(isChild && field.name === 'parentId');
10
+ const defaultValue = (field) => {
11
+ switch (field.type) {
12
+ case 'string':
13
+ return "''";
14
+ case 'number':
15
+ return '0';
16
+ case 'boolean':
17
+ return 'false';
18
+ case 'date':
19
+ return 'null';
20
+ }
21
+ };
22
+ const typeOf = (field) => (field.type === 'date' ? 'Date | null' : field.type);
23
+ /** A model file: a class whose properties have a default value, so `new Item()` is an empty row. */
24
+ function modelFile(model) {
25
+ const lines = model.fields.map((field) => field.type === 'date' ? ` ${field.name}: ${typeOf(field)} = null;` : ` ${field.name} = ${defaultValue(field)};`);
26
+ return { path: `${model.fileBase}.model.ts`, role: 'model', content: `export class ${model.className} {\n${lines.join('\n')}\n}\n` };
27
+ }
28
+ /**
29
+ * Example rows, so a page shows something as soon as it is generated. A child row points to a parent with `parentId`.
30
+ * The Builder of the demo shows these same rows in its preview.
31
+ */
32
+ function sampleRecords(model, count, parentCount = 0, isChild = false) {
33
+ const keyName = keyFieldOf(model).name;
34
+ return Array.from({ length: count }, (_, i) => {
35
+ const n = i + 1;
36
+ const row = {};
37
+ for (const field of model.fields) {
38
+ if (field.name === keyName)
39
+ row[field.name] = field.type === 'number' ? n : String(n);
40
+ else if (isChild && field.name === 'parentId')
41
+ row[field.name] = (i % Math.max(1, parentCount)) + 1;
42
+ else if (field.type === 'string')
43
+ row[field.name] = `${field.name} ${n}`;
44
+ else if (field.type === 'number')
45
+ row[field.name] = n * 10;
46
+ else if (field.type === 'boolean')
47
+ row[field.name] = n % 2 === 1;
48
+ else
49
+ row[field.name] = new Date(2026, 0, n);
50
+ }
51
+ return row;
52
+ });
53
+ }
54
+ const literal = (value) => (value instanceof Date ? `new Date(2026, 0, ${value.getDate()})` : typeof value === 'string' ? (0, naming_1.quote)(value) : String(value));
55
+ /** The example rows as a TypeScript constant. */
56
+ function sampleRows(model, name, count, parentCount, isChild) {
57
+ const rows = sampleRecords(model, count, parentCount, isChild).map((record) => ` { ${model.fields.map((field) => `${field.name}: ${literal(record[field.name])}`).join(', ')} }`);
58
+ // Properties that are left out would be missing from the rows: the cast says that it is intended.
59
+ const cast = model.ignored?.length ? ` as ${model.className}[]` : '';
60
+ return `const ${name}: ${model.className}[] = [\n${rows.join(',\n')}\n]${cast};`;
61
+ }
62
+ /** `PAGES.STOCK.` for the labels of the columns and of the dialog (the dialog reads `prefix + name`). */
63
+ const prefixOf = (ctx) => (ctx.i18n ? `${ctx.root}.${ctx.pageConstant}.` : '');
64
+ /** The text of a column title or a toolbar: a key of the translation file, or the text itself. */
65
+ function columnTitle(ctx, field) {
66
+ if (!ctx.i18n)
67
+ return (0, naming_1.quote)((0, naming_1.label)(field.name));
68
+ ctx.translations[`${prefixOf(ctx)}${field.name}`] = (0, naming_1.label)(field.name);
69
+ return `t(${(0, naming_1.quote)(field.name)})`;
70
+ }
71
+ /** Columns, dialog and table of one model, as three exported functions. */
72
+ function sideCode(ctx, block, side, hasChild) {
73
+ const { model, isChild } = side;
74
+ const base = (0, naming_1.camel)(model.className);
75
+ const filters = block.filters !== false && !isChild;
76
+ const shown = model.fields.filter((field) => isShown(model, field, isChild));
77
+ const firstText = shown.find((field) => field.type === 'string') ?? shown[0];
78
+ let filtered = 0;
79
+ const columns = shown.map((field) => {
80
+ const title = columnTitle(ctx, field);
81
+ if (field.type === 'boolean') {
82
+ return ` new MatColumnTyped({
83
+ name: ${(0, naming_1.quote)(field.name)},
84
+ type: ColumnType.ICON,
85
+ translateTitle: ${title},
86
+ enableIcon: 'check_circle',
87
+ disableIcon: 'cancel',
88
+ stickyClass: 'text-center',
89
+ conditionFn: (item: ${model.className}) => !!item.${field.name},
90
+ cssClassFn: (item: ${model.className}) => (item.${field.name} ? 'text-success' : 'text-danger')
91
+ })`;
92
+ }
93
+ const properties = [`name: ${(0, naming_1.quote)(field.name)}`, `translateTitle: ${title}`];
94
+ if (field.type === 'date')
95
+ properties.push('type: ColumnType.DATE');
96
+ if (filters && field.type === 'string' && filtered < 2) {
97
+ properties.push("enableFilter: true, filterType: 'text'");
98
+ filtered++;
99
+ }
100
+ return ` new MatColumnTyped({ ${properties.join(', ')} })`;
101
+ });
102
+ columns.push(" new MatColumnTyped({ name: 'actions', headerIcon: 'rule', stickyClass: 'text-center' })");
103
+ const dialogFields = shown.map((field, index) => {
104
+ const inputType = field.type === 'boolean' ? 'Checkbox' : field.type === 'number' ? 'Number' : field.type === 'date' ? 'Date' : undefined;
105
+ const properties = [`name: ${(0, naming_1.quote)(field.name)}`, `order: ${index + 1}`];
106
+ if (field === firstText)
107
+ properties.push('isRequired: true');
108
+ if (inputType)
109
+ properties.push(`inputType: InputType.${inputType}`);
110
+ return ` new MatColumnTyped({ ${properties.join(', ')} })`;
111
+ });
112
+ const empty = model.fields.map((field) => `${field.name}: ${defaultValue(field)}`).join(', ');
113
+ const entityKey = isChild ? 'CHILD_ENTITY' : 'ENTITY';
114
+ const entityText = isChild ? 'Sub-item' : 'Item';
115
+ let dialogTitle;
116
+ if (ctx.i18n) {
117
+ ctx.translations[`${prefixOf(ctx)}${entityKey}`] = (0, naming_1.label)(model.className) || entityText;
118
+ dialogTitle = (0, naming_1.quote)(`${prefixOf(ctx)}${entityKey}`);
119
+ }
120
+ else {
121
+ dialogTitle = (0, naming_1.quote)((0, naming_1.label)(model.className) || entityText);
122
+ }
123
+ const canCreate = block.canCreate !== false;
124
+ const canUpdate = block.canUpdate !== false;
125
+ const canDelete = block.canDelete !== false;
126
+ const pageSize = isChild ? 5 : block.pageSize ?? 10;
127
+ const tableProperties = [
128
+ " appearance: 'outline'",
129
+ ' withToolbar: true',
130
+ ` withFilterInHeader: ${filters}`,
131
+ ...(!isChild && hasChild ? [' isExpanded: true'] : []),
132
+ ` changePageSize: ${pageSize}`,
133
+ " sortedBy: ''",
134
+ ` canCreate: ${canCreate}`,
135
+ ` canUpdate: ${canUpdate}`,
136
+ ` canDelete: ${canDelete}`,
137
+ ' prefix: PREFIX',
138
+ ` displayedColumns: ${base}Columns()`,
139
+ ` toolbarConfig: new ToolbarConfig({ icon: ${(0, naming_1.quote)(block.icon ?? 'grid_view')}, translations: new ToolbarTranslations({ title: ctx.title }) })`,
140
+ ' data: ctx.data',
141
+ ` dialog: { add: ${canCreate}, edit: ${canUpdate}, view: true, mode: 'open', form: ${base}DialogForm }`
142
+ ];
143
+ return `export function ${base}Columns(): MatColumnTyped[] {
144
+ return [
145
+ ${columns.join(',\n')}
146
+ ];
147
+ }
148
+
149
+ export function ${base}DialogFields(): MatColumnTyped[] {
150
+ return [
151
+ ${dialogFields.join(',\n')}
152
+ ];
153
+ }
154
+
155
+ export function ${base}DialogForm(request: EasyTableDialogRequest<${model.className}>): EasyDialogInit<${model.className}> {
156
+ return {
157
+ title: ${dialogTitle},
158
+ titleField: ${(0, naming_1.quote)(firstText?.name ?? keyFieldOf(model).name)},
159
+ action: request.action,
160
+ data: request.action === CRUD.CREATE ? ({ ${empty} } as ${model.className}) : request.data,
161
+ fields: ${base}DialogFields(),
162
+ prefix: PREFIX,
163
+ withAuditFields: false
164
+ };
165
+ }
166
+
167
+ export interface ${model.className}TableCtx {
168
+ data: ${model.className}[];
169
+ /** Title of the toolbar, already translated. */
170
+ title: string;
171
+ }
172
+
173
+ export function ${base}Table(ctx: ${model.className}TableCtx): EasyTableConfig<${model.className}> {
174
+ return new EasyTableConfig<${model.className}>({
175
+ ${tableProperties.join(',\n')}
176
+ });
177
+ }`;
178
+ }
179
+ function renderTable(ctx, block, pageName) {
180
+ const sides = [{ model: block.model, isChild: false, title: block.title }];
181
+ if (block.child)
182
+ sides.push({ model: block.child.model, isChild: true, title: block.child.title ?? `${block.title} details` });
183
+ const hasChild = sides.length > 1;
184
+ const configName = `${pageName}.config`;
185
+ // ---- configuration file --------------------------------------------------------------------------------------
186
+ const imports = new Map();
187
+ const need = (from, ...names) => {
188
+ const set = imports.get(from) ?? new Set();
189
+ names.forEach((n) => set.add(n));
190
+ imports.set(from, set);
191
+ };
192
+ const code = sides.map((side) => sideCode(ctx, block, side, hasChild)).join('\n\n');
193
+ // Only what the generated code really uses is imported.
194
+ for (const name of ['ColumnType', 'CRUD', 'EasyDialogInit', 'EasyTableConfig', 'EasyTableDialogRequest', 'MatColumnTyped', 'ToolbarConfig', 'ToolbarTranslations']) {
195
+ if (new RegExp(`\\b${name}\\b`).test(code))
196
+ need(ctx.lib, name);
197
+ }
198
+ for (const side of sides) {
199
+ need(side.model.generate ? `./${side.model.fileBase}.model` : side.model.importPath ?? `./${side.model.fileBase}.model`, side.model.className);
200
+ }
201
+ const importLines = [...imports.entries()]
202
+ .sort(([a], [b]) => Number(a.startsWith('.')) - Number(b.startsWith('.')) || a.localeCompare(b))
203
+ .map(([from, names]) => `import { ${[...names].sort((a, b) => a.localeCompare(b)).join(', ')} } from '${from}';`)
204
+ .join('\n');
205
+ const header = [
206
+ importLines,
207
+ '',
208
+ ...(/InputType\./.test(code) ? ['const { InputType } = MatColumnTyped;'] : []),
209
+ // The dialog reads `prefix + name` for the label of each field, and the columns read `translateTitle`.
210
+ `const PREFIX = ${(0, naming_1.quote)(prefixOf(ctx))};`,
211
+ ...(ctx.i18n ? ['const t = (key: string) => PREFIX + key;'] : [])
212
+ ].join('\n');
213
+ const configFile = { path: `${configName}.ts`, role: 'config', content: `${header}\n\n${code}\n` };
214
+ // ---- models and example rows -------------------------------------------------------------------------------------
215
+ const modelFiles = sides.filter((s) => s.model.generate).map((s) => modelFile(s.model));
216
+ const topLevel = [];
217
+ const parentRows = 6;
218
+ const sampleName = (model) => `SAMPLE_${(0, naming_1.constant)(model.className)}S`;
219
+ topLevel.push(sampleRows(block.model, sampleName(block.model), parentRows, 0, false));
220
+ if (block.child)
221
+ topLevel.push(sampleRows(block.child.model, sampleName(block.child.model), 10, parentRows, true));
222
+ // ---- members of the component ------------------------------------------------------------------------------------
223
+ const parent = block.model;
224
+ const parentKey = keyFieldOf(parent).name;
225
+ const parentBase = (0, naming_1.camel)(parent.className);
226
+ ctx.imports.add('@angular/core', 'computed', 'signal');
227
+ ctx.useComponent('EasyTableComponent');
228
+ ctx.useLib('CRUD', 'EasyTableDialogResult');
229
+ ctx.imports.add(`./${configName}`, ...sides.map((s) => `${(0, naming_1.camel)(s.model.className)}Table`));
230
+ for (const side of sides) {
231
+ ctx.imports.add(side.model.generate ? `./${side.model.fileBase}.model` : side.model.importPath ?? `./${side.model.fileBase}.model`, side.model.className);
232
+ }
233
+ const canCreate = block.canCreate !== false;
234
+ const canUpdate = block.canUpdate !== false;
235
+ const canDelete = block.canDelete !== false;
236
+ const reads = ctx.i18n ? ' this.lang();\n' : '';
237
+ const title = (suffix, text) => ctx.ts(suffix, text);
238
+ const nextKey = (rowsVar, model) => {
239
+ const key = keyFieldOf(model);
240
+ return key.type === 'number'
241
+ ? `Math.max(0, ...${rowsVar}.map((row) => row.${key.name})) + 1`
242
+ : `String(Date.now())`;
243
+ };
244
+ ctx.members.push(`readonly rows = signal<${parent.className}[]>(${sampleName(parent)});`);
245
+ ctx.members.push(`readonly tableConfig = computed(() => {\n${reads} return ${parentBase}Table({ data: this.rows(), title: ${title('TABLE_TITLE', block.title)} });\n});`);
246
+ if (canCreate || canUpdate) {
247
+ ctx.members.push(`onDialogResult({ result }: EasyTableDialogResult<${parent.className}>): void {
248
+ if (result.event !== CRUD.CREATE && result.event !== CRUD.UPDATE) return;
249
+ const saved = result.data as ${parent.className};
250
+ // Replace the next lines with a call to your service when the data comes from an API.
251
+ this.rows.update((rows) =>
252
+ rows.some((row) => row.${parentKey} === saved.${parentKey})
253
+ ? rows.map((row) => (row.${parentKey} === saved.${parentKey} ? saved : row))
254
+ : [...rows, { ...saved, ${parentKey}: ${nextKey('rows', parent)} }]
255
+ );
256
+ }`);
257
+ }
258
+ if (canDelete) {
259
+ ctx.members.push(`onDelete(item: object): void {
260
+ const { ${parentKey} } = item as ${parent.className};
261
+ // Replace the next line with a call to your service when the data comes from an API.
262
+ this.rows.update((rows) => rows.filter((row) => row.${parentKey} !== ${parentKey}));
263
+ }`);
264
+ }
265
+ if (block.child) {
266
+ const child = block.child.model;
267
+ const childKey = keyFieldOf(child).name;
268
+ const childBase = (0, naming_1.camel)(child.className);
269
+ const link = parentLinkOf(child);
270
+ const childTitle = block.child.title ?? `${block.title} details`;
271
+ ctx.members.push(`private readonly allChildRows = signal<${child.className}[]>(${sampleName(child)});`);
272
+ ctx.members.push(`private readonly currentParent = signal<${parent.className} | null>(null);`);
273
+ ctx.members.push(link
274
+ ? `readonly childRows = computed(() => {\n const parent = this.currentParent();\n return this.allChildRows().filter((row) => row.${link.name} === parent?.${parentKey});\n});`
275
+ : `// The rows of the child table. Filter them by the row that is open (this.currentParent()).\nreadonly childRows = computed(() => this.allChildRows());`);
276
+ ctx.members.push(`readonly childConfig = computed(() => {\n${reads} return ${childBase}Table({ data: this.childRows(), title: ${title('CHILD_TITLE', childTitle)} });\n});`);
277
+ ctx.members.push(`onExtendRow(parent: ${parent.className} | null): void {\n this.currentParent.set(parent);\n}`);
278
+ if (canCreate || canUpdate) {
279
+ ctx.members.push(`onChildDialogResult({ result }: EasyTableDialogResult<${child.className}>): void {
280
+ if (result.event !== CRUD.CREATE && result.event !== CRUD.UPDATE) return;
281
+ const saved = result.data as ${child.className};
282
+ // Replace the next lines with a call to your service when the data comes from an API.
283
+ this.allChildRows.update((rows) =>
284
+ rows.some((row) => row.${childKey} === saved.${childKey})
285
+ ? rows.map((row) => (row.${childKey} === saved.${childKey} ? saved : row))
286
+ : [...rows, { ...saved, ${childKey}: ${nextKey('rows', child)}${link ? `, ${link.name}: this.currentParent()?.${parentKey} ?? saved.${link.name}` : ''} }]
287
+ );
288
+ }`);
289
+ }
290
+ if (canDelete) {
291
+ ctx.members.push(`onDeleteChild(item: object): void {
292
+ const { ${childKey} } = item as ${child.className};
293
+ // Replace the next line with a call to your service when the data comes from an API.
294
+ this.allChildRows.update((rows) => rows.filter((row) => row.${childKey} !== ${childKey}));
295
+ }`);
296
+ }
297
+ }
298
+ // ---- template ------------------------------------------------------------------------------------------------------
299
+ const bindings = [
300
+ '[config]="tableConfig()"',
301
+ block.child ? '[childConfig]="childConfig()"' : '',
302
+ canCreate || canUpdate ? '(dialogResult)="onDialogResult($event)"' : '',
303
+ canDelete ? '(deleteItem)="onDelete($event)"' : '',
304
+ block.child ? '(extendRow)="onExtendRow($event)"' : '',
305
+ block.child && (canCreate || canUpdate) ? '(childDialogResult)="onChildDialogResult($event)"' : '',
306
+ block.child && canDelete ? '(deleteChildItem)="onDeleteChild($event)"' : ''
307
+ ].filter(Boolean);
308
+ const html = `<lib-easy-table\n ${bindings.join('\n ')} />`;
309
+ return { html, configFile, modelFiles, topLevel, modelClassNames: sides.map((s) => s.model.className) };
310
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * What a page is made of. A `PageConfig` is plain data (it can be written as JSON), so the CLI, the Builder of the demo
4
+ * and a developer by hand all describe a page the same way, and `generatePage` turns it into files.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,39 @@
1
+ .bg-yellow {
2
+ background-color: var(--color-yellow, #ffb804) !important;
3
+ }
4
+
5
+ .bg-morning-blue {
6
+ background-color: var(--color-morning-blue, #82a7a6) !important;
7
+ }
8
+
9
+ .bg-blue {
10
+ background-color: var(--color-primary-blue, #6b95aa) !important;
11
+ }
12
+
13
+ .bg-morning-clear-green {
14
+ background-color: var(--color-morning-clear-green, #d1e0e0) !important;
15
+ }
16
+
17
+ .bg-taupe {
18
+ background-color: var(--color-taupe, #785964) !important;
19
+ }
20
+
21
+ .bg-red {
22
+ background-color: var(--color-red, #f44438) !important;
23
+ }
24
+
25
+ .bg-orange {
26
+ background-color: var(--color-orange, tomato) !important;
27
+ }
28
+
29
+ .bg-green {
30
+ background-color: var(--color-green, #4caf50) !important;
31
+ }
32
+
33
+ .bg-info {
34
+ background-color: var(--color-info, #00bcd4) !important;
35
+ }
36
+
37
+ .bg-white{
38
+ background-color: white;
39
+ }