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; 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): 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) {
{{ props.label }}
} @if (props.description) {

{{ props.description }}

} @for (f of field.fieldGroup; track $index) { } `, 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: `
{{ props.label }}
@for (f of field.fieldGroup; track $index; let i = $index) {
} `, 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: ` {{ props.label }} @if (error) { {{ error }} } @if (props.description) { {{ props.description }} } `, styles: '.json { width: 100%; } textarea { font-family: monospace; font-size: 12px; }', }) export class JsonType extends FieldType { 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: `
{{ props.label }}
@if (props.description) {

{{ props.description }}

} @for (row of rows(); track $index; let i = $index) {
{{ props['fieldKeys'] ? 'Dato' : 'Nombre' }} @if (props['fieldKeys']) { @for (o of keyOptions(row[0]); track o[0]) { {{ o[1] }} } } @else { } Valor
} `, 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 { /** 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>; const entity = (this.model as Record | undefined)?.['entity'] as string | undefined; const titles: Record = 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); } 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: `
{{ props.label }}
@if (props.description) {

{{ props.description }}

} @for (row of rows(); track $index; let i = $index) {
Primera entrada = Segunda entrada
} `, 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 { 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' }, ], };