mams_frontend/scripts/gen-layouts.mjs

116 lines
5.1 KiB
JavaScript

// Generates src/features/forms/generated-layouts.json from the legacy create pages.
//
// node scripts/gen-layouts.mjs [--only=ENTITY,ENTITY] [path-to-legacy-frontend/entities]
//
// For every <entity>/<entity>create/<entity>create.html it records, in the order the legacy page SHOWS
// them, the tab panes, fieldset legends and `div_<FIELD>` containers:
// - HTML comments are dropped first (the pages keep many retired fields commented out);
// - the pages lay fields out in 3 independent columns (`col-md-4`), so the columns are interleaved
// row by row, which is how they read on screen;
// - a number + area-code pair sharing one `d-flex` row stays adjacent.
// At runtime the list is intersected with the backend's own field metadata (types, required flags,
// options), so only real fields are shown.
//
// `--only` regenerates just the named entities and keeps every other entry of the existing file as is.
import { readdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const args = process.argv.slice(2);
const only = args.find((a) => a.startsWith('--only='))?.slice(7).split(',').map((s) => s.trim().toUpperCase());
const root = args.find((a) => !a.startsWith('--')) ?? 'C:/inetpub/wwwroot/OmanTCS_STG/frontend/entities';
const out = join(here, '../src/features/forms/generated-layouts.json');
// div ids that wrap something other than a form field
const NOT_FIELDS = /^(EXRTA_FIELD|EXTRA_FIELD)$|_ACTIONS?$|^MAIN_|^SECOND_|^THIRD_/;
function parse(rawHtml, entity) {
const html = rawHtml.replace(/<!--[\s\S]*?-->/g, '');
const sections = [];
let pane = '';
let legend = '';
const current = () => {
const key = legend || pane || `${entity}_INFO`;
let s = sections.find((x) => x.key === key);
if (!s) sections.push((s = { key, title: key, columns: [] }));
return s;
};
// every opening/closing <div> and <legend>, in document order; the stack tells which column / flex row a field sits in
const tag = /<(\/?)(div|legend)\b([^>]*)>/gi;
const stack = [];
let seq = 0;
for (let m; (m = tag.exec(html)); ) {
const closing = m[1] === '/';
const name = m[2].toLowerCase();
const attrs = m[3];
if (name === 'legend') {
if (!closing) {
const id = /\bid\s*=\s*"([^"]+)"/i.exec(attrs)?.[1];
if (id) legend = id;
}
continue;
}
if (closing) {
stack.pop();
continue;
}
const id = /\bid\s*=\s*"([^"]+)"/i.exec(attrs)?.[1];
const cls = /\bclass\s*=\s*"([^"]*)"/i.exec(attrs)?.[1] ?? '';
const selfClosing = /\/\s*$/.test(attrs);
const entry = { kind: 'other', seq: seq++ };
if (!id && /\bcol-(md|lg|xl)-\d+\b/.test(cls)) entry.kind = 'col';
else if (!id && /\bd-flex\b/.test(cls)) entry.kind = 'flex';
if (!selfClosing) stack.push(entry);
if (id && /\btab-pane\b/.test(cls)) {
pane = id;
legend = '';
} else if (id?.startsWith('div_')) {
const field = id.slice(4);
if (NOT_FIELDS.test(field) || !/^[A-Z][A-Z0-9_]*$/.test(field)) continue;
const s = current();
if (s.columns.some((c) => c.cells.some((cell) => cell.fields.includes(field)))) continue;
const col = [...stack].reverse().find((e) => e.kind === 'col');
const flex = [...stack].reverse().find((e) => e.kind === 'flex');
const colKey = col ? col.seq : `loose${entry.seq}`;
let column = s.columns.find((c) => c.key === colKey);
if (!column) s.columns.push((column = { key: colKey, cells: [] }));
const cellKey = flex ? flex.seq : `single${entry.seq}`;
let cell = column.cells.find((c) => c.key === cellKey);
if (!cell) column.cells.push((cell = { key: cellKey, fields: [] }));
cell.fields.push(field);
}
}
// columns -> reading order: first cell of every column, then the second cell of every column, ...
return sections
.map((s) => {
const rows = Math.max(0, ...s.columns.map((c) => c.cells.length));
const fields = [];
for (let r = 0; r < rows; r++) for (const c of s.columns) fields.push(...(c.cells[r]?.fields ?? []));
return {
title: /^ATTACHMENT/.test(s.key) ? 'ATTACHMENTS' : /^(INFO|INFORMATIONS?|MAIN)$/i.test(s.key) ? `${entity}_INFO` : s.key,
fields,
};
})
.filter((s) => s.fields.length);
}
const result = only && existsSync(out) ? JSON.parse(readFileSync(out, 'utf8')) : {};
for (const dir of readdirSync(root, { withFileTypes: true })) {
if (!dir.isDirectory()) continue;
const entity = dir.name.toUpperCase();
if (only && !only.includes(entity)) continue;
const page = join(root, dir.name, `${dir.name}create`, `${dir.name}create.html`);
if (!existsSync(page)) continue;
const sections = parse(readFileSync(page, 'utf8'), entity);
if (sections.length) result[entity] = sections;
}
writeFileSync(out, JSON.stringify(result, null, 1));
const n = Object.keys(result).length;
const f = Object.values(result).reduce((a, s) => a + s.reduce((b, x) => b + x.fields.length, 0), 0);
console.log(`wrote ${n} entities, ${f} fields -> ${out}`);