Conectar: Configuración and Avanzado tabs, rows instead of JSON, field titles as keys, captions that fit their nodes

This commit is contained in:
Roberto Treviño
2026-11-29 15:24:24 -06:00
parent b48c025400
commit bb506c3926
8 changed files with 498 additions and 61 deletions
+17 -5
View File
@@ -102,12 +102,18 @@ test('conectar: open the hospital pipeline, preview a source, run it to success'
await page.goto('/conectar'); await page.goto('/conectar');
await page.getByText('cacu', { exact: true }).click(); await page.getByText('cacu', { exact: true }).click();
await expect(page.locator('vflow')).toBeVisible(); await expect(page.locator('vflow')).toBeVisible();
await page.getByText('Fuente de datos · Patients').click(); // a node's caption: its kind, then its name
await expect(page.locator('formly-form')).toBeVisible(); // drawn by hand: its raw form await page.locator('.node-caption', { hasText: 'Pacientes' }).click();
// drawn from a fixture, read back as a guided SQLite source: the dialog edits it
await expect(page.getByRole('button', { name: 'Editar conexión' })).toBeVisible();
await page.getByRole('button', { name: 'Vista previa' }).click(); await page.getByRole('button', { name: 'Vista previa' }).click();
await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible(); await expect(page.locator('.preview tr[mat-row]').first()).toBeVisible();
// A map node shows the site's codes in platform terms (its ConceptMap), editable as rows. // A map node shows the site's codes in platform terms (its ConceptMap), editable as rows.
await page.getByText('Traducir códigos · cytology', { exact: true }).click(); await page;
await page
.locator('.node-caption', { hasText: 'Traducir códigos' })
.filter({ has: page.locator('.name', { hasText: /^Citología$/ }) })
.click();
await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible(); await expect(page.getByRole('heading', { name: /^Códigos del sitio/ })).toBeVisible();
await expect await expect
.poll(() => .poll(() =>
@@ -146,7 +152,7 @@ test('gobernanza: a version with its reports, its curves, and promotion refused
await version.getByRole('button', { name: 'Ver gráficas' }).click(); await version.getByRole('button', { name: 'Ver gráficas' }).click();
await expect(page.locator('app-plot .plot svg').first()).toBeVisible(); await expect(page.locator('app-plot .plot svg').first()).toBeVisible();
await version.getByRole('button', { name: 'Promover' }).click(); await version.getByRole('button', { name: 'Promover' }).click();
await expect(page.getByText('No se promovió')).toContainText('clinical_validation'); await expect(page.getByText('No se promovió')).toContainText('Validación clínica');
expect(problems.filter((p) => !p.includes('409'))).toEqual([]); expect(problems.filter((p) => !p.includes('409'))).toEqual([]);
}); });
@@ -172,7 +178,7 @@ test('conectar: someone who knows nothing of databases connects the SQL Server w
await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible(); await expect(page.getByText(/(Las primeras \d+ filas|La primera fila):/)).toBeVisible();
await page.getByLabel('Nombre de esta fuente').fill('Resultados'); await page.getByLabel('Nombre de esta fuente').fill('Resultados');
await page.getByRole('button', { name: 'Guardar', exact: true }).last().click(); await page.getByRole('button', { name: 'Guardar', exact: true }).last().click();
await expect(page.getByText('Fuente de datos · Resultados')).toBeVisible(); await expect(page.locator('.node-caption', { hasText: 'Resultados' })).toBeVisible();
// A wrong password says so in words, not a stack trace. // A wrong password says so in words, not a stack trace.
await page.getByRole('button', { name: 'Editar conexión' }).click(); await page.getByRole('button', { name: 'Editar conexión' }).click();
await page.locator('[data-field="password"]').fill('not-it'); await page.locator('[data-field="password"]').fill('not-it');
@@ -323,6 +329,12 @@ for (const width of [1440, 820]) {
} }
await page.goto('/conectar'); await page.goto('/conectar');
await check('conectar'); await check('conectar');
// a pipeline open, a node chosen, in both of its panel's tabs
await page.locator('.pipelines [mat-list-item]').first().click();
await page.locator('.node-caption').first().dispatchEvent('click'); // the canvas may draw it off-screen
await check('conectar node');
await page.getByRole('tab', { name: 'Avanzado' }).click();
await check('conectar node, advanced');
await page.goto('/revision'); await page.goto('/revision');
const tabs = page.locator('.mdc-tab'); const tabs = page.locator('.mdc-tab');
for (let i = 0; i < (await tabs.count()); i++) { for (let i = 0; i < (await tabs.count()); i++) {
+62 -35
View File
@@ -73,10 +73,6 @@
</button> </button>
</div> </div>
<p class="help">{{ help[d.kind ?? 'source'] }}</p> <p class="help">{{ help[d.kind ?? 'source'] }}</p>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
</mat-form-field>
@if (d.inputs?.length) { @if (d.inputs?.length) {
<div class="inputs"> <div class="inputs">
Entradas: Entradas:
@@ -87,40 +83,71 @@
} }
</div> </div>
} @else if (d.kind !== 'source') { } @else if (d.kind !== 'source') {
<p class="muted">Una flecha desde otro nodo le da su entrada.</p> <p class="muted">Conecte una flecha desde otro nodo para darle entrada.</p>
} }
@if (guided(d); as g) { <mat-tab-group class="panel-tabs" animationDuration="0ms" mat-stretch-tabs="false">
<div class="source-summary"> <mat-tab label="Configuración">
<p> @if (d.kind === 'source') {
<mat-icon>check_circle</mat-icon> @if (guided(d)) {
{{ d.label || d.id }} <div class="source-summary">
<p>
<mat-icon>check_circle</mat-icon>
{{ d.label || d.id }}
</p>
<button mat-flat-button (click)="connectSource(d.id)">
<mat-icon>edit</mat-icon> Editar conexión
</button>
</div>
} @else {
<p class="muted">
Esta fuente no corresponde a ningún tipo del asistente. Edítela en «Avanzado» o
vuelva a conectarla con el asistente.
</p>
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con el asistente
</button>
}
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
[options]="formOptions"
(modelChange)="edited($event)"
/>
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
</mat-tab>
<mat-tab label="Avanzado">
<p class="hint">
Para personal técnico: el nodo completo como lo guarda la plataforma.
@if (guided(d)) {
Si cambia su fuente aquí, deja de editarse con el asistente.
}
</p> </p>
<button mat-flat-button (click)="connectSource(d.id)"> <mat-form-field appearance="outline" subscriptSizing="dynamic" class="full">
<mat-icon>edit</mat-icon> Editar conexión <mat-label>Id</mat-label>
<input matInput [value]="d.id" (change)="rename($any($event.target).value)" />
<mat-hint>Nombre interno: minúsculas, números y _.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="full raw">
<mat-label>Nodo (JSON)</mat-label>
<textarea
matInput
rows="16"
[value]="raw(d)"
(input)="rawDraft.set($any($event.target).value)"
></textarea>
</mat-form-field>
@if (rawError()) {
<p class="error" role="alert">{{ rawError() }}</p>
}
<button mat-stroked-button [disabled]="rawDraft() === undefined" (click)="applyRaw()">
Aplicar
</button> </button>
</div> </mat-tab>
<mat-slide-toggle [checked]="advanced()" (change)="advanced.set($event.checked)"> </mat-tab-group>
Avanzado (para personal técnico)
</mat-slide-toggle>
} @else if (d.kind === 'source') {
<button mat-stroked-button (click)="connectSource(d.id)">
<mat-icon>cable</mat-icon> Conectar con ayuda
</button>
}
@if (!guided(d) || advanced()) {
@if (guided(d)) {
<p class="muted">Si cambia algo aquí, la fuente deja de editarse con ayuda.</p>
}
<formly-form
[form]="form"
[fields]="fields()"
[model]="model"
(modelChange)="edited($event)"
/>
}
@if (conceptMap(d); as cm) {
<app-concept-map-editor [id]="cm" />
}
<button mat-stroked-button (click)="show()">Vista previa</button> <button mat-stroked-button (click)="show()">Vista previa</button>
@if (preview(); as rows) { @if (preview(); as rows) {
<div class="preview"> <div class="preview">
+52
View File
@@ -140,3 +140,55 @@ h2 {
color: var(--color-success, #2e7d32); color: var(--color-success, #2e7d32);
} }
} }
// The canvas's nodes: the kind small on top, the name below in two lines at most.
:host ::ng-deep default-node {
box-sizing: border-box;
overflow: hidden;
padding: 4px 10px;
display: flex;
align-items: center;
}
:host ::ng-deep .node-caption {
min-width: 0;
width: 100%;
line-height: 1.2;
}
:host ::ng-deep .node-caption .kind {
display: block;
font-size: 10px;
color: var(--color-text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
:host ::ng-deep .node-caption .name {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
font-size: 12px;
font-weight: 500;
overflow-wrap: anywhere;
}
.panel-tabs {
margin-top: var(--space-2);
}
.panel-tabs .hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: var(--space-3) 0;
}
.raw textarea {
font-family: monospace;
font-size: 12px;
}
.error {
color: var(--mat-sys-error);
font-size: 13px;
}
// Fields in the panel keep their hints clear of the next field's label.
:host ::ng-deep .panel mat-form-field {
margin-bottom: var(--space-3);
}
+86 -15
View File
@@ -1,5 +1,13 @@
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { Component, computed, inject, resource, signal, WritableSignal } from '@angular/core'; import {
Component,
computed,
effect,
inject,
resource,
signal,
WritableSignal,
} from '@angular/core';
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms'; import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
@@ -7,7 +15,7 @@ import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatListModule } from '@angular/material/list'; import { MatListModule } from '@angular/material/list';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { MatSlideToggleModule } from '@angular/material/slide-toggle'; import { MatTabsModule } from '@angular/material/tabs';
import { MatTableModule } from '@angular/material/table'; import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core'; import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
@@ -57,21 +65,21 @@ export const KINDS: Record<Kind, string> = {
read: 'Leer documentos', read: 'Leer documentos',
route: 'Separar por tipo', route: 'Separar por tipo',
map: 'Traducir códigos', map: 'Traducir códigos',
extract: 'Sacar datos', extract: 'Extraer datos',
fhir: 'Leer FHIR', fhir: 'Leer FHIR',
join: 'Juntar', join: 'Unir',
link: 'Identificar a la persona', link: 'Identificar a la persona',
target: 'Guardar en la plataforma', target: 'Guardar en la plataforma',
}; };
export const HELP: Record<Kind, string> = { export const HELP: Record<Kind, string> = {
source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.', source: 'De dónde vienen los datos: una base de datos, una carpeta, la nube o una API.',
read: 'Saca el texto de cada documento (PDF, Word, escaneos con OCR).', read: 'Extrae el texto de cada documento (PDF, Word, escaneos con OCR).',
route: route:
'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.', 'Deja pasar solo los documentos o filas que cumplen una condición; por ejemplo, las citologías.',
map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.', map: 'Cambia los códigos del hospital por los de la plataforma, con una tabla de equivalencias.',
extract: 'Toma de cada documento los datos de un estudio: fechas, resultados, nombres.', extract: 'Extrae de cada documento los datos de un estudio: fechas, resultados, nombres.',
fhir: 'Lee paquetes FHIR que un sistema envió y saca de ellos los estudios.', fhir: 'Lee los paquetes FHIR que envía un sistema y extrae sus estudios.',
join: 'Junta dos entradas que hablan de lo mismo; por ejemplo, un resultado con su orden.', join: 'Une dos entradas que se refieren al mismo registro; por ejemplo, un resultado con su orden.',
link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.', link: 'Reconoce a qué paciente pertenece cada registro, aunque su nombre venga escrito distinto.',
target: 'Guarda los estudios ya revisados en la plataforma.', target: 'Guarda los estudios ya revisados en la plataforma.',
}; };
@@ -90,7 +98,7 @@ const ID = /^[a-z][a-z0-9_]*$/;
MatIconModule, MatIconModule,
MatInputModule, MatInputModule,
MatListModule, MatListModule,
MatSlideToggleModule, MatTabsModule,
MatTableModule, MatTableModule,
MatTooltipModule, MatTooltipModule,
Vflow, Vflow,
@@ -107,8 +115,9 @@ export class Conectar {
private readonly dialog = inject(MatDialog); private readonly dialog = inject(MatDialog);
protected readonly kinds = Object.entries(KINDS) as [Kind, string][]; protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
protected readonly help = HELP; protected readonly help = HELP;
/** The raw form of a source drawn with the dialog ("Avanzado"). */ /** "Avanzado": the selected node as JSON, as edited and not applied yet. */
protected readonly advanced = signal(false); protected readonly rawDraft = signal<string | undefined>(undefined);
protected readonly rawError = signal('');
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) }); protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
private readonly schema = resource({ loader: () => this.api.invoke(schema) }); private readonly schema = resource({ loader: () => this.api.invoke(schema) });
@@ -132,6 +141,20 @@ export class Conectar {
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status); return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
}); });
/** What the node forms share: each entity's fields by their titles (the catalog's). */
protected readonly formOptions = { formState: { fields: {} as Record<string, unknown> } };
private readonly titles = effect(() => {
const entities = (this.schema.value()?.['entities'] ?? {}) as Record<
string,
{ properties?: Record<string, { title?: string }> }
>;
this.formOptions.formState.fields = Object.fromEntries(
Object.entries(entities).map(([e, s]) => [
e,
Object.fromEntries(Object.entries(s.properties ?? {}).map(([f, p]) => [f, p.title ?? f])),
]),
);
});
protected form = new UntypedFormGroup({}); protected form = new UntypedFormGroup({});
protected model: Record<string, unknown> = {}; protected model: Record<string, unknown> = {};
/** The selected node's form, generated from its kind's JSON Schema. */ /** The selected node's form, generated from its kind's JSON Schema. */
@@ -264,7 +287,8 @@ export class Conectar {
); );
this.form = new UntypedFormGroup({}); this.form = new UntypedFormGroup({});
this.preview.set(undefined); this.preview.set(undefined);
this.advanced.set(false); this.rawDraft.set(undefined);
this.rawError.set('');
} }
/** A source the dialog drew (its answers make its dlt fields). */ /** A source the dialog drew (its answers make its dlt fields). */
@@ -279,13 +303,46 @@ export class Conectar {
const values = Object.fromEntries( const values = Object.fromEntries(
Object.entries(model).filter(([, v]) => v !== undefined && v !== null), Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
); );
if (this.advanced()) delete values['guided']; // drawn by hand from here on
this.update( this.update(
id, id,
(d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc, (d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc,
); );
} }
/** The node as the platform keeps it (its place on the canvas aside). */
protected raw(d: Doc): string {
const { position, ...rest } = d as Doc & { position?: unknown };
return JSON.stringify(rest, null, 2);
}
/** "Aplicar": the edited JSON becomes the node. Its kind stays; its id changes with the
* Id field (so the arrows follow). A source whose dlt fields change is drawn by hand from
* then on (unless a catalog type makes it exactly: the platform reads it back). */
protected applyRaw(): void {
const d = this.doc();
const text = this.rawDraft();
if (!d || text === undefined) return;
let parsed: Record<string, unknown>;
try {
parsed = JSON.parse(text);
} catch {
this.rawError.set('El texto no es JSON válido.');
return;
}
if (parsed['kind'] !== d.kind) {
this.rawError.set(`El tipo del nodo es «${d.kind}» y no cambia aquí.`);
return;
}
if (d.kind === 'source') {
const dlt = ['source', 'args', 'resource', 'then'] as const;
const before = d as unknown as Record<string, unknown>;
if (dlt.some((k) => JSON.stringify(parsed[k]) !== JSON.stringify(before[k])))
delete parsed['guided'];
}
this.update(d.id, () => ({ ...parsed, id: d.id, kind: d.kind }) as unknown as Doc);
this.select(d.id);
}
protected rename(to: string): void { protected rename(to: string): void {
const from = this.selected(); const from = this.selected();
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return; if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
@@ -363,7 +420,7 @@ export class Conectar {
? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source }) ? await this.api.invoke(sourcePreview, { limit: 20, body: doc as Source })
: await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 }); : await this.api.invoke(nodeRows, { pipeline_id: id, node_id: doc.id, limit: 50 });
this.preview.set(rows); this.preview.set(rows);
this.message.set(rows.length ? '' : 'Sin filas todavía: ejecute la canalización.'); this.message.set(rows.length ? '' : 'Sin filas: ejecute la canalización.');
} catch (e) { } catch (e) {
this.message.set(problem(e)); this.message.set(problem(e));
} }
@@ -389,7 +446,14 @@ export class Conectar {
} }
function text(d: Doc): string { function text(d: Doc): string {
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`; // ngx-vflow draws a node's text as HTML: the kind above, the name below (two lines at
// most; the whole of it on hover). The name is the operator's text, so it is escaped.
const kind = KINDS[d.kind ?? 'source'];
const name = escape(d.label || d.id);
return (
`<div class="node-caption" title="${kind} · ${name}">` +
`<span class="kind">${kind}</span><span class="name">${name}</span></div>`
);
} }
/** Each node's distance from the sources: its column when it has no saved position. */ /** Each node's distance from the sources: its column when it has no saved position. */
@@ -416,3 +480,10 @@ function problem(e: unknown): string {
} }
return String(e); return String(e);
} }
function escape(text: string): string {
return text.replace(
/[&<>"']/g,
(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!,
);
}
+15 -3
View File
@@ -16,6 +16,12 @@ const PIPELINE = {
when: { type: 'array', items: { $ref: '#/$defs/Condition' } }, when: { type: 'array', items: { $ref: '#/$defs/Condition' } },
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' }, resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' }, values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' },
on: {
type: 'array',
items: { type: 'array', prefixItems: [{ type: 'string' }, { type: 'string' }] },
},
extra: { type: 'object', title: 'Extra' },
source: { type: 'string', advanced: true },
}, },
}, },
}, },
@@ -25,7 +31,7 @@ describe('node forms from the pipeline schema', () => {
const schema = nodeSchema(PIPELINE, 'route') as any; const schema = nodeSchema(PIPELINE, 'route') as any;
it('leaves out what the canvas edits', () => { it('leaves out what the canvas edits', () => {
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values']); expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values', 'on']);
expect(schema.required).toEqual(['when']); expect(schema.required).toEqual(['when']);
}); });
@@ -34,7 +40,13 @@ describe('node forms from the pipeline schema', () => {
expect(schema.properties.resource.type).toBe('string'); expect(schema.properties.resource.type).toBe('string');
}); });
it('edits maps as JSON', () => { it('edits maps of texts and pairs as rows', () => {
expect(schema.properties.values.widget.formlyConfig.type).toBe('json'); expect(schema.properties.values.widget.formlyConfig.type).toBe('map');
expect(schema.properties.on.widget.formlyConfig.type).toBe('pairs');
});
it('leaves JSON-only values and advanced fields to the "Avanzado" tab', () => {
expect(schema.properties.extra).toBeUndefined();
expect(schema.properties.source).toBeUndefined();
}); });
}); });
+236 -2
View File
@@ -3,6 +3,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { ReactiveFormsModule } from '@angular/forms'; import { ReactiveFormsModule } from '@angular/forms';
import { import {
ConfigOption, ConfigOption,
@@ -27,11 +28,29 @@ export function nodeSchema(pipeline: Schema, kind: string): Schema {
)!; )!;
const node = structuredClone(defs[name]); const node = structuredClone(defs[name]);
for (const field of CANVAS_FIELDS) delete node.properties?.[field]; for (const field of CANVAS_FIELDS) delete node.properties?.[field];
node.required = (node.required ?? []).filter((f) => !CANVAS_FIELDS.includes(f)); // The panel says what the kind does (in Spanish); the class's own docstring is for code.
delete node.title;
delete node.description;
// What a guided dialog fills, or what only JSON can say, is for the "Avanzado" tab.
for (const [field, value] of Object.entries(node.properties ?? {})) {
const simple = simplify(value as Schema, defs) as Schema & { widget?: unknown };
if ((value as { advanced?: boolean }).advanced || isJson(simple))
delete node.properties![field];
}
node.required = (node.required ?? []).filter(
(f) => !CANVAS_FIELDS.includes(f) && f in (node.properties ?? {}),
);
delete node.additionalProperties; delete node.additionalProperties;
return simplify(node, defs); return simplify(node, defs);
} }
function isJson(schema: Schema): boolean {
return (
(schema as { widget?: { formlyConfig?: { type?: string } } }).widget?.formlyConfig?.type ===
'json'
);
}
function simplify(schema: Schema, defs: Record<string, Schema>): Schema { function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
if (schema.$ref) { if (schema.$ref) {
const { $ref, ...rest } = schema; const { $ref, ...rest } = schema;
@@ -45,6 +64,34 @@ function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
return simplify({ ...kept[0], ...rest }, defs); return simplify({ ...kept[0], ...rest }, defs);
} }
} }
const values = schema.additionalProperties as Schema | boolean | undefined;
if (
schema.type === 'object' &&
!schema.properties &&
typeof values === 'object' &&
values.type === 'string'
) {
const byField = (schema as { keys?: string }).keys === 'field';
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'map', props: { fieldKeys: byField } } },
} as Schema;
}
const pair = schema.items as Schema | undefined;
if (
schema.type === 'array' &&
(pair?.prefixItems as Schema[] | undefined)?.length === 2 &&
(pair!.prefixItems as Schema[]).every((p) => p.type === 'string')
) {
return {
title: schema.title,
description: schema.description,
default: schema.default,
widget: { formlyConfig: { type: 'pairs' } },
} as Schema;
}
const isMap = schema.type === 'object' && !schema.properties; const isMap = schema.type === 'object' && !schema.properties;
const isTuple = const isTuple =
schema.type === 'array' && schema.type === 'array' &&
@@ -117,7 +164,7 @@ export class ArrayType extends FieldArrayType {}
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule], imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
template: ` template: `
<mat-form-field appearance="outline" class="json"> <mat-form-field appearance="outline" class="json">
<mat-label>{{ props.label }} (JSON)</mat-label> <mat-label>{{ props.label }}</mat-label>
<textarea <textarea
matInput matInput
rows="4" rows="4"
@@ -152,11 +199,198 @@ export class JsonType extends FieldType<FormlyFieldConfig> {
} }
} }
/** A map of names to texts (fields to columns, fields to patterns, date formats): a row
* per entry, its name and its text, to add or remove. */
@Component({
selector: 'app-formly-map',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="key">
<mat-label>{{ props['fieldKeys'] ? 'Dato' : 'Nombre' }}</mat-label>
@if (props['fieldKeys']) {
<mat-select [value]="row[0]" (selectionChange)="edit(i, $event.value, row[1])">
@for (o of keyOptions(row[0]); track o[0]) {
<mat-option [value]="o[0]">{{ o[1] }}</mat-option>
}
</mat-select>
} @else {
<input
matInput
[value]="row[0]"
(change)="edit(i, $any($event.target).value, row[1])"
/>
}
</mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="value">
<mat-label>Valor</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, row[0], $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: grid;
grid-template-columns: 1fr auto;
column-gap: 4px;
row-gap: 6px;
padding: 8px 0;
border-bottom: 1px solid var(--color-border);
}
.key,
.value {
min-width: 0;
grid-column: 1;
}
.row button {
grid-column: 2;
grid-row: 1 / span 2;
align-self: center;
}
`,
})
export class MapType extends FieldType<FormlyFieldConfig> {
/** The platform fields a key can be, by title: the node's study's, or every study's when
* it names none (formState.fields: entity -> field -> title). */
protected keyOptions(current: string): [string, string][] {
const all = (this.options?.formState?.fields ?? {}) as Record<string, Record<string, string>>;
const entity = (this.model as Record<string, unknown> | undefined)?.['entity'] as
string | undefined;
const titles: Record<string, string> = entity
? (all[entity] ?? {})
: Object.assign({}, ...Object.values(all));
const options = Object.entries(titles);
if (current && !(current in titles)) options.unshift([current, current]);
return options;
}
protected rows(): [string, string][] {
return Object.entries((this.formControl.value ?? {}) as Record<string, string>);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(Object.fromEntries(rows.filter(([k]) => k !== '')));
this.formControl.markAsDirty();
}
protected edit(i: number, key: string, value: string): void {
const rows = this.rows();
rows[i] = [key.trim(), value];
this.save(rows);
}
protected add(): void {
// a new row needs a key before it is kept: the first field not used yet, or a new name
const rows = this.rows();
const used = new Set(rows.map(([k]) => k));
const free = this.props['fieldKeys']
? this.keyOptions('').find(([k]) => !used.has(k))?.[0]
: undefined;
let n = rows.length + 1;
while (used.has(`campo_${n}`)) n++;
this.save([...rows, [free ?? `campo_${n}`, '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
/** Pairs of names (a join's columns, the first input's = the second's): a row per pair. */
@Component({
selector: 'app-formly-pairs',
imports: [MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
template: `
<div class="legend">{{ props.label }}</div>
@if (props.description) {
<p class="hint">{{ props.description }}</p>
}
@for (row of rows(); track $index; let i = $index) {
<div class="row">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Primera entrada</mat-label>
<input matInput [value]="row[0]" (change)="edit(i, 0, $any($event.target).value)" />
</mat-form-field>
<span>=</span>
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="half">
<mat-label>Segunda entrada</mat-label>
<input matInput [value]="row[1]" (change)="edit(i, 1, $any($event.target).value)" />
</mat-form-field>
<button mat-icon-button type="button" (click)="remove(i)" aria-label="Quitar">
<mat-icon>close</mat-icon>
</button>
</div>
}
<button mat-stroked-button type="button" (click)="add()">
<mat-icon>add</mat-icon> Agregar
</button>
`,
styles: `
.legend {
font-weight: 500;
margin: 12px 0 4px;
}
.hint {
color: var(--color-text-secondary);
font-size: 12px;
margin: 0 0 8px;
}
.row {
display: flex;
gap: 6px;
align-items: center;
margin-bottom: 6px;
}
.half {
flex: 1;
min-width: 0;
}
`,
})
export class PairsType extends FieldType<FormlyFieldConfig> {
protected rows(): [string, string][] {
return ((this.formControl.value ?? []) as [string, string][]).map((r) => [r[0], r[1]]);
}
private save(rows: [string, string][]): void {
this.formControl.setValue(rows);
this.formControl.markAsDirty();
}
protected edit(i: number, side: 0 | 1, value: string): void {
const rows = this.rows();
rows[i][side] = value.trim();
this.save(rows);
}
protected add(): void {
this.save([...this.rows(), ['', '']]);
}
protected remove(i: number): void {
this.save(this.rows().filter((_, j) => j !== i));
}
}
export const FORMLY_TYPES: ConfigOption = { export const FORMLY_TYPES: ConfigOption = {
types: [ types: [
{ name: 'object', component: ObjectType }, { name: 'object', component: ObjectType },
{ name: 'array', component: ArrayType }, { name: 'array', component: ArrayType },
{ name: 'json', component: JsonType }, { name: 'json', component: JsonType },
{ name: 'map', component: MapType },
{ name: 'pairs', component: PairsType },
{ name: 'enum', extends: 'select' }, { name: 'enum', extends: 'select' },
{ name: 'string', extends: 'input' }, { name: 'string', extends: 'input' },
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } }, { name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
+20 -1
View File
@@ -128,6 +128,25 @@
} }
</mat-form-field> </mat-form-field>
} }
@case ('columns') {
<mat-form-field appearance="outline" class="full">
<mat-label>{{ f.label }}</mat-label>
<mat-select
multiple
[ngModel]="listed(name)"
(ngModelChange)="set(name, $event.length ? $event : null)"
[attr.data-field]="name"
placeholder="Todas"
>
@for (c of columnOptions(name); track c) {
<mat-option [value]="c">{{ c }}</mat-option>
}
</mat-select>
<mat-hint>{{
columnOptions(name).length ? f.help : 'Pulse «Probar conexión» para ver las columnas.'
}}</mat-hint>
</mat-form-field>
}
@case ('folder') { @case ('folder') {
<div class="picker"> <div class="picker">
<mat-form-field appearance="outline" class="grow"> <mat-form-field appearance="outline" class="grow">
@@ -319,7 +338,7 @@
</p> </p>
@if (t.detail) { @if (t.detail) {
<details> <details>
<summary>Lo que respondió el sistema</summary> <summary>Respuesta de la fuente</summary>
<pre>{{ t.detail }}</pre> <pre>{{ t.detail }}</pre>
</details> </details>
} }
+10
View File
@@ -204,6 +204,16 @@ export class SourceDialog {
} }
/** The tables a database listed, for its table field. */ /** The tables a database listed, for its table field. */
/** A list answer (the columns picked), as a list. */
protected listed(name: string): string[] {
const v = this.value(name);
return Array.isArray(v) ? (v as string[]) : [];
}
/** The columns to pick from: the first rows', and those already picked. */
protected columnOptions(name: string): string[] {
return [...new Set([...this.columns(), ...this.listed(name)])];
}
protected tables(): string[] { protected tables(): string[] {
return this.tableList(); return this.tableList();
} }