rework params-form logic out of schema service

This commit is contained in:
Joel Wetzell
2026-04-03 18:48:06 -05:00
parent 71b9eb6ec5
commit 653c65c00f
6 changed files with 368 additions and 337 deletions
@@ -5,6 +5,7 @@ import { MatIconModule } from '@angular/material/icon';
import { ParamInfo } from '../../models/form.model';
import { ListsService } from '../../services/lists.service';
import { SchemaService } from '../../services/schema.service';
import { parseStringToArray } from '../../utils/params.utils';
@Component({
selector: 'app-array-form',
@@ -30,7 +31,7 @@ export class ArrayFormComponent implements OnInit {
ngOnInit(): void {
if (this.paramFormControl && this.paramInfo?.schema) {
if (!Array.isArray(this.paramFormControl.value)) {
this.arrayValue = this.schemaService.parseStringToArray(
this.arrayValue = parseStringToArray(
this.paramFormControl.value,
this.paramInfo.schema,
);
@@ -1,15 +1,4 @@
@if (paramsSchema && paramsFormInfo) {
@if (paramsOptions.length > 1) {
<mat-tab-group
dynamicHeight
[selectedIndex]="paramsOptionsSelectedIndex"
(selectedTabChange)="paramsOptionsTabSelected($event)"
>
@for (paramsOption of paramsOptions; track paramsOption) {
<mat-tab [label]="paramsOption.display"></mat-tab>
}
</mat-tab-group>
}
<form [formGroup]="paramsFormInfo.formGroup">
<div class="flex flex-col">
@for (key of paramKeys(); track key) {
@@ -0,0 +1,95 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { ParamsFormComponent } from './params-form.component';
import { SchemaService } from '../../services/schema.service';
import { SomeJSONSchema } from 'ajv/dist/types/json-schema';
describe('ParamsForm', ()=>{
let component: ParamsFormComponent;
let fixture: ComponentFixture<ParamsFormComponent>;
beforeEach(async ()=>{
fixture = TestBed.createComponent(ParamsFormComponent);
component = fixture.componentInstance;
await fixture.whenStable();
})
it('should create', ()=>{
expect(component).toBeTruthy();
})
it('should create form for schema', async ()=>{
const paramsSchema: SomeJSONSchema = {
type: "object",
properties: {},
required: []
}
fixture.componentRef.setInput('paramsSchema', paramsSchema)
await fixture.whenStable()
expect(fixture.nativeElement.querySelector('form')).toBeTruthy()
})
it('form should have input for string property', async ()=>{
const paramsSchema: SomeJSONSchema = {
type: "object",
properties: {
"test": {
type: "string",
}
},
required: []
}
fixture.componentRef.setInput('paramsSchema', paramsSchema)
await fixture.whenStable()
const formEl = fixture.nativeElement.querySelector('form')
expect(formEl).toBeDefined()
const inputEl = formEl.querySelector('input')
expect(inputEl).toBeDefined()
})
it('form should have select for string enum property', async ()=>{
const paramsSchema: SomeJSONSchema = {
type: "object",
properties: {
"test": {
type: "string",
enum: ['one','two','three']
}
},
required: []
}
fixture.componentRef.setInput('paramsSchema', paramsSchema)
await fixture.whenStable()
const formEl = fixture.nativeElement.querySelector('form')
expect(formEl).toBeDefined()
const selectEl = formEl.querySelector('select')
expect(selectEl).toBeDefined()
})
it('form input should reflect data', async ()=>{
const paramsSchema: SomeJSONSchema = {
type: "object",
properties: {
"test": {
type: "string",
}
},
required: []
}
fixture.componentRef.setInput('paramsSchema', paramsSchema)
await fixture.whenStable()
fixture.componentRef.setInput('data', {
test: 'hello'
})
await fixture.whenStable()
const inputEl = fixture.nativeElement.querySelector('input')
expect(inputEl).toBeDefined()
expect(inputEl.value).toBe('hello')
fixture.componentRef.setInput('data', {
test: 'changed'
})
await fixture.whenStable()
expect(inputEl.value).toBe('changed')
})
})
@@ -1,18 +1,18 @@
import { JsonPipe } from '@angular/common';
import { Component, inject, Input, OnInit, output } from '@angular/core';
import { Component, inject, Input, OnChanges, OnDestroy, OnInit, output, SimpleChange, SimpleChanges } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs';
import { MatTabsModule } from '@angular/material/tabs';
import { MatTooltipModule } from '@angular/material/tooltip';
import { SomeJSONSchema } from 'ajv/dist/types/json-schema';
import { cloneDeep, has } from 'lodash-es';
import { cloneDeep, has, isEqual } from 'lodash-es';
import { Subscription } from 'rxjs';
import { ParamInfo, ParamsFormInfo } from '../../models/form.model';
import { SchemaService } from '../../services/schema.service';
import { cleanParams, schemaToParamsFormInfo } from '../../utils/params.utils';
import { ArrayFormComponent } from '../array-form/array-form.component';
@Component({
selector: 'app-params-form',
templateUrl: './params-form.component.html',
@@ -29,7 +29,7 @@ import { ArrayFormComponent } from '../array-form/array-form.component';
],
standalone: true,
})
export class ParamsFormComponent implements OnInit {
export class ParamsFormComponent implements OnChanges, OnDestroy {
@Input() paramsSchema?: SomeJSONSchema;
@Input() data?: any;
updated = output<any>();
@@ -37,136 +37,75 @@ export class ParamsFormComponent implements OnInit {
paramsFormInfo?: ParamsFormInfo;
formGroupSubscription?: Subscription;
paramsOptions: {
display: string;
paramsFormInfo: ParamsFormInfo;
keys: string[];
schema: SomeJSONSchema;
}[] = [];
paramsOptionsSelectedIndex: number = 0;
private schemaService = inject(SchemaService);
constructor() {}
ngOnInit(): void {
if (this.paramsSchema) {
if (this.paramsSchema.properties) {
this.paramsFormInfo = this.schemaService.getFormInfoFromParamsSchema(this.paramsSchema);
} else if (this.paramsSchema.oneOf) {
this.paramsOptions = this.paramsSchema.oneOf.map((oneOf: any, index: number) => {
const paramsOption = {
display: oneOf.title ? oneOf.title : `Option ${index + 1}`,
schema: oneOf,
paramsFormInfo: this.schemaService.getFormInfoFromParamsSchema(oneOf),
};
return {
...paramsOption,
keys: Object.keys(paramsOption.paramsFormInfo.formGroup.controls),
};
});
const matchingSchemaIndex = this.schemaService.matchParamsDataToSchema(
this.data,
this.paramsOptions.map((paramsOption) => paramsOption.schema),
);
this.paramsOptionsSelectedIndex = matchingSchemaIndex;
this.paramsFormInfo = this.paramsOptions[matchingSchemaIndex].paramsFormInfo;
this.paramsSchema = this.paramsOptions[matchingSchemaIndex].schema;
} else {
console.error('params is not a singular or oneOf');
console.error(this.paramsSchema);
}
ngOnDestroy(): void {
console.log('params-form destroyed')
if (this.formGroupSubscription) {
this.formGroupSubscription.unsubscribe()
}
if (this.data && this.paramsFormInfo?.formGroup) {
// NOTE(jwetzell): prepare data for form patching
const dataToPatch = cloneDeep(this.data);
Object.entries(this.paramsFormInfo.paramsInfo).forEach(([paramKey, paramInfo]) => {
if (has(dataToPatch, paramKey)) {
switch (paramInfo.type) {
case 'object':
dataToPatch[paramKey] = JSON.stringify(dataToPatch[paramKey]);
break;
case 'array':
dataToPatch[paramKey] = dataToPatch[paramKey]
.map((item: any) => {
switch (typeof item) {
case 'object':
return JSON.stringify(item);
default:
return item;
}
})
.join(',');
break;
default:
break;
}
}
});
this.paramsFormInfo.formGroup.patchValue(dataToPatch);
}
this.formGroupSubscription = this.paramsFormInfo?.formGroup.valueChanges.subscribe((value) => {
this.formUpdated();
});
}
paramsOptionsTabSelected(event: MatTabChangeEvent) {
// NOTE(jwetzell): no longer interested in the old formGroup valueChanges
if (this.formGroupSubscription) {
this.formGroupSubscription.unsubscribe();
}
const paramsOption = this.paramsOptions[event.index];
this.paramsSchema = paramsOption.schema;
this.paramsFormInfo = paramsOption.paramsFormInfo;
// NOTE(jwetzell): modify params that should change from the data when switch paramOptions
Object.entries(this.paramsFormInfo.paramsInfo).forEach(([paramKey, paramInfo]) => {
if (this.data !== undefined) {
if (paramInfo.isConst) {
if (this.data[paramKey]) {
delete this.data[paramKey];
}
}
if (paramInfo.default) {
if (this.data[paramKey] !== undefined && this.data[paramKey] !== paramInfo.default) {
this.data[paramKey] = paramInfo.default;
ngOnChanges(changes: SimpleChanges<{
paramsSchema: SomeJSONSchema
data: any
}>): void {
console.log(changes)
if (changes.paramsSchema) {
if (changes.paramsSchema.previousValue === undefined && changes.paramsSchema.currentValue !== undefined) {
if (this.paramsSchema) {
if (this.paramsSchema.properties) {
this.paramsFormInfo = schemaToParamsFormInfo(this.paramsSchema);
if (this.formGroupSubscription === undefined) {
this.formGroupSubscription = this.paramsFormInfo?.formGroup.valueChanges.subscribe((value) => {
this.formUpdated();
});
}
} else {
console.error('params is not a singular object');
console.error(this.paramsSchema);
}
}
}
});
}
const allowedParamKeys = Object.keys(this.paramsSchema?.properties);
if (this.data) {
// NOTE(jwetzell): remove keys that aren't allowed in the new params variation
Object.keys(this.data).forEach((paramKey) => {
if (allowedParamKeys && !allowedParamKeys.includes(paramKey)) {
delete this.data[paramKey];
if (changes.data) {
if (!isEqual(changes.data.currentValue, changes.data.previousValue)) {
if (this.paramsFormInfo?.formGroup !== undefined) {
// NOTE(jwetzell): prepare data for form patching
const dataToPatch = cloneDeep(this.data);
Object.entries(this.paramsFormInfo.paramsInfo).forEach(([paramKey, paramInfo]) => {
if (has(dataToPatch, paramKey)) {
switch (paramInfo.type) {
case 'object':
dataToPatch[paramKey] = JSON.stringify(dataToPatch[paramKey]);
break;
case 'array':
dataToPatch[paramKey] = dataToPatch[paramKey]
.map((item: any) => {
switch (typeof item) {
case 'object':
return JSON.stringify(item);
default:
return item;
}
})
.join(',');
break;
default:
break;
}
}
});
this.paramsFormInfo.formGroup.patchValue(dataToPatch);
}
});
}
if (this.paramsFormInfo.formGroup) {
this.formGroupSubscription = this.paramsFormInfo.formGroup.valueChanges.subscribe((value) => {
this.formUpdated();
});
}
if (this.data && this.paramsFormInfo.formGroup) {
this.paramsFormInfo.formGroup.patchValue(this.data);
}
}
}
formUpdated() {
if (this.paramsSchema) {
const params = this.schemaService.cleanParams(
const params = cleanParams(
this.paramsSchema,
this.paramsFormInfo?.formGroup.value,
);
@@ -186,14 +125,16 @@ export class ParamsFormComponent implements OnInit {
getParamInfo(key: string): ParamInfo | undefined {
return this.paramsFormInfo?.paramsInfo[key];
}
getParamValue(key: string) {
if (this.paramsSchema) {
const params = this.schemaService.cleanParams(
const params = cleanParams(
this.paramsSchema,
this.paramsFormInfo?.formGroup.value,
);
return params[key];
}
}
}