Skip to content

Commit

Permalink
feat: Add Middleware Support for Angular and Vue
Browse files Browse the repository at this point in the history
This commit implements middleware support for both Angular and Vue,
addressing the discussion in issue #2174
  • Loading branch information
LukasBoll committed Jan 9, 2024
1 parent b00754c commit 46c2146
Show file tree
Hide file tree
Showing 9 changed files with 170 additions and 43 deletions.
89 changes: 89 additions & 0 deletions packages/angular-material/test/middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
The MIT License
Copyright (c) 2023-2023 EclipseSource Munich
https://github.com/eclipsesource/jsonforms
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

import { ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { NumberControlRenderer } from '../src';
import { JsonFormsAngularService, JsonFormsControl } from '@jsonforms/angular';
import {
baseSetup,
getJsonFormsService,
prepareComponent,
} from '@jsonforms/angular-test';

const imports = [
MatFormFieldModule,
MatInputModule,
NoopAnimationsModule,
ReactiveFormsModule,
];
const providers = [JsonFormsAngularService];
const componentUT: any = NumberControlRenderer;
const testConfig = { imports, providers, componentUT };

describe('middleware tests', () => {
let component: JsonFormsControl;
const startingValues = {
core: {
data: 'startValue',
schema: { type: 'string' },
uischema: {
type: 'control',
},
},
};

baseSetup(testConfig);

beforeEach(() => {
const preparedComponents = prepareComponent(testConfig, 'input');
component = preparedComponents.component;
});

it('init using middleware', () => {
const jsonFormsService: JsonFormsAngularService =
getJsonFormsService(component);
const spyMiddleware = jasmine.createSpy('spy1').and.returnValue({
data: 4,
schema: { type: 'number' },
uischema: {
type: 'VerticalLayout',
elements: [
{
type: 'Control',
},
],
},
});
jsonFormsService.init(startingValues, spyMiddleware);
expect(spyMiddleware).toHaveBeenCalled();
const core = jsonFormsService.getState().jsonforms.core;
expect(core?.data).toBe(4);
expect(core?.schema.type).toBe('number');
expect(core?.uischema.type).toBe('VerticalLayout');
});
});
34 changes: 20 additions & 14 deletions packages/angular/src/library/jsonforms-root.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,11 @@ import {
JsonFormsI18nState,
JsonFormsRendererRegistryEntry,
JsonSchema,
Middleware,
UISchemaElement,
UISchemaTester,
ValidationMode,
defaultMiddleware,
} from '@jsonforms/core';
import Ajv, { ErrorObject } from 'ajv';
import { JsonFormsAngularService, USE_STATE_VALUE } from './jsonforms.service';
Expand All @@ -64,6 +66,7 @@ export class JsonForms implements DoCheck, OnChanges, OnInit {
@Input() config: any;
@Input() i18n: JsonFormsI18nState;
@Input() additionalErrors: ErrorObject[];
@Input() middleware: Middleware = defaultMiddleware;
@Output() errors = new EventEmitter<ErrorObject[]>();

private previousData: any;
Expand All @@ -75,21 +78,24 @@ export class JsonForms implements DoCheck, OnChanges, OnInit {
constructor(private jsonformsService: JsonFormsAngularService) {}

ngOnInit(): void {
this.jsonformsService.init({
core: {
data: this.data,
uischema: this.uischema,
schema: this.schema,
ajv: this.ajv,
validationMode: this.validationMode,
additionalErrors: this.additionalErrors,
this.jsonformsService.init(
{
core: {
data: this.data,
uischema: this.uischema,
schema: this.schema,
ajv: this.ajv,
validationMode: this.validationMode,
additionalErrors: this.additionalErrors,
},
uischemas: this.uischemas,
i18n: this.i18n,
renderers: this.renderers,
config: this.config,
readonly: this.readonly,
},
uischemas: this.uischemas,
i18n: this.i18n,
renderers: this.renderers,
config: this.config,
readonly: this.readonly,
});
this.middleware
);
this.jsonformsService.$state.subscribe((state) => {
const data = state?.jsonforms?.core?.data;
const errors = state?.jsonforms?.core?.errors;
Expand Down
38 changes: 28 additions & 10 deletions packages/angular/src/library/jsonforms.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ import {
UISchemaTester,
ValidationMode,
updateI18n,
Middleware,
defaultMiddleware,
} from '@jsonforms/core';
import { BehaviorSubject, Observable } from 'rxjs';
import type { JsonFormsBaseRenderer } from './base.renderer';
Expand All @@ -56,6 +58,7 @@ export const USE_STATE_VALUE = Symbol('Marker to use state value');
export class JsonFormsAngularService {
private _state: JsonFormsSubStates;
private state: BehaviorSubject<JsonFormsState>;
private middleware: Middleware;

init(
initialState: JsonFormsSubStates = {
Expand All @@ -66,8 +69,10 @@ export class JsonFormsAngularService {
validationMode: 'ValidateAndShow',
additionalErrors: undefined,
},
}
},
middleware: Middleware = defaultMiddleware
) {
this.middleware = middleware;
this._state = initialState;
this._state.config = configReducer(
undefined,
Expand Down Expand Up @@ -143,9 +148,10 @@ export class JsonFormsAngularService {
}

updateValidationMode(validationMode: ValidationMode): void {
const coreState = coreReducer(
const coreState = this.middleware(
this._state.core,
Actions.setValidationMode(validationMode)
Actions.setValidationMode(validationMode),
coreReducer
);
this._state.core = coreState;
this.updateSubject();
Expand All @@ -161,7 +167,11 @@ export class JsonFormsAngularService {
}

updateCore<T extends CoreActions>(coreAction: T): T {
const coreState = coreReducer(this._state.core, coreAction);
const coreState = this.middleware(
this._state.core,
coreAction,
coreReducer
);
if (coreState !== this._state.core) {
this._state.core = coreState;
this.updateSubject();
Expand Down Expand Up @@ -199,13 +209,14 @@ export class JsonFormsAngularService {
setUiSchema(uischema: UISchemaElement | undefined): void {
const newUiSchema =
uischema ?? generateDefaultUISchema(this._state.core.schema);
const coreState = coreReducer(
const coreState = this.middleware(
this._state.core,
Actions.updateCore(
this._state.core.data,
this._state.core.schema,
newUiSchema
)
),
coreReducer
);
if (coreState !== this._state.core) {
this._state.core = coreState;
Expand All @@ -214,13 +225,14 @@ export class JsonFormsAngularService {
}

setSchema(schema: JsonSchema | undefined): void {
const coreState = coreReducer(
const coreState = this.middleware(
this._state.core,
Actions.updateCore(
this._state.core.data,
schema ?? generateJsonSchema(this._state.core.data),
this._state.core.uischema
)
),
coreReducer
);
if (coreState !== this._state.core) {
this._state.core = coreState;
Expand All @@ -229,13 +241,14 @@ export class JsonFormsAngularService {
}

setData(data: any): void {
const coreState = coreReducer(
const coreState = this.middleware(
this._state.core,
Actions.updateCore(
data,
this._state.core.schema,
this._state.core.uischema
)
),
coreReducer
);
if (coreState !== this._state.core) {
this._state.core = coreState;
Expand All @@ -257,6 +270,11 @@ export class JsonFormsAngularService {
this.updateSubject();
}

setMiddleware(middleware: Middleware): void {
this._state.middleware = middleware;
this.updateSubject();
}

getState(): JsonFormsState {
return cloneDeep({ jsonforms: this._state });
}
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/reducers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ export * from './reducers';
export * from './renderers';
export * from './selectors';
export * from './uischemas';
export * from './middleware';
12 changes: 12 additions & 0 deletions packages/core/src/reducers/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { CoreActions } from '../actions';
import { JsonFormsCore } from './core';

export interface Middleware {
(
state: JsonFormsCore,
action: CoreActions,
defaultReducer: (state: JsonFormsCore, action: CoreActions) => JsonFormsCore
): JsonFormsCore;
}
export const defaultMiddleware: Middleware = (state, action, defaultReducer) =>
defaultReducer(state, action);
2 changes: 1 addition & 1 deletion packages/react/src/JsonForms.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ import {
JsonFormsRendererRegistryEntry,
JsonFormsUISchemaRegistryEntry,
JsonSchema,
Middleware,
OwnPropsOfJsonFormsRenderer,
removeId,
UISchemaElement,
ValidationMode,
} from '@jsonforms/core';
import {
JsonFormsStateProvider,
Middleware,
withJsonFormsRendererProps,
} from './JsonFormsContext';

Expand Down
13 changes: 2 additions & 11 deletions packages/react/src/JsonFormsContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ import {
LabelProps,
mapStateToLabelProps,
CoreActions,
Middleware,
defaultMiddleware,
} from '@jsonforms/core';
import debounce from 'lodash/debounce';
import React, {
Expand Down Expand Up @@ -128,17 +130,6 @@ const useEffectAfterFirstRender = (
}, dependencies);
};

export interface Middleware {
(
state: JsonFormsCore,
action: CoreActions,
defaultReducer: (state: JsonFormsCore, action: CoreActions) => JsonFormsCore
): JsonFormsCore;
}

const defaultMiddleware: Middleware = (state, action, defaultReducer) =>
defaultReducer(state, action);

export const JsonFormsStateProvider = ({
children,
initState,
Expand Down
2 changes: 1 addition & 1 deletion packages/react/test/renderers/JsonForms.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import type {
JsonFormsStore,
JsonSchema,
Layout,
Middleware,
RendererProps,
UISchemaElement,
} from '@jsonforms/core';
Expand All @@ -58,7 +59,6 @@ import {
} from '../../src/JsonForms';
import {
JsonFormsStateProvider,
Middleware,
useJsonForms,
withJsonFormsControlProps,
} from '../../src/JsonFormsContext';
Expand Down
Loading

0 comments on commit 46c2146

Please sign in to comment.