Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

introduce middleware support #2220

Merged
merged 2 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/react/src/JsonForms.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
} from '@jsonforms/core';
import {
JsonFormsStateProvider,
Middleware,
withJsonFormsRendererProps,
} from './JsonFormsContext';

Expand All @@ -54,6 +55,7 @@ interface JsonFormsRendererState {

export interface JsonFormsReactProps {
onChange?(state: Pick<JsonFormsCore, 'data' | 'errors'>): void;
middleware?: Middleware;
}

export class JsonFormsDispatchRenderer extends React.Component<
Expand Down Expand Up @@ -203,6 +205,7 @@ export const JsonForms = (
validationMode,
i18n,
additionalErrors,
middleware,
} = props;
const schemaToUse = useMemo(
() => (schema !== undefined ? schema : Generate.jsonSchema(data)),
Expand Down Expand Up @@ -233,6 +236,7 @@ export const JsonForms = (
i18n,
}}
onChange={onChange}
middleware={middleware}
>
<JsonFormsDispatch />
</JsonFormsStateProvider>
Expand Down
58 changes: 44 additions & 14 deletions packages/react/src/JsonFormsContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ import {
OwnPropsOfLabel,
LabelProps,
mapStateToLabelProps,
CoreActions,
} from '@jsonforms/core';
import debounce from 'lodash/debounce';
import React, {
Expand All @@ -87,6 +88,7 @@ import React, {
useMemo,
useReducer,
useRef,
useState,
} from 'react';

const initialCoreState: JsonFormsCore = {
Expand Down Expand Up @@ -126,33 +128,56 @@ 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,
onChange,
middleware,
}: any) => {
const { data, schema, uischema, ajv, validationMode, additionalErrors } =
initState.core;

const [core, coreDispatch] = useReducer(coreReducer, undefined, () =>
coreReducer(
const middlewareRef = useRef<Middleware>(middleware ?? defaultMiddleware);
middlewareRef.current = middleware ?? defaultMiddleware;

const [core, setCore] = useState<JsonFormsCore>(() =>
middlewareRef.current(
initState.core,
Actions.init(data, schema, uischema, {
ajv,
validationMode,
additionalErrors,
})
}),
coreReducer
)
);
useEffect(() => {
coreDispatch(
Actions.updateCore(data, schema, uischema, {
ajv,
validationMode,
additionalErrors,
})
);
}, [data, schema, uischema, ajv, validationMode, additionalErrors]);

useEffect(
() =>
setCore((currentCore) =>
middlewareRef.current(
currentCore,
Actions.updateCore(data, schema, uischema, {
ajv,
validationMode,
additionalErrors,
}),
coreReducer
)
),
[data, schema, uischema, ajv, validationMode, additionalErrors]
);

const [config, configDispatch] = useReducer(configReducer, undefined, () =>
configReducer(undefined, Actions.setConfig(initState.config))
Expand Down Expand Up @@ -185,6 +210,12 @@ export const JsonFormsStateProvider = ({
initState.i18n?.translateError,
]);

const dispatch = useCallback((action: CoreActions) => {
setCore((currentCore) =>
middlewareRef.current(currentCore, action, coreReducer)
);
}, []);

const contextValue = useMemo(
() => ({
core,
Expand All @@ -194,8 +225,7 @@ export const JsonFormsStateProvider = ({
uischemas: initState.uischemas,
readonly: initState.readonly,
i18n: i18n,
// only core dispatch available
dispatch: coreDispatch,
dispatch: dispatch,
}),
[
core,
Expand Down
142 changes: 142 additions & 0 deletions packages/react/test/renderers/JsonForms.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import {
} from '../../src/JsonForms';
import {
JsonFormsStateProvider,
Middleware,
useJsonForms,
withJsonFormsControlProps,
} from '../../src/JsonFormsContext';
Expand Down Expand Up @@ -1100,3 +1101,144 @@ test('JsonForms should use react to additionalErrors update', () => {
expect(wrapper.find('h5').text()).toBe('Foobar');
wrapper.unmount();
});

test('JsonForms middleware should be called if provided', async () => {
// given
const onChangeHandler = jest.fn();
const customMiddleware = jest.fn();
const TestInputRenderer = withJsonFormsControlProps((props) => (
<input
onChange={(ev) => props.handleChange('foo', ev.target.value)}
value={props.data}
/>
));
const renderers = [
{
tester: () => 10,
renderer: TestInputRenderer,
},
];
const controlledMiddleware: Middleware = (state, action, reducer) => {
if (action.type === 'jsonforms/UPDATE') {
customMiddleware();
return state;
} else {
return reducer(state, action);
}
};
const wrapper = mount(
<JsonForms
data={fixture.data}
uischema={fixture.uischema}
schema={fixture.schema}
middleware={controlledMiddleware}
onChange={onChangeHandler}
renderers={renderers}
/>
);

// wait for 50 ms for the change handler invocation
await new Promise((resolve) => setTimeout(resolve, 50));

// initial rendering should call onChange 1 time
expect(onChangeHandler).toHaveBeenCalledTimes(1);
const calls = onChangeHandler.mock.calls;
const lastCallParameter = calls[calls.length - 1][0];
expect(lastCallParameter.data).toEqual({ foo: 'John Doe' });
expect(lastCallParameter.errors).toEqual([]);

// adapt test input
wrapper.find('input').simulate('change', {
target: {
value: 'Test Value',
},
});

expect(customMiddleware).toHaveBeenCalledTimes(1);

// wait for 50 ms for the change handler invocation
await new Promise((resolve) => setTimeout(resolve, 50));
// change handler should not have been called another time as we blocked the update in the middleware
expect(onChangeHandler).toHaveBeenCalledTimes(1);
// The rendered field should also not have been updated
expect(wrapper.find('input').getDOMNode<HTMLInputElement>().value).toBe(
'John Doe'
);

wrapper.unmount();
});

test('JsonForms middleware should update state if modified', async () => {
// given
const onChangeHandler = jest.fn();
const customMiddleware = jest.fn();
const TestInputRenderer = withJsonFormsControlProps((props) => (
<input
onChange={(ev) => props.handleChange('foo', ev.target.value)}
value={props.data}
/>
));
const renderers = [
{
tester: () => 10,
renderer: TestInputRenderer,
},
];
const controlledMiddleware: Middleware = (state, action, reducer) => {
if (action.type === 'jsonforms/UPDATE') {
customMiddleware();
const newState = reducer(state, action);
return { ...newState, data: { foo: `${newState.data.foo} Test` } };
} else {
return reducer(state, action);
}
};
const wrapper = mount(
<JsonForms
data={fixture.data}
uischema={fixture.uischema}
schema={fixture.schema}
middleware={controlledMiddleware}
onChange={onChangeHandler}
renderers={renderers}
/>
);

// wait for 50 ms for the change handler invocation
await new Promise((resolve) => setTimeout(resolve, 50));

// initial rendering should call onChange 1 time
expect(onChangeHandler).toHaveBeenCalledTimes(1);
{
const calls = onChangeHandler.mock.calls;
const lastCallParameter = calls[calls.length - 1][0];
expect(lastCallParameter.data).toEqual({ foo: 'John Doe' });
expect(lastCallParameter.errors).toEqual([]);
}

// adapt input
wrapper.find('input').simulate('change', {
target: {
value: 'Test Value',
},
});

// then
expect(customMiddleware).toHaveBeenCalledTimes(1);
expect(wrapper.find('input').getDOMNode<HTMLInputElement>().value).toBe(
'Test Value Test'
);

// wait for 50 ms for the change handler invocation
await new Promise((resolve) => setTimeout(resolve, 50));
// onChangeHandler should have been called after the state update
expect(onChangeHandler).toHaveBeenCalledTimes(2);
{
const calls = onChangeHandler.mock.calls;
const lastCallParameter = calls[calls.length - 1][0];
expect(lastCallParameter.data).toEqual({ foo: 'Test Value Test' });
expect(lastCallParameter.errors).toEqual([]);
}

wrapper.unmount();
});