easy-mat-ui 0.0.7 → 1.1.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.
- package/LICENSE +21 -0
- package/README.md +482 -63
- package/fesm2022/easy-mat-ui.mjs +3724 -564
- package/fesm2022/easy-mat-ui.mjs.map +1 -1
- package/index.d.ts +1221 -55
- package/package.json +59 -22
- package/page-generator/blocks.js +155 -0
- package/page-generator/catalog.js +132 -0
- package/page-generator/cli/main.js +314 -0
- package/page-generator/cli/project.js +252 -0
- package/page-generator/context.js +108 -0
- package/page-generator/generate.js +182 -0
- package/page-generator/index.js +33 -0
- package/page-generator/naming.js +53 -0
- package/page-generator/table.js +310 -0
- package/page-generator/types.js +6 -0
- package/styles/styles/_backgrounds.scss +39 -0
- package/styles/styles/_buttons.scss +90 -0
- package/styles/styles/_colors.scss +197 -0
- package/styles/styles/_effects.scss +44 -0
- package/styles/styles/_material-overrides.scss +106 -0
- package/styles/styles/_spacing.scss +68 -0
- package/styles/styles/_tables.scss +569 -0
- package/styles/styles/_typography.scss +100 -0
- package/styles/styles.scss +29 -0
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
4
|
+
if (k2 === undefined) k2 = k;
|
|
5
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
6
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
7
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
8
|
+
}
|
|
9
|
+
Object.defineProperty(o, k2, desc);
|
|
10
|
+
}) : (function(o, m, k, k2) {
|
|
11
|
+
if (k2 === undefined) k2 = k;
|
|
12
|
+
o[k2] = m[k];
|
|
13
|
+
}));
|
|
14
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
15
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
16
|
+
}) : function(o, v) {
|
|
17
|
+
o["default"] = v;
|
|
18
|
+
});
|
|
19
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
20
|
+
var ownKeys = function(o) {
|
|
21
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
22
|
+
var ar = [];
|
|
23
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
24
|
+
return ar;
|
|
25
|
+
};
|
|
26
|
+
return ownKeys(o);
|
|
27
|
+
};
|
|
28
|
+
return function (mod) {
|
|
29
|
+
if (mod && mod.__esModule) return mod;
|
|
30
|
+
var result = {};
|
|
31
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
32
|
+
__setModuleDefault(result, mod);
|
|
33
|
+
return result;
|
|
34
|
+
};
|
|
35
|
+
})();
|
|
36
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
|
+
const fs = __importStar(require("fs"));
|
|
38
|
+
const path = __importStar(require("path"));
|
|
39
|
+
const readline = __importStar(require("readline/promises"));
|
|
40
|
+
const catalog_1 = require("../catalog");
|
|
41
|
+
const generate_1 = require("../generate");
|
|
42
|
+
const naming_1 = require("../naming");
|
|
43
|
+
const project_1 = require("./project");
|
|
44
|
+
const USAGE = `Generates an Angular page from the components of easy-mat-ui.
|
|
45
|
+
|
|
46
|
+
Usage: npx easy-mat-ui add-page [options]
|
|
47
|
+
|
|
48
|
+
Options:
|
|
49
|
+
--name <name> page name in kebab-case (asked when missing)
|
|
50
|
+
--dir <folder> destination folder, relative to the project (default: src/app/pages)
|
|
51
|
+
--blocks <list> components, separated by commas. Available:
|
|
52
|
+
${catalog_1.BLOCK_CATALOG.map((b) => b.type).join(', ')}
|
|
53
|
+
--table-model <name> model of the table: a name (stock-item), a path, or "generic".
|
|
54
|
+
Without it, a model that matches the page name is reused, else a generic one is generated
|
|
55
|
+
--child add a second table opened under a row, with a generic model
|
|
56
|
+
--child-model <name> add a second table with this existing model
|
|
57
|
+
--i18n / --no-i18n with translation keys (ngx-translate), or with plain texts.
|
|
58
|
+
Default: keys when @ngx-translate/core is installed
|
|
59
|
+
--i18n-dir <folder> folder of the translation files (default: public/assets/i18n or src/assets/i18n)
|
|
60
|
+
--i18n-root <KEY> first part of the translation keys (default: PAGES)
|
|
61
|
+
--prefix <prefix> prefix of the selector (default: the one of angular.json, or app)
|
|
62
|
+
--lib <package> package to import from (default: the installed one, easy-mat-ui)
|
|
63
|
+
--config <file.json> a complete page description, for example exported by the Builder of the demo
|
|
64
|
+
--dry-run show what would be done, write nothing
|
|
65
|
+
--print with --dry-run, show the content of the files
|
|
66
|
+
--help show this help
|
|
67
|
+
|
|
68
|
+
Missing answers are asked interactively. Nothing is ever installed.`;
|
|
69
|
+
function parseArguments(argv) {
|
|
70
|
+
const flags = {};
|
|
71
|
+
const positional = [];
|
|
72
|
+
for (let i = 0; i < argv.length; i++) {
|
|
73
|
+
const arg = argv[i];
|
|
74
|
+
if (arg.startsWith('--no-')) {
|
|
75
|
+
flags[arg.slice(5)] = false;
|
|
76
|
+
}
|
|
77
|
+
else if (arg.startsWith('--')) {
|
|
78
|
+
const next = argv[i + 1];
|
|
79
|
+
const hasValue = next !== undefined && !next.startsWith('--');
|
|
80
|
+
flags[arg.slice(2)] = hasValue ? next : true;
|
|
81
|
+
if (hasValue)
|
|
82
|
+
i++;
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
positional.push(arg);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return { flags, positional };
|
|
89
|
+
}
|
|
90
|
+
const text = (flags, key) => (typeof flags[key] === 'string' ? flags[key] : undefined);
|
|
91
|
+
// ---- questions ---------------------------------------------------------------------------------------------------------
|
|
92
|
+
function createPrompter() {
|
|
93
|
+
const reader = readline.createInterface({ input: process.stdin });
|
|
94
|
+
const lines = reader[Symbol.asyncIterator]();
|
|
95
|
+
const ask = async (question, fallback = '') => {
|
|
96
|
+
process.stdout.write(`${question}${fallback ? ` [${fallback}]` : ''}: `);
|
|
97
|
+
const { value, done } = await lines.next();
|
|
98
|
+
if (done)
|
|
99
|
+
throw new Error('Input interrupted.');
|
|
100
|
+
return String(value).trim() || fallback;
|
|
101
|
+
};
|
|
102
|
+
const askRequired = async (question) => {
|
|
103
|
+
for (;;) {
|
|
104
|
+
const answer = await ask(question);
|
|
105
|
+
if (answer)
|
|
106
|
+
return answer;
|
|
107
|
+
console.log(' This value is required.');
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
const askYesNo = async (question, fallback) => ['y', 'yes'].includes((await ask(`${question} (y/n)`, fallback)).toLowerCase());
|
|
111
|
+
const choose = async (question, options) => {
|
|
112
|
+
options.forEach((option, index) => console.log(` ${index + 1}. ${option}`));
|
|
113
|
+
for (;;) {
|
|
114
|
+
const index = Number(await ask(question, '1')) - 1;
|
|
115
|
+
if (options[index])
|
|
116
|
+
return index;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const close = () => {
|
|
120
|
+
reader.close();
|
|
121
|
+
process.stdin.destroy();
|
|
122
|
+
};
|
|
123
|
+
return { ask, askRequired, askYesNo, choose, close };
|
|
124
|
+
}
|
|
125
|
+
/** The menu of components, by category; the answer is a list of numbers. */
|
|
126
|
+
async function askBlocks(prompter) {
|
|
127
|
+
console.log('\nComponents of the page:');
|
|
128
|
+
const numbered = [];
|
|
129
|
+
for (const category of catalog_1.BLOCK_CATEGORIES) {
|
|
130
|
+
const group = catalog_1.BLOCK_CATALOG.filter((block) => block.category === category);
|
|
131
|
+
if (!group.length)
|
|
132
|
+
continue;
|
|
133
|
+
console.log(` ${category}`);
|
|
134
|
+
for (const block of group) {
|
|
135
|
+
numbered.push(block.type);
|
|
136
|
+
console.log(` ${String(numbered.length).padStart(2)}. ${block.label}: ${block.description}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const defaults = [numbered.indexOf('page-header') + 1, numbered.indexOf('table') + 1].join(',');
|
|
140
|
+
for (;;) {
|
|
141
|
+
const answer = await prompter.ask('Numbers separated by commas', defaults);
|
|
142
|
+
const picked = answer.split(',').map((n) => numbered[Number(n.trim()) - 1]);
|
|
143
|
+
if (picked.length && picked.every(Boolean))
|
|
144
|
+
return [...new Set(picked)];
|
|
145
|
+
console.log(' Enter numbers from the list, for example 1,2.');
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
// ---- building the description of the page -----------------------------------------------------------------------------
|
|
149
|
+
async function pickModel(root, name, pageDirectory, warnings, prompter, label) {
|
|
150
|
+
const files = (0, project_1.findModelFiles)(root, name);
|
|
151
|
+
if (!files.length)
|
|
152
|
+
return null;
|
|
153
|
+
let file = files[0];
|
|
154
|
+
if (files.length > 1) {
|
|
155
|
+
const shown = files.map((f) => (0, project_1.toPosix)(path.relative(root, f)));
|
|
156
|
+
if (!prompter)
|
|
157
|
+
throw new Error(`Several files match "${name}":\n ${shown.join('\n ')}\nGive the path of the one to use.`);
|
|
158
|
+
console.log(`Several files match "${name}" (${label}):`);
|
|
159
|
+
file = files[await prompter.choose('Which one?', shown)];
|
|
160
|
+
}
|
|
161
|
+
return (0, project_1.parseModel)(root, file, pageDirectory, warnings);
|
|
162
|
+
}
|
|
163
|
+
async function buildTable(flags, root, name, pageDirectory, notes, prompter) {
|
|
164
|
+
const block = (0, catalog_1.defaultBlock)('table', name);
|
|
165
|
+
const requested = text(flags, 'table-model');
|
|
166
|
+
if (requested && requested !== 'generic') {
|
|
167
|
+
const model = await pickModel(root, requested, pageDirectory, notes, prompter, 'table');
|
|
168
|
+
if (!model)
|
|
169
|
+
throw new Error(`Model "${requested}" not found in src/, projects/, apps/ or libs/ (expected: ${(0, naming_1.kebab)(requested)}.model.ts).`);
|
|
170
|
+
block.model = model;
|
|
171
|
+
}
|
|
172
|
+
else if (!requested) {
|
|
173
|
+
// No model asked for: reuse one that matches the page name.
|
|
174
|
+
for (const candidate of new Set([(0, naming_1.kebab)(name), (0, naming_1.singular)(name)])) {
|
|
175
|
+
const model = await pickModel(root, candidate, pageDirectory, notes, prompter, 'table');
|
|
176
|
+
if (model) {
|
|
177
|
+
console.log(`Reusing the existing model ${model.className} (${model.importPath}). Use --table-model generic to get a generic one.`);
|
|
178
|
+
block.model = model;
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const childName = text(flags, 'child-model');
|
|
184
|
+
let wantsChild = flags.child === true || Boolean(childName);
|
|
185
|
+
if (!wantsChild && flags.child !== false && prompter && !flags.blocks)
|
|
186
|
+
wantsChild = await prompter.askYesNo('Open a second table under each row of the first one?', 'n');
|
|
187
|
+
if (wantsChild) {
|
|
188
|
+
let child = null;
|
|
189
|
+
if (childName && childName !== 'generic') {
|
|
190
|
+
child = await pickModel(root, childName, pageDirectory, notes, prompter, 'child table');
|
|
191
|
+
if (!child)
|
|
192
|
+
throw new Error(`Model "${childName}" not found.`);
|
|
193
|
+
}
|
|
194
|
+
block.child = { title: `${block.title} details`, model: child ?? (0, catalog_1.genericChildModel)() };
|
|
195
|
+
}
|
|
196
|
+
return block;
|
|
197
|
+
}
|
|
198
|
+
async function buildPlan(flags, root, prompter) {
|
|
199
|
+
const notes = [];
|
|
200
|
+
const configFile = text(flags, 'config');
|
|
201
|
+
let name = text(flags, 'name');
|
|
202
|
+
let config = null;
|
|
203
|
+
if (configFile) {
|
|
204
|
+
config = (0, project_1.readJson)(path.resolve(process.cwd(), configFile));
|
|
205
|
+
name = name ?? config.name;
|
|
206
|
+
}
|
|
207
|
+
name = name ?? (prompter ? await prompter.askRequired('Page name in kebab-case (for example stock-items)') : undefined);
|
|
208
|
+
if (!name)
|
|
209
|
+
throw new Error('The page needs a name: use --name.');
|
|
210
|
+
name = (0, naming_1.kebab)(name);
|
|
211
|
+
const defaultDirectory = (0, project_1.defaultPagesDirectory)(root);
|
|
212
|
+
const directory = (0, project_1.toPosix)(path.normalize(text(flags, 'dir') ?? (prompter && !configFile && !flags.blocks ? await prompter.ask('Destination folder', defaultDirectory) : defaultDirectory))).replace(/\/$/, '');
|
|
213
|
+
const pageDirectory = path.resolve(root, directory, name);
|
|
214
|
+
const detected = (0, project_1.usesNgxTranslate)(root);
|
|
215
|
+
let i18n = flags.i18n === true ? true : flags.i18n === false ? false : detected;
|
|
216
|
+
if (config) {
|
|
217
|
+
config.name = name;
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
const types = text(flags, 'blocks')?.split(',').map((t) => t.trim()).filter(Boolean) ?? (prompter ? await askBlocks(prompter) : undefined);
|
|
221
|
+
if (!types?.length)
|
|
222
|
+
throw new Error('Choose the components of the page with --blocks or answer the questions.');
|
|
223
|
+
const known = catalog_1.BLOCK_CATALOG.map((b) => b.type);
|
|
224
|
+
const unknown = types.filter((t) => !known.includes(t));
|
|
225
|
+
if (unknown.length)
|
|
226
|
+
throw new Error(`Unknown component: ${unknown.join(', ')}. Available: ${known.join(', ')}.`);
|
|
227
|
+
const blocks = [];
|
|
228
|
+
for (const type of types) {
|
|
229
|
+
blocks.push(type === 'table' ? await buildTable(flags, root, name, pageDirectory, notes, prompter) : (0, catalog_1.defaultBlock)(type, name));
|
|
230
|
+
}
|
|
231
|
+
if (detected && flags.i18n === undefined && prompter && !flags.blocks) {
|
|
232
|
+
i18n = await prompter.askYesNo('ngx-translate is installed: generate translation keys and add them to the English file?', 'y');
|
|
233
|
+
}
|
|
234
|
+
config = { name, i18n, blocks };
|
|
235
|
+
}
|
|
236
|
+
config.libPackage = text(flags, 'lib') ?? config.libPackage ?? (0, project_1.detectLibrary)(root);
|
|
237
|
+
config.i18n = flags.i18n === true ? true : flags.i18n === false ? false : config.i18n ?? i18n;
|
|
238
|
+
config.i18nRoot = text(flags, 'i18n-root') ?? config.i18nRoot;
|
|
239
|
+
config.selectorPrefix = text(flags, 'prefix') ?? config.selectorPrefix ?? prefixOf(root, directory);
|
|
240
|
+
return { config, directory, notes };
|
|
241
|
+
}
|
|
242
|
+
/** The prefix of the Angular project that contains the folder, from angular.json. */
|
|
243
|
+
function prefixOf(root, directory) {
|
|
244
|
+
const file = path.join(root, 'angular.json');
|
|
245
|
+
if (!fs.existsSync(file))
|
|
246
|
+
return 'app';
|
|
247
|
+
const projects = (0, project_1.readJson)(file).projects ?? {};
|
|
248
|
+
const match = Object.values(projects).find((project) => project.sourceRoot && `${directory}/`.startsWith(`${(0, project_1.toPosix)(project.sourceRoot)}/`));
|
|
249
|
+
return match?.prefix ?? 'app';
|
|
250
|
+
}
|
|
251
|
+
// ---- writing --------------------------------------------------------------------------------------------------------------
|
|
252
|
+
function run(plan, root, flags) {
|
|
253
|
+
const dryRun = flags['dry-run'] === true;
|
|
254
|
+
const { config, directory } = plan;
|
|
255
|
+
const result = (0, generate_1.generatePage)(config);
|
|
256
|
+
const pageDirectory = path.resolve(root, directory, config.name);
|
|
257
|
+
if (fs.existsSync(pageDirectory))
|
|
258
|
+
throw new Error(`${(0, project_1.toPosix)(path.relative(root, pageDirectory))} already exists: nothing was generated.`);
|
|
259
|
+
const shown = (file) => (0, project_1.toPosix)(path.relative(root, file));
|
|
260
|
+
const label = dryRun ? '(dry run) ' : '';
|
|
261
|
+
for (const file of result.files) {
|
|
262
|
+
const target = path.join(pageDirectory, file.path);
|
|
263
|
+
if (!dryRun) {
|
|
264
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
265
|
+
fs.writeFileSync(target, file.content, 'utf8');
|
|
266
|
+
}
|
|
267
|
+
console.log(`${dryRun ? '📝' : '✅'} ${label}${shown(target)}`);
|
|
268
|
+
if (dryRun && flags.print === true)
|
|
269
|
+
console.log(`\n${file.content}\n`);
|
|
270
|
+
}
|
|
271
|
+
if (config.i18n) {
|
|
272
|
+
const translationFile = (0, project_1.findTranslationFile)(root, text(flags, 'i18n-dir'));
|
|
273
|
+
const outcome = (0, project_1.planTranslations)(translationFile, result.translations, result.standardTranslations);
|
|
274
|
+
if (outcome.note)
|
|
275
|
+
console.log(`⚠️ ${outcome.note}`);
|
|
276
|
+
else if (!outcome.added.length)
|
|
277
|
+
console.log(`⏭️ ${shown(translationFile)}: nothing to add.`);
|
|
278
|
+
else {
|
|
279
|
+
if (!dryRun)
|
|
280
|
+
outcome.write?.();
|
|
281
|
+
console.log(`${dryRun ? '📝' : '✅'} ${label}${shown(translationFile)}: ${outcome.added.length} keys`);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
[...plan.notes, ...result.warnings].forEach((note) => console.log(`⚠️ ${note}`));
|
|
285
|
+
// The route file sits in the `app` folder: import the page relative to it.
|
|
286
|
+
const posixPage = (0, project_1.toPosix)(path.join(pageDirectory, config.name));
|
|
287
|
+
const appFolder = posixPage.lastIndexOf('/app/');
|
|
288
|
+
const importPath = appFolder >= 0 ? posixPage.slice(appFolder + '/app/'.length) : (0, project_1.toPosix)(path.relative(path.join(root, 'src/app'), path.join(pageDirectory, config.name)));
|
|
289
|
+
console.log(`
|
|
290
|
+
Done${dryRun ? ' (dry run)' : ''}. To show the page:
|
|
291
|
+
- in a template: <${result.selector}></${result.selector}> (add ${result.className} to the imports of the component)
|
|
292
|
+
- or as a route: { path: '${config.name}', title: '${(0, naming_1.title)(config.name)}', loadComponent: () => import('./${importPath}').then((m) => m.${result.className}) }`);
|
|
293
|
+
}
|
|
294
|
+
async function main() {
|
|
295
|
+
const { flags, positional } = parseArguments(process.argv.slice(2));
|
|
296
|
+
const command = positional[0] ?? 'add-page';
|
|
297
|
+
if (flags.help === true || command === 'help')
|
|
298
|
+
return console.log(USAGE);
|
|
299
|
+
if (command !== 'add-page')
|
|
300
|
+
throw new Error(`Unknown command "${command}". Try: npx easy-mat-ui add-page --help`);
|
|
301
|
+
const root = (0, project_1.findProjectRoot)(process.cwd());
|
|
302
|
+
const answered = Boolean(flags.name || flags.config) && Boolean(flags.blocks || flags.config);
|
|
303
|
+
const prompter = answered ? null : createPrompter();
|
|
304
|
+
try {
|
|
305
|
+
run(await buildPlan(flags, root, prompter), root, flags);
|
|
306
|
+
}
|
|
307
|
+
finally {
|
|
308
|
+
prompter?.close();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
main().catch((error) => {
|
|
312
|
+
console.error(`\x1b[31mError: ${error.message}\x1b[0m`);
|
|
313
|
+
process.exit(1);
|
|
314
|
+
});
|
|
@@ -0,0 +1,252 @@
|
|
|
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
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
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.usesNgxTranslate = exports.toPosix = void 0;
|
|
37
|
+
exports.readJson = readJson;
|
|
38
|
+
exports.findProjectRoot = findProjectRoot;
|
|
39
|
+
exports.detectLibrary = detectLibrary;
|
|
40
|
+
exports.defaultPagesDirectory = defaultPagesDirectory;
|
|
41
|
+
exports.findTranslationFile = findTranslationFile;
|
|
42
|
+
exports.findModelFiles = findModelFiles;
|
|
43
|
+
exports.parseModel = parseModel;
|
|
44
|
+
exports.planTranslations = planTranslations;
|
|
45
|
+
const fs = __importStar(require("fs"));
|
|
46
|
+
const path = __importStar(require("path"));
|
|
47
|
+
const naming_1 = require("../naming");
|
|
48
|
+
/*
|
|
49
|
+
* What the command learns about the project it runs in: where it is, which package gives the components, whether
|
|
50
|
+
* ngx-translate is used, where the translations and the models are. It never installs anything.
|
|
51
|
+
*/
|
|
52
|
+
const SKIPPED = new Set(['node_modules', 'dist', 'tmp', '.git', '.angular', '.nx', 'out-tsc', 'coverage']);
|
|
53
|
+
const toPosix = (file) => file.split(path.sep).join('/');
|
|
54
|
+
exports.toPosix = toPosix;
|
|
55
|
+
function readJson(file) {
|
|
56
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
57
|
+
}
|
|
58
|
+
/** The folder with the `package.json`, looking upward from where the command was started. */
|
|
59
|
+
function findProjectRoot(start) {
|
|
60
|
+
let current = path.resolve(start);
|
|
61
|
+
for (;;) {
|
|
62
|
+
if (fs.existsSync(path.join(current, 'package.json')))
|
|
63
|
+
return current;
|
|
64
|
+
const parent = path.dirname(current);
|
|
65
|
+
if (parent === current)
|
|
66
|
+
throw new Error('No package.json found: run this command inside an Angular project.');
|
|
67
|
+
current = parent;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function dependencies(root) {
|
|
71
|
+
const pkg = readJson(path.join(root, 'package.json'));
|
|
72
|
+
return { ...pkg.devDependencies, ...pkg.dependencies };
|
|
73
|
+
}
|
|
74
|
+
/** The package the components are imported from: the one that is installed, `easy-mat-ui` otherwise. */
|
|
75
|
+
function detectLibrary(root) {
|
|
76
|
+
const deps = dependencies(root);
|
|
77
|
+
return ['easy-mat-ui', '@lih/easy-mat-ui', 'easy-mat-ui'].find((name) => name in deps) ?? 'easy-mat-ui';
|
|
78
|
+
}
|
|
79
|
+
const usesNgxTranslate = (root) => '@ngx-translate/core' in dependencies(root);
|
|
80
|
+
exports.usesNgxTranslate = usesNgxTranslate;
|
|
81
|
+
/** `src/app/pages` when the project has it, otherwise `src/app`. */
|
|
82
|
+
function defaultPagesDirectory(root) {
|
|
83
|
+
if (fs.existsSync(path.join(root, 'src/app/pages')))
|
|
84
|
+
return 'src/app/pages';
|
|
85
|
+
if (fs.existsSync(path.join(root, 'src/app')))
|
|
86
|
+
return 'src/app/pages';
|
|
87
|
+
return 'src/app';
|
|
88
|
+
}
|
|
89
|
+
/** The English translation file: in the folder given, or the usual places. */
|
|
90
|
+
function findTranslationFile(root, directory) {
|
|
91
|
+
const candidates = directory
|
|
92
|
+
? [path.resolve(root, directory, 'en.json')]
|
|
93
|
+
: ['public/assets/i18n', 'src/assets/i18n', 'public/i18n', 'src/assets/locale'].map((dir) => path.join(root, dir, 'en.json'));
|
|
94
|
+
return candidates.find((file) => fs.existsSync(file)) ?? null;
|
|
95
|
+
}
|
|
96
|
+
function walk(directory, visit) {
|
|
97
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
98
|
+
if (SKIPPED.has(entry.name))
|
|
99
|
+
continue;
|
|
100
|
+
const full = path.join(directory, entry.name);
|
|
101
|
+
if (entry.isDirectory())
|
|
102
|
+
walk(full, visit);
|
|
103
|
+
else
|
|
104
|
+
visit(full);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Files named `<name>.model.ts` (or `<name>.ts` when a path or a name is given exactly) in the sources of the project. */
|
|
108
|
+
function findModelFiles(root, name) {
|
|
109
|
+
const direct = [path.resolve(process.cwd(), name), path.resolve(root, name)].find((file) => file.endsWith('.ts') && fs.existsSync(file));
|
|
110
|
+
if (direct)
|
|
111
|
+
return [direct];
|
|
112
|
+
const wanted = (0, naming_1.kebab)(name.replace(/\.ts$/, '').replace(/\.model$/i, ''));
|
|
113
|
+
const found = [];
|
|
114
|
+
for (const folder of ['src', 'projects', 'apps', 'libs']) {
|
|
115
|
+
const start = path.join(root, folder);
|
|
116
|
+
if (!fs.existsSync(start))
|
|
117
|
+
continue;
|
|
118
|
+
walk(start, (file) => {
|
|
119
|
+
if (file.endsWith('.model.ts') && (0, naming_1.kebab)(path.basename(file, '.model.ts')) === wanted)
|
|
120
|
+
found.push(file);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return found;
|
|
124
|
+
}
|
|
125
|
+
function typescriptOf(root) {
|
|
126
|
+
try {
|
|
127
|
+
return require(require.resolve('typescript', { paths: [root] }));
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
throw new Error('TypeScript was not found in the project: it is needed to read an existing model.');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const NULLABLE = '(\\|null|\\|undefined)*';
|
|
134
|
+
const STRING_LITERAL = `('[^']*'|"[^"]*")`;
|
|
135
|
+
/** The kind of a property, or null when it is not text, a number, a boolean or a date (a list, an object, an enum...). */
|
|
136
|
+
function fieldType(ts, node, source) {
|
|
137
|
+
const text = node.type?.getText(source).replace(/\s+/g, '') ?? '';
|
|
138
|
+
if (new RegExp(`^string${NULLABLE}$`).test(text) || new RegExp(`^${STRING_LITERAL}(\\|${STRING_LITERAL})*${NULLABLE}$`).test(text))
|
|
139
|
+
return 'string';
|
|
140
|
+
if (new RegExp(`^number${NULLABLE}$`).test(text))
|
|
141
|
+
return 'number';
|
|
142
|
+
if (new RegExp(`^boolean${NULLABLE}$`).test(text))
|
|
143
|
+
return 'boolean';
|
|
144
|
+
if (new RegExp(`^Date${NULLABLE}$`).test(text))
|
|
145
|
+
return 'date';
|
|
146
|
+
if (!text) {
|
|
147
|
+
// No annotation: the initial value tells.
|
|
148
|
+
const initializer = 'initializer' in node ? node.initializer : undefined;
|
|
149
|
+
switch (initializer?.kind) {
|
|
150
|
+
case ts.SyntaxKind.StringLiteral:
|
|
151
|
+
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
|
|
152
|
+
return 'string';
|
|
153
|
+
case ts.SyntaxKind.NumericLiteral:
|
|
154
|
+
return 'number';
|
|
155
|
+
case ts.SyntaxKind.TrueKeyword:
|
|
156
|
+
case ts.SyntaxKind.FalseKeyword:
|
|
157
|
+
return 'boolean';
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
/** Reads the exported class of a model file: its public properties become the columns of the table. */
|
|
163
|
+
function parseModel(root, file, importerDirectory, warnings) {
|
|
164
|
+
const ts = typescriptOf(root);
|
|
165
|
+
const source = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
|
|
166
|
+
const classes = source.statements.filter((statement) => ts.isClassDeclaration(statement) && !!statement.name && (ts.getCombinedModifierFlags(statement) & ts.ModifierFlags.Export) !== 0);
|
|
167
|
+
const fileBase = (0, naming_1.kebab)(path.basename(file, '.ts').replace(/\.model$/i, ''));
|
|
168
|
+
if (!classes.length) {
|
|
169
|
+
const hasInterface = source.statements.some((statement) => ts.isInterfaceDeclaration(statement));
|
|
170
|
+
throw new Error(`${(0, exports.toPosix)(path.relative(root, file))}: ${hasInterface ? 'only classes are supported (not interfaces)' : 'no exported class found'}.`);
|
|
171
|
+
}
|
|
172
|
+
const node = classes.find((candidate) => candidate.name.text === (0, naming_1.pascal)(fileBase)) ?? classes[0];
|
|
173
|
+
const hidden = ts.ModifierFlags.Static | ts.ModifierFlags.Private | ts.ModifierFlags.Protected;
|
|
174
|
+
const fields = [];
|
|
175
|
+
const ignored = [];
|
|
176
|
+
const add = (member) => {
|
|
177
|
+
const name = member.name && (ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) ? member.name.text : '';
|
|
178
|
+
if (!name || ts.getCombinedModifierFlags(member) & hidden || fields.some((f) => f.name === name) || ignored.includes(name))
|
|
179
|
+
return;
|
|
180
|
+
const type = fieldType(ts, member, source);
|
|
181
|
+
if (type) {
|
|
182
|
+
fields.push({ name, type });
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
ignored.push(name);
|
|
186
|
+
const written = member.type?.getText(source) ?? 'unknown';
|
|
187
|
+
warnings.push(`Field "${name}" (${written}) is left out: only text, number, boolean and date fields become columns.`);
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
for (const member of node.members) {
|
|
191
|
+
if (ts.isPropertyDeclaration(member))
|
|
192
|
+
add(member);
|
|
193
|
+
if (ts.isConstructorDeclaration(member)) {
|
|
194
|
+
member.parameters.filter((parameter) => ts.getCombinedModifierFlags(parameter) & ts.ModifierFlags.Public).forEach(add);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (!fields.length)
|
|
198
|
+
throw new Error(`${(0, exports.toPosix)(path.relative(root, file))}: no property found in class ${node.name.text}.`);
|
|
199
|
+
if (node.heritageClauses?.length)
|
|
200
|
+
warnings.push(`${node.name.text} extends another class: inherited fields are not read.`);
|
|
201
|
+
const relative = (0, exports.toPosix)(path.relative(importerDirectory, file)).replace(/\.ts$/, '');
|
|
202
|
+
return {
|
|
203
|
+
className: node.name.text,
|
|
204
|
+
fileBase,
|
|
205
|
+
fields,
|
|
206
|
+
generate: false,
|
|
207
|
+
importPath: relative.startsWith('.') ? relative : `./${relative}`,
|
|
208
|
+
...(ignored.length ? { ignored } : {})
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
/** Adds flat keys (`A.B.c`) to a nested JSON object without touching what is already there. Returns the keys added. */
|
|
212
|
+
function addKeys(target, flat) {
|
|
213
|
+
const added = [];
|
|
214
|
+
for (const [key, text] of Object.entries(flat)) {
|
|
215
|
+
const parts = key.split('.');
|
|
216
|
+
let node = target;
|
|
217
|
+
let blocked = false;
|
|
218
|
+
for (const part of parts.slice(0, -1)) {
|
|
219
|
+
if (node[part] === undefined)
|
|
220
|
+
node[part] = {};
|
|
221
|
+
if (typeof node[part] !== 'object' || node[part] === null) {
|
|
222
|
+
blocked = true;
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
node = node[part];
|
|
226
|
+
}
|
|
227
|
+
const last = parts[parts.length - 1];
|
|
228
|
+
if (!blocked && node[last] === undefined) {
|
|
229
|
+
node[last] = text;
|
|
230
|
+
added.push(key);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return added;
|
|
234
|
+
}
|
|
235
|
+
/** Plans the update of the English translation file: new keys only, same formatting. */
|
|
236
|
+
function planTranslations(file, pageKeys, standardKeys) {
|
|
237
|
+
const all = { ...pageKeys, ...standardKeys };
|
|
238
|
+
if (!Object.keys(all).length)
|
|
239
|
+
return { added: [] };
|
|
240
|
+
const snippet = JSON.stringify(all, null, 2);
|
|
241
|
+
if (!file)
|
|
242
|
+
return { added: [], note: `No translation file found. Add these entries to your English file:\n${snippet}` };
|
|
243
|
+
const raw = fs.readFileSync(file, 'utf8');
|
|
244
|
+
const eol = raw.includes('\r\n') ? '\r\n' : '\n';
|
|
245
|
+
const serialize = (json) => JSON.stringify(json, null, 2).replace(/\n/g, eol) + (/\n$/.test(raw) ? eol : '');
|
|
246
|
+
const parsed = JSON.parse(raw);
|
|
247
|
+
if (serialize(parsed) !== raw) {
|
|
248
|
+
return { added: [], note: `${path.basename(file)} has an unusual format, so it was not rewritten. Add these entries by hand:\n${snippet}` };
|
|
249
|
+
}
|
|
250
|
+
const added = addKeys(parsed, all);
|
|
251
|
+
return { added, write: () => fs.writeFileSync(file, serialize(parsed), 'utf8') };
|
|
252
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.keyOf = exports.Ctx = exports.ImportBook = void 0;
|
|
4
|
+
const naming_1 = require("./naming");
|
|
5
|
+
/** The `import { ... } from '...'` lines of a generated file, grouped by module. */
|
|
6
|
+
class ImportBook {
|
|
7
|
+
modules = new Map();
|
|
8
|
+
add(from, ...names) {
|
|
9
|
+
const set = this.modules.get(from) ?? new Set();
|
|
10
|
+
names.forEach((name) => set.add(name));
|
|
11
|
+
this.modules.set(from, set);
|
|
12
|
+
}
|
|
13
|
+
/** Angular first, then other packages, then the files of the project. Names are sorted. */
|
|
14
|
+
render() {
|
|
15
|
+
const rank = (from) => (from.startsWith('@angular/') ? 0 : from.startsWith('.') ? 2 : 1);
|
|
16
|
+
return [...this.modules.keys()]
|
|
17
|
+
.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))
|
|
18
|
+
.map((from) => {
|
|
19
|
+
const names = [...this.modules.get(from)].sort((a, b) => a.localeCompare(b));
|
|
20
|
+
const line = `import { ${names.join(', ')} } from '${from}';`;
|
|
21
|
+
// A long list goes one name per line, so the file stays easy to read and to merge.
|
|
22
|
+
return line.length <= 120 ? line : `import {\n${names.map((name) => ` ${name}`).join(',\n')}\n} from '${from}';`;
|
|
23
|
+
})
|
|
24
|
+
.join('\n');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
exports.ImportBook = ImportBook;
|
|
28
|
+
/**
|
|
29
|
+
* What the blocks of a page build together: imports, members of the component, styles and translations.
|
|
30
|
+
* Every text goes through `tpl`, `ts` or `attr`, so that the same code serves the mode with translations
|
|
31
|
+
* (keys in the translation file) and the mode without (the texts themselves).
|
|
32
|
+
*/
|
|
33
|
+
class Ctx {
|
|
34
|
+
pageConstant;
|
|
35
|
+
i18n;
|
|
36
|
+
root;
|
|
37
|
+
lib;
|
|
38
|
+
translations = {};
|
|
39
|
+
imports = new ImportBook();
|
|
40
|
+
/** Names listed in `imports: [...]` of the component. */
|
|
41
|
+
componentImports = new Set();
|
|
42
|
+
styles = new Set();
|
|
43
|
+
warnings = [];
|
|
44
|
+
/** Members that come first in the class: they are used by the ones that follow. */
|
|
45
|
+
infrastructure = [];
|
|
46
|
+
members = [];
|
|
47
|
+
/** The template uses the `translate` pipe. */
|
|
48
|
+
usesPipe = false;
|
|
49
|
+
/** The code asks the `TranslateService` for texts: computed values that read the language. */
|
|
50
|
+
usesInstant = false;
|
|
51
|
+
/** The code needs the `TranslateService` (to read texts or to change the language). */
|
|
52
|
+
needsTranslateService = false;
|
|
53
|
+
counters = new Map();
|
|
54
|
+
constructor(pageConstant, i18n, root, lib) {
|
|
55
|
+
this.pageConstant = pageConstant;
|
|
56
|
+
this.i18n = i18n;
|
|
57
|
+
this.root = root;
|
|
58
|
+
this.lib = lib;
|
|
59
|
+
}
|
|
60
|
+
/** `nav`, then `nav2`, `nav3`... when a page has several blocks of a kind. */
|
|
61
|
+
varName(base) {
|
|
62
|
+
const n = (this.counters.get(base) ?? 0) + 1;
|
|
63
|
+
this.counters.set(base, n);
|
|
64
|
+
return n === 1 ? base : `${base}${n}`;
|
|
65
|
+
}
|
|
66
|
+
useLib(...names) {
|
|
67
|
+
this.imports.add(this.lib, ...names);
|
|
68
|
+
}
|
|
69
|
+
useComponent(name) {
|
|
70
|
+
this.componentImports.add(name);
|
|
71
|
+
this.useLib(name);
|
|
72
|
+
}
|
|
73
|
+
key(suffix) {
|
|
74
|
+
return `${this.root}.${this.pageConstant}.${suffix}`;
|
|
75
|
+
}
|
|
76
|
+
/** A text in a template expression (an object literal in a binding, or `{{ }}`). */
|
|
77
|
+
tpl(suffix, english) {
|
|
78
|
+
if (!this.i18n)
|
|
79
|
+
return (0, naming_1.quote)(english);
|
|
80
|
+
this.usesPipe = true;
|
|
81
|
+
this.translations[this.key(suffix)] = english;
|
|
82
|
+
return `('${this.key(suffix)}' | translate)`;
|
|
83
|
+
}
|
|
84
|
+
/** A text in TypeScript code that runs again when the language changes (inside a `computed`). */
|
|
85
|
+
ts(suffix, english) {
|
|
86
|
+
if (!this.i18n)
|
|
87
|
+
return (0, naming_1.quote)(english);
|
|
88
|
+
this.usesInstant = true;
|
|
89
|
+
this.needsTranslateService = true;
|
|
90
|
+
this.translations[this.key(suffix)] = english;
|
|
91
|
+
return `this.translate.instant('${this.key(suffix)}')`;
|
|
92
|
+
}
|
|
93
|
+
/** An HTML attribute: static text without translations, a binding with them. */
|
|
94
|
+
attr(name, suffix, english) {
|
|
95
|
+
if (!this.i18n)
|
|
96
|
+
return `${name}="${(0, naming_1.attributeEscape)(english)}"`;
|
|
97
|
+
this.usesPipe = true;
|
|
98
|
+
this.translations[this.key(suffix)] = english;
|
|
99
|
+
return `[${name}]="'${this.key(suffix)}' | translate"`;
|
|
100
|
+
}
|
|
101
|
+
/** A key-less text placed by the author (not translated, for example the name of a language). */
|
|
102
|
+
literal(english) {
|
|
103
|
+
return (0, naming_1.quote)(english);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
exports.Ctx = Ctx;
|
|
107
|
+
const keyOf = (name) => (0, naming_1.constant)(name);
|
|
108
|
+
exports.keyOf = keyOf;
|