Files
WebApp/src/app/conectar/schema-form.ts
T

401 lines
14 KiB
TypeScript

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 { MatSelectModule } from '@angular/material/select';
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];
// 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;
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 {
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 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 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 }}</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';
}
}
}
/** 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 = {
types: [
{ name: 'object', component: ObjectType },
{ name: 'array', component: ArrayType },
{ name: 'json', component: JsonType },
{ name: 'map', component: MapType },
{ name: 'pairs', component: PairsType },
{ 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' },
],
};