One shell with the current look: indicators, follow-up list and patient view from FHIR; /conectar canvas; /revision; Playwright page tests
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
<div class="workspace">
|
||||
<aside class="pipelines">
|
||||
<h2>Canalizaciones</h2>
|
||||
<mat-nav-list dense>
|
||||
@for (p of list.value() ?? []; track p['pipeline_id']) {
|
||||
<a
|
||||
mat-list-item
|
||||
[activated]="p['pipeline_id'] === pipelineId()"
|
||||
(click)="open(p['pipeline_id'])"
|
||||
>
|
||||
<span matListItemTitle>{{ p['pipeline_id'] }}</span>
|
||||
<span matListItemLine>v{{ p['version'] }}</span>
|
||||
</a>
|
||||
}
|
||||
</mat-nav-list>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="new">
|
||||
<mat-label>Nueva canalización</mat-label>
|
||||
<input matInput #name (keydown.enter)="create(name.value)" placeholder="hospital_norte" />
|
||||
</mat-form-field>
|
||||
</aside>
|
||||
|
||||
<section class="canvas-area">
|
||||
<div class="toolbar">
|
||||
<span class="title"
|
||||
>{{ pipelineId() ?? 'Elija o cree una canalización' }}
|
||||
@if (version()) {
|
||||
<span class="muted"> · v{{ version() }}</span>
|
||||
}
|
||||
</span>
|
||||
@if (pipelineId()) {
|
||||
@for (k of kinds; track k[0]) {
|
||||
<button mat-stroked-button (click)="add(k[0])"><mat-icon>add</mat-icon>{{ k[1] }}</button>
|
||||
}
|
||||
<span class="spacer"></span>
|
||||
<button mat-stroked-button (click)="save()">Guardar</button>
|
||||
<button mat-flat-button (click)="start()" [disabled]="running()">Ejecutar</button>
|
||||
}
|
||||
</div>
|
||||
@if (message()) {
|
||||
<p class="message" role="status">{{ message() }}</p>
|
||||
}
|
||||
@if (run(); as r) {
|
||||
<p class="run" role="status">
|
||||
Ejecución <code>{{ r.id.slice(0, 8) }}</code>: <strong>{{ r.status }}</strong> ·
|
||||
<a [href]="dagster()" target="_blank" rel="noopener">ver en Dagster</a>
|
||||
</p>
|
||||
}
|
||||
<div class="canvas">
|
||||
@if (pipelineId()) {
|
||||
<vflow
|
||||
[nodes]="nodes()"
|
||||
[edges]="edges()"
|
||||
[connection]="{ curve: 'smooth-step', marker: { type: 'arrow-closed' } }"
|
||||
(connect)="connect($event)"
|
||||
(nodesChanges)="changed($event)"
|
||||
view="auto"
|
||||
background="#f7f8f6"
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@if (doc(); as d) {
|
||||
<aside class="panel">
|
||||
<div class="panel-head">
|
||||
<h2>
|
||||
{{ kindLabel(d.kind) }} · <span class="muted">{{ d.id }}</span>
|
||||
</h2>
|
||||
<button mat-icon-button (click)="remove(d.id)" aria-label="Quitar nodo">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
<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) {
|
||||
<div class="inputs">
|
||||
Entradas:
|
||||
@for (i of d.inputs; track i) {
|
||||
<button mat-stroked-button class="chip" (click)="disconnect(d.id, i)">
|
||||
{{ i }} <mat-icon>close</mat-icon>
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
} @else if (d.kind !== 'source') {
|
||||
<p class="muted">Una flecha desde otro nodo le da su entrada.</p>
|
||||
}
|
||||
<formly-form
|
||||
[form]="form"
|
||||
[fields]="fields()"
|
||||
[model]="model"
|
||||
(modelChange)="edited($event)"
|
||||
/>
|
||||
<button mat-stroked-button (click)="show()">Vista previa</button>
|
||||
@if (preview(); as rows) {
|
||||
<div class="preview">
|
||||
<table mat-table [dataSource]="rows">
|
||||
@for (c of columns(); track c) {
|
||||
<ng-container [matColumnDef]="c">
|
||||
<th mat-header-cell *matHeaderCellDef>{{ c }}</th>
|
||||
<td mat-cell *matCellDef="let row">{{ cell(row[c]) }}</td>
|
||||
</ng-container>
|
||||
}
|
||||
<tr mat-header-row *matHeaderRowDef="columns()"></tr>
|
||||
<tr mat-row *matRowDef="let row; columns: columns()"></tr>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</aside>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,111 @@
|
||||
:host {
|
||||
display: block;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.workspace {
|
||||
display: grid;
|
||||
grid-template-columns: 220px 1fr auto;
|
||||
height: calc(100dvh - var(--header-height) - 86px);
|
||||
min-height: 560px;
|
||||
}
|
||||
|
||||
.pipelines,
|
||||
.panel {
|
||||
background: var(--color-surface);
|
||||
border-right: 1px solid var(--color-border);
|
||||
overflow-y: auto;
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.panel {
|
||||
border-left: 1px solid var(--color-border);
|
||||
border-right: 0;
|
||||
width: 380px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
margin: 0 0 var(--space-2);
|
||||
}
|
||||
|
||||
.new,
|
||||
.full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.canvas-area {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
align-items: center;
|
||||
background: var(--color-surface);
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-weight: 500;
|
||||
margin-right: var(--space-3);
|
||||
}
|
||||
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.message,
|
||||
.run {
|
||||
margin: var(--space-2) var(--space-3) 0;
|
||||
}
|
||||
|
||||
.canvas {
|
||||
flex: 1;
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.inputs {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
margin: var(--space-2) 0;
|
||||
}
|
||||
|
||||
.preview {
|
||||
margin-top: var(--space-3);
|
||||
max-height: 360px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.preview td,
|
||||
.preview th {
|
||||
font-size: 12px;
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.workspace {
|
||||
grid-template-columns: 1fr;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.panel {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Component, computed, inject, resource, signal, WritableSignal } from '@angular/core';
|
||||
import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatListModule } from '@angular/material/list';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { FormlyFieldConfig, FormlyForm, provideFormlyCore } from '@ngx-formly/core';
|
||||
import { FormlyJsonschema } from '@ngx-formly/core/json-schema';
|
||||
import { withFormlyMaterial } from '@ngx-formly/material';
|
||||
import { Connection, NodeChange, Vflow } from 'ngx-vflow';
|
||||
import { Api } from '../api/api';
|
||||
import { nodeRows } from '../api/fn/ingest/node-rows';
|
||||
import { pipeline as getPipeline } from '../api/fn/ingest/pipeline';
|
||||
import { pipelines } from '../api/fn/ingest/pipelines';
|
||||
import { savePipeline } from '../api/fn/ingest/save-pipeline';
|
||||
import { schema } from '../api/fn/ingest/schema';
|
||||
import { sourcePreview } from '../api/fn/ingest/source-preview';
|
||||
import { startRun } from '../api/fn/ingest/start-run';
|
||||
import { runStatus } from '../api/fn/runs/run-status';
|
||||
import type { Pipeline } from '../api/models/pipeline';
|
||||
import type { Source } from '../api/models/source';
|
||||
import { FORMLY_TYPES, nodeSchema } from './schema-form';
|
||||
|
||||
type Doc = Pipeline['nodes'][number];
|
||||
type Kind = NonNullable<Doc['kind']>;
|
||||
interface CanvasNode {
|
||||
id: string;
|
||||
type: 'default';
|
||||
point: WritableSignal<{ x: number; y: number }>;
|
||||
text: WritableSignal<string>;
|
||||
width: WritableSignal<number>;
|
||||
height: WritableSignal<number>;
|
||||
}
|
||||
|
||||
function canvasNode(id: string, point: { x: number; y: number }, label: string): CanvasNode {
|
||||
return {
|
||||
id,
|
||||
type: 'default',
|
||||
point: signal(point),
|
||||
text: signal(label),
|
||||
width: signal(190),
|
||||
height: signal(56),
|
||||
};
|
||||
}
|
||||
|
||||
export const KINDS: Record<Kind, string> = {
|
||||
source: 'Fuente',
|
||||
read: 'Leer',
|
||||
route: 'Filtrar',
|
||||
map: 'Mapear',
|
||||
extract: 'Extraer',
|
||||
join: 'Unir',
|
||||
link: 'Vincular',
|
||||
target: 'Destino',
|
||||
};
|
||||
const ID = /^[a-z][a-z0-9_]*$/;
|
||||
|
||||
/** /conectar: an operator draws a site's pipeline on a canvas (nodes and the edges between
|
||||
* them), fills each node's form, previews what it gives, saves a version and runs it. */
|
||||
@Component({
|
||||
selector: 'app-conectar',
|
||||
imports: [
|
||||
FormsModule,
|
||||
ReactiveFormsModule,
|
||||
FormlyForm,
|
||||
MatButtonModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
MatListModule,
|
||||
MatTableModule,
|
||||
Vflow,
|
||||
],
|
||||
// Forms are this page's only: Formly loads with it, not with the app.
|
||||
providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])],
|
||||
templateUrl: './conectar.html',
|
||||
styleUrl: './conectar.scss',
|
||||
})
|
||||
export class Conectar {
|
||||
private readonly api = inject(Api);
|
||||
private readonly jsonschema = inject(FormlyJsonschema);
|
||||
protected readonly kinds = Object.entries(KINDS) as [Kind, string][];
|
||||
|
||||
protected readonly list = resource({ loader: () => this.api.invoke(pipelines) });
|
||||
private readonly schema = resource({ loader: () => this.api.invoke(schema) });
|
||||
|
||||
protected readonly pipelineId = signal<string | undefined>(undefined);
|
||||
protected readonly version = signal<number | undefined>(undefined);
|
||||
/** The drawn pipeline: node configs (positions live on the canvas nodes). */
|
||||
protected readonly docs = signal<Doc[]>([]);
|
||||
protected readonly nodes = signal<CanvasNode[]>([]);
|
||||
protected readonly edges = computed(() =>
|
||||
this.docs().flatMap((d) =>
|
||||
(d.inputs ?? []).map((i) => ({ id: `${i}->${d.id}`, source: i, target: d.id })),
|
||||
),
|
||||
);
|
||||
protected readonly selected = signal<string | undefined>(undefined);
|
||||
protected readonly doc = computed(() => this.docs().find((d) => d.id === this.selected()));
|
||||
protected readonly message = signal('');
|
||||
protected readonly run = signal<{ id: string; status: string } | undefined>(undefined);
|
||||
protected readonly running = computed(() => {
|
||||
const run = this.run();
|
||||
return !!run && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(run.status);
|
||||
});
|
||||
|
||||
protected form = new UntypedFormGroup({});
|
||||
protected model: Record<string, unknown> = {};
|
||||
/** The selected node's form, generated from its kind's JSON Schema. */
|
||||
protected readonly fields = computed<FormlyFieldConfig[]>(() => {
|
||||
const kind = this.doc()?.kind;
|
||||
const pipeline = this.schema.value()?.['pipeline'];
|
||||
if (!kind || !pipeline) return [];
|
||||
return [this.jsonschema.toFieldConfig(nodeSchema(pipeline as never, kind))];
|
||||
});
|
||||
|
||||
protected readonly preview = signal<Record<string, unknown>[] | undefined>(undefined);
|
||||
protected readonly columns = computed(() => Object.keys(this.preview()?.[0] ?? {}));
|
||||
|
||||
async open(id: string): Promise<void> {
|
||||
const saved = await this.api.invoke(getPipeline, { pipeline_id: id });
|
||||
this.pipelineId.set(id);
|
||||
this.version.set(saved.version);
|
||||
this.load(saved.pipeline.nodes);
|
||||
this.message.set('');
|
||||
}
|
||||
|
||||
protected create(id: string): void {
|
||||
if (!ID.test(id)) {
|
||||
this.message.set('El nombre va en minúsculas, sin espacios (a-z, 0-9, _).');
|
||||
return;
|
||||
}
|
||||
this.pipelineId.set(id);
|
||||
this.version.set(undefined);
|
||||
this.load([]);
|
||||
this.message.set('');
|
||||
}
|
||||
|
||||
private load(docs: Doc[]): void {
|
||||
this.docs.set(docs);
|
||||
const depth = depths(docs);
|
||||
const row = new Map<number, number>();
|
||||
this.nodes.set(
|
||||
docs.map((d) => {
|
||||
const level = depth.get(d.id) ?? 0;
|
||||
const n = row.get(level) ?? 0;
|
||||
row.set(level, n + 1);
|
||||
const point = d.position ?? { x: 40 + level * 260, y: 40 + n * 90 };
|
||||
return canvasNode(d.id, point, text(d));
|
||||
}),
|
||||
);
|
||||
this.select(undefined);
|
||||
}
|
||||
|
||||
protected add(kind: Kind): void {
|
||||
let n = 1;
|
||||
while (this.docs().some((d) => d.id === `${kind}_${n}`)) n++;
|
||||
const id = `${kind}_${n}`;
|
||||
const doc = { id, kind, inputs: [] } as unknown as Doc;
|
||||
this.docs.update((ds) => [...ds, doc]);
|
||||
this.nodes.update((ns) => [
|
||||
...ns,
|
||||
canvasNode(id, { x: 60, y: 60 + ns.length * 30 }, text(doc)),
|
||||
]);
|
||||
this.select(id);
|
||||
}
|
||||
|
||||
protected remove(id: string): void {
|
||||
this.docs.update((ds) =>
|
||||
ds
|
||||
.filter((d) => d.id !== id)
|
||||
.map((d) => ({ ...d, inputs: (d.inputs ?? []).filter((i) => i !== id) })),
|
||||
);
|
||||
this.nodes.update((ns) => ns.filter((n) => n.id !== id));
|
||||
this.select(undefined);
|
||||
}
|
||||
|
||||
protected connect({ source, target }: Connection): void {
|
||||
this.update(target, (d) => ({ ...d, inputs: [...new Set([...(d.inputs ?? []), source])] }));
|
||||
}
|
||||
|
||||
protected disconnect(target: string, source: string): void {
|
||||
this.update(target, (d) => ({ ...d, inputs: (d.inputs ?? []).filter((i) => i !== source) }));
|
||||
}
|
||||
|
||||
protected changed(changes: NodeChange[]): void {
|
||||
for (const c of changes) {
|
||||
if (c.type === 'select' && c.selected) this.select(c.id);
|
||||
}
|
||||
}
|
||||
|
||||
protected select(id: string | undefined): void {
|
||||
this.selected.set(id);
|
||||
const doc = (this.docs().find((d) => d.id === id) ?? {}) as Record<string, unknown>;
|
||||
this.model = Object.fromEntries(
|
||||
Object.entries(structuredClone(doc)).filter(
|
||||
([k]) => !['id', 'kind', 'inputs', 'position'].includes(k),
|
||||
),
|
||||
);
|
||||
this.form = new UntypedFormGroup({});
|
||||
this.preview.set(undefined);
|
||||
}
|
||||
|
||||
/** The form's values into the selected node. */
|
||||
protected edited(model: Record<string, unknown>): void {
|
||||
const id = this.selected();
|
||||
if (!id) return;
|
||||
const values = Object.fromEntries(
|
||||
Object.entries(model).filter(([, v]) => v !== undefined && v !== null),
|
||||
);
|
||||
this.update(
|
||||
id,
|
||||
(d) => ({ ...values, id: d.id, kind: d.kind, inputs: d.inputs }) as unknown as Doc,
|
||||
);
|
||||
}
|
||||
|
||||
protected rename(to: string): void {
|
||||
const from = this.selected();
|
||||
if (!from || from === to || !ID.test(to) || this.docs().some((d) => d.id === to)) return;
|
||||
this.docs.update((ds) =>
|
||||
ds.map((d) => ({
|
||||
...d,
|
||||
id: d.id === from ? to : d.id,
|
||||
inputs: (d.inputs ?? []).map((i) => (i === from ? to : i)),
|
||||
})),
|
||||
);
|
||||
this.nodes.update((ns) => ns.map((n) => (n.id === from ? { ...n, id: to } : n)));
|
||||
this.selected.set(to);
|
||||
}
|
||||
|
||||
private update(id: string, change: (d: Doc) => Doc): void {
|
||||
this.docs.update((ds) => ds.map((d) => (d.id === id ? change(d) : d)));
|
||||
const doc = this.docs().find((d) => d.id === id);
|
||||
if (doc)
|
||||
this.nodes()
|
||||
.find((n) => n.id === id)
|
||||
?.text.set(text(doc));
|
||||
}
|
||||
|
||||
/** The drawn pipeline, each node where it sits on the canvas. */
|
||||
private drawn(): Pipeline {
|
||||
const at = new Map(this.nodes().map((n) => [n.id, n.point()]));
|
||||
return { nodes: this.docs().map((d) => ({ ...d, position: at.get(d.id) })) } as Pipeline;
|
||||
}
|
||||
|
||||
protected async save(): Promise<boolean> {
|
||||
const id = this.pipelineId();
|
||||
if (!id) return false;
|
||||
try {
|
||||
const { version } = await this.api.invoke(savePipeline, {
|
||||
pipeline_id: id,
|
||||
body: this.drawn(),
|
||||
});
|
||||
this.version.set(version);
|
||||
this.message.set(`Versión ${version} guardada.`);
|
||||
this.list.reload();
|
||||
return true;
|
||||
} catch (e) {
|
||||
this.message.set(problem(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves, starts the `ingest` job and follows it to its end. */
|
||||
protected async start(): Promise<void> {
|
||||
const id = this.pipelineId();
|
||||
if (!id || !(await this.save())) return;
|
||||
try {
|
||||
const { run_id } = await this.api.invoke(startRun, { pipeline_id: id, body: {} });
|
||||
this.run.set({ id: run_id, status: 'STARTING' });
|
||||
while (this.running()) {
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
this.run.set({
|
||||
id: run_id,
|
||||
status: (await this.api.invoke(runStatus, { run_id }))['status'],
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
this.message.set(problem(e));
|
||||
}
|
||||
}
|
||||
|
||||
/** What the node gives: a source's first rows, or what any other node gave in the last run. */
|
||||
protected async show(): Promise<void> {
|
||||
const doc = this.doc();
|
||||
const id = this.pipelineId();
|
||||
if (!doc || !id) return;
|
||||
try {
|
||||
const rows =
|
||||
doc.kind === '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 });
|
||||
this.preview.set(rows);
|
||||
this.message.set(rows.length ? '' : 'Sin filas todavía: ejecute la canalización.');
|
||||
} catch (e) {
|
||||
this.message.set(problem(e));
|
||||
}
|
||||
}
|
||||
|
||||
/** The run in Dagster's own UI (its port beside this app's). */
|
||||
protected readonly dagster = computed(() => {
|
||||
const run = this.run();
|
||||
return run ? `${location.protocol}//${location.hostname}:5712/runs/${run.id}` : '';
|
||||
});
|
||||
protected kindLabel(kind: Doc['kind']): string {
|
||||
return KINDS[kind ?? 'source'];
|
||||
}
|
||||
protected cell(value: unknown): string {
|
||||
return typeof value === 'object' && value !== null
|
||||
? JSON.stringify(value)
|
||||
: String(value ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
function text(d: Doc): string {
|
||||
return `${KINDS[d.kind ?? 'source']} · ${d.label || d.id}`;
|
||||
}
|
||||
|
||||
/** Each node's distance from the sources: its column when it has no saved position. */
|
||||
function depths(docs: Doc[]): Map<string, number> {
|
||||
const by = new Map(docs.map((d) => [d.id, d]));
|
||||
const found = new Map<string, number>();
|
||||
const depth = (id: string, seen: Set<string>): number => {
|
||||
if (found.has(id)) return found.get(id)!;
|
||||
if (seen.has(id)) return 0;
|
||||
seen.add(id);
|
||||
const inputs = by.get(id)?.inputs ?? [];
|
||||
const d = inputs.length ? 1 + Math.max(...inputs.map((i) => depth(i, seen))) : 0;
|
||||
found.set(id, d);
|
||||
return d;
|
||||
};
|
||||
docs.forEach((d) => depth(d.id, new Set()));
|
||||
return found;
|
||||
}
|
||||
|
||||
function problem(e: unknown): string {
|
||||
if (e instanceof HttpErrorResponse) {
|
||||
const detail = e.error?.detail;
|
||||
return typeof detail === 'string' ? detail : JSON.stringify(detail ?? e.message);
|
||||
}
|
||||
return String(e);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { nodeSchema } from './schema-form';
|
||||
|
||||
const PIPELINE = {
|
||||
$defs: {
|
||||
Position: { type: 'object', properties: { x: { type: 'number' } } },
|
||||
Condition: { type: 'object', properties: { column: { type: 'string' } } },
|
||||
Route: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['id', 'when'],
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
kind: { const: 'route' },
|
||||
inputs: { type: 'array' },
|
||||
position: { anyOf: [{ $ref: '#/$defs/Position' }, { type: 'null' }] },
|
||||
when: { type: 'array', items: { $ref: '#/$defs/Condition' } },
|
||||
resource: { anyOf: [{ type: 'string' }, { type: 'null' }], title: 'Resource' },
|
||||
values: { type: 'object', additionalProperties: { type: 'string' }, title: 'Values' },
|
||||
},
|
||||
},
|
||||
},
|
||||
} as never;
|
||||
|
||||
describe('node forms from the pipeline schema', () => {
|
||||
const schema = nodeSchema(PIPELINE, 'route') as any;
|
||||
|
||||
it('leaves out what the canvas edits', () => {
|
||||
expect(Object.keys(schema.properties)).toEqual(['when', 'resource', 'values']);
|
||||
expect(schema.required).toEqual(['when']);
|
||||
});
|
||||
|
||||
it('inlines references and drops null from optional values', () => {
|
||||
expect(schema.properties.when.items.properties.column.type).toBe('string');
|
||||
expect(schema.properties.resource.type).toBe('string');
|
||||
});
|
||||
|
||||
it('edits maps as JSON', () => {
|
||||
expect(schema.properties.values.widget.formlyConfig.type).toBe('json');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,166 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import {
|
||||
ConfigOption,
|
||||
FieldArrayType,
|
||||
FieldType,
|
||||
FormlyField,
|
||||
FormlyFieldConfig,
|
||||
} from '@ngx-formly/core';
|
||||
import type { JSONSchema7 } from 'json-schema';
|
||||
|
||||
type Schema = JSONSchema7 & { $defs?: Record<string, Schema>; prefixItems?: unknown };
|
||||
|
||||
/** The canvas edits these itself; the form leaves them out. */
|
||||
const CANVAS_FIELDS = ['id', 'kind', 'inputs', 'position'];
|
||||
|
||||
/** A node kind's form schema from the pipeline's JSON Schema (pydantic's): `$ref`s inlined,
|
||||
* optional values as their type, and maps or tuples (which forms don't draw) as JSON. */
|
||||
export function nodeSchema(pipeline: Schema, kind: string): Schema {
|
||||
const defs = pipeline.$defs ?? {};
|
||||
const name = Object.keys(defs).find(
|
||||
(k) => (defs[k].properties?.['kind'] as Schema | undefined)?.const === kind,
|
||||
)!;
|
||||
const node = structuredClone(defs[name]);
|
||||
for (const field of CANVAS_FIELDS) delete node.properties?.[field];
|
||||
node.required = (node.required ?? []).filter((f) => !CANVAS_FIELDS.includes(f));
|
||||
delete node.additionalProperties;
|
||||
return simplify(node, defs);
|
||||
}
|
||||
|
||||
function simplify(schema: Schema, defs: Record<string, Schema>): Schema {
|
||||
if (schema.$ref) {
|
||||
const { $ref, ...rest } = schema;
|
||||
return simplify({ ...structuredClone(defs[$ref.split('/').pop()!]), ...rest }, defs);
|
||||
}
|
||||
const options = schema.anyOf as Schema[] | undefined;
|
||||
if (options) {
|
||||
const kept = options.filter((o) => o.type !== 'null');
|
||||
if (kept.length === 1) {
|
||||
const { anyOf, ...rest } = schema;
|
||||
return simplify({ ...kept[0], ...rest }, defs);
|
||||
}
|
||||
}
|
||||
const isMap = schema.type === 'object' && !schema.properties;
|
||||
const isTuple =
|
||||
schema.type === 'array' &&
|
||||
(schema.prefixItems || (schema.items as Schema | undefined)?.prefixItems);
|
||||
if (isMap || isTuple || (!schema.type && !schema.enum && !schema.const)) {
|
||||
return {
|
||||
title: schema.title,
|
||||
description: schema.description,
|
||||
default: schema.default,
|
||||
widget: { formlyConfig: { type: 'json' } },
|
||||
} as Schema;
|
||||
}
|
||||
const out: Schema = { ...schema };
|
||||
if (schema.properties) {
|
||||
out.properties = Object.fromEntries(
|
||||
Object.entries(schema.properties).map(([k, v]) => [k, simplify(v as Schema, defs)]),
|
||||
);
|
||||
}
|
||||
if (schema.items && !Array.isArray(schema.items))
|
||||
out.items = simplify(schema.items as Schema, defs);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** An object's fields, one after another. */
|
||||
@Component({
|
||||
selector: 'app-formly-object',
|
||||
imports: [FormlyField],
|
||||
template: `
|
||||
@if (props.label) {
|
||||
<div class="legend">{{ props.label }}</div>
|
||||
}
|
||||
@if (props.description) {
|
||||
<p class="hint">{{ props.description }}</p>
|
||||
}
|
||||
@for (f of field.fieldGroup; track $index) {
|
||||
<formly-field [field]="f" />
|
||||
}
|
||||
`,
|
||||
styles:
|
||||
'.legend { font-weight: 500; margin: 8px 0 4px; } .hint { color: var(--color-text-secondary); font-size: 12px; margin: 0 0 8px; }',
|
||||
})
|
||||
export class ObjectType extends FieldType {}
|
||||
|
||||
/** A list: each item with a remove button, and an add button. */
|
||||
@Component({
|
||||
selector: 'app-formly-array',
|
||||
imports: [FormlyField, MatButtonModule, MatIconModule],
|
||||
template: `
|
||||
<div class="legend">{{ props.label }}</div>
|
||||
@for (f of field.fieldGroup; track $index; let i = $index) {
|
||||
<div class="item">
|
||||
<formly-field [field]="f" />
|
||||
<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: 8px 0 4px; } .item { display: flex; align-items: flex-start; gap: 4px; } .item formly-field { flex: 1; }',
|
||||
})
|
||||
export class ArrayType extends FieldArrayType {}
|
||||
|
||||
/** A value forms don't draw (a map, a pair, anything), edited as JSON. */
|
||||
@Component({
|
||||
selector: 'app-formly-json',
|
||||
imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
|
||||
template: `
|
||||
<mat-form-field appearance="outline" class="json">
|
||||
<mat-label>{{ props.label }} (JSON)</mat-label>
|
||||
<textarea
|
||||
matInput
|
||||
rows="4"
|
||||
[value]="text()"
|
||||
(change)="parse($any($event.target).value)"
|
||||
></textarea>
|
||||
@if (error) {
|
||||
<mat-error>{{ error }}</mat-error>
|
||||
}
|
||||
@if (props.description) {
|
||||
<mat-hint>{{ props.description }}</mat-hint>
|
||||
}
|
||||
</mat-form-field>
|
||||
`,
|
||||
styles: '.json { width: 100%; } textarea { font-family: monospace; font-size: 12px; }',
|
||||
})
|
||||
export class JsonType extends FieldType<FormlyFieldConfig> {
|
||||
protected error = '';
|
||||
protected text(): string {
|
||||
return this.formControl.value === undefined
|
||||
? ''
|
||||
: JSON.stringify(this.formControl.value, null, 1);
|
||||
}
|
||||
protected parse(value: string): void {
|
||||
try {
|
||||
this.formControl.setValue(value.trim() ? JSON.parse(value) : undefined);
|
||||
this.formControl.markAsDirty();
|
||||
this.error = '';
|
||||
} catch {
|
||||
this.error = 'No es JSON válido';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const FORMLY_TYPES: ConfigOption = {
|
||||
types: [
|
||||
{ name: 'object', component: ObjectType },
|
||||
{ name: 'array', component: ArrayType },
|
||||
{ name: 'json', component: JsonType },
|
||||
{ name: 'enum', extends: 'select' },
|
||||
{ name: 'string', extends: 'input' },
|
||||
{ name: 'number', extends: 'input', defaultOptions: { props: { type: 'number' } } },
|
||||
{ name: 'integer', extends: 'input', defaultOptions: { props: { type: 'number' } } },
|
||||
{ name: 'boolean', extends: 'checkbox' },
|
||||
],
|
||||
};
|
||||
Reference in New Issue
Block a user