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

feat: implement validate on blur & input #610

Merged
merged 1 commit into from
Jul 27, 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
14 changes: 12 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 7 additions & 3 deletions packages/form-js-viewer/src/Form.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import Ids from 'ids';
import { get, isString, set } from 'min-dash';

import ExpressionLanguageModule from './features/expression-language';
import MarkdownModule from './features/markdown';
import {
ExpressionLanguageModule,
MarkdownModule,
ViewerCommandsModule
} from './features';

import core from './core';

Expand Down Expand Up @@ -381,7 +384,8 @@ export default class Form {
_getModules() {
return [
ExpressionLanguageModule,
MarkdownModule
MarkdownModule,
ViewerCommandsModule
];
}

Expand Down
4 changes: 3 additions & 1 deletion packages/form-js-viewer/src/features/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export { default as ExpressionLanguageModule } from './expression-language';
export { default as MarkdownModule } from './markdown';
export { default as ViewerCommandsModule } from './viewerCommands';

export * from './expression-language';
export * from './markdown';
export * from './markdown';
export * from './viewerCommands';
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import UpdateFieldValidationHandler from './cmd/UpdateFieldValidationHandler';

export default class ViewerCommands {
constructor(commandStack, eventBus) {
this._commandStack = commandStack;

eventBus.on('form.init', () => {
this.registerHandlers();
});
}

registerHandlers() {
Object.entries(this.getHandlers()).forEach(([ id, handler ]) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found the usage of CommandStack in the viewer context interesting here. Just to better understand what is happening, why did we add it? Is undo/redo a needed capability?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CC @Skaiir

this._commandStack.registerHandler(id, handler);
});
}

getHandlers() {
return {
'formField.validation.update': UpdateFieldValidationHandler
};
}

updateFieldValidation(field, value) {
const context = {
field,
value
};

this._commandStack.execute('formField.validation.update', context);
}

}

ViewerCommands.$inject = [
'commandStack',
'eventBus'
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { set } from 'min-dash';
import { clone, pathStringify } from '../../../util';

export default class UpdateFieldValidationHandler {

constructor(form, validator) {
this._form = form;
this._validator = validator;
}

execute(context) {
const { field, value } = context;
const { _path } = field;
const { errors } = this._form._getState();

context.oldErrors = clone(errors);

const fieldErrors = this._validator.validateField(field, value);
const updatedErrors = set(errors, [ pathStringify(_path) ], fieldErrors.length ? fieldErrors : undefined);
this._form._setState({ errors: updatedErrors });
}

revert(context) {
this._form._setState({ errors: context.oldErrors });
}
}

UpdateFieldValidationHandler.$inject = [ 'form', 'validator' ];
13 changes: 13 additions & 0 deletions packages/form-js-viewer/src/features/viewerCommands/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import commandModule from 'diagram-js/lib/command';

import ViewerCommands from './ViewerCommands';

export default {
__depends__: [
commandModule
],
__init__: [ 'viewerCommands' ],
viewerCommands: [ 'type', ViewerCommands ]
};

export { ViewerCommands };
19 changes: 18 additions & 1 deletion packages/form-js-viewer/src/render/components/FormField.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext } from 'preact/hooks';
import { useCallback, useContext, useEffect, useMemo } from 'preact/hooks';

import { get } from 'min-dash';

Expand All @@ -24,9 +24,11 @@ export default function FormField(props) {
} = props;

const formFields = useService('formFields'),
viewerCommands = useService('viewerCommands', false),
form = useService('form');

const {
initialData,
data,
errors,
properties
Expand All @@ -44,6 +46,8 @@ export default function FormField(props) {
throw new Error(`cannot render field <${field.type}>`);
}

const initialValue = useMemo(() => get(initialData, field._path), [ initialData, field._path ]);

const value = get(data, field._path);

const fieldErrors = findErrors(errors, field._path);
Expand All @@ -55,6 +59,18 @@ export default function FormField(props) {
properties.disabled || field.disabled || false
);

const onBlur = useCallback(() => {
if (viewerCommands) {
viewerCommands.updateFieldValidation(field, value);
}
}, [ viewerCommands, field, value ]);

useEffect(() => {
if (viewerCommands && initialValue) {
viewerCommands.updateFieldValidation(field, initialValue);
}
}, [ viewerCommands, field, initialValue ]);

pinussilvestrus marked this conversation as resolved.
Show resolved Hide resolved
const hidden = useCondition(field.conditional && field.conditional.hide || null);

if (hidden) {
Expand All @@ -69,6 +85,7 @@ export default function FormField(props) {
disabled={ disabled }
errors={ fieldErrors }
onChange={ disabled || readonly ? noop : onChange }
onBlur={ disabled || readonly ? noop : onBlur }
readonly={ readonly }
value={ value } />
</Element>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export default function Checkbox(props) {
const {
disabled,
errors = [],
onBlur,
field,
readonly,
value = false
Expand Down Expand Up @@ -56,6 +57,7 @@ export default function Checkbox(props) {
id={ prefixId(id, formId) }
type="checkbox"
onChange={ onChange }
onBlur={ onBlur }
aria-describedby={ errorMessageId } />
</Label>
<Description description={ description } />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext } from 'preact/hooks';
import { useContext, useRef } from 'preact/hooks';
import useValuesAsync, { LOAD_STATES } from '../../hooks/useValuesAsync';
import classNames from 'classnames';
import { FormContext } from '../../context';
Expand All @@ -20,6 +20,7 @@ export default function Checklist(props) {
const {
disabled,
errors = [],
onBlur,
field,
readonly,
value = [],
Expand All @@ -32,6 +33,8 @@ export default function Checklist(props) {
validate = {}
} = field;

const outerDivRef = useRef();

const { required } = validate;

const toggleCheckbox = (v) => {
Expand All @@ -50,6 +53,15 @@ export default function Checklist(props) {
});
};

const onCheckboxBlur = (e) => {

if (outerDivRef.current.contains(e.relatedTarget)) {
return;
}

onBlur();
};

const {
state: loadState,
values: options
Expand All @@ -58,7 +70,7 @@ export default function Checklist(props) {
const { formId } = useContext(FormContext);
const errorMessageId = errors.length === 0 ? undefined : `${prefixId(id, formId)}-error-message`;

return <div class={ classNames(formFieldClasses(type, { errors, disabled, readonly })) }>
return <div class={ classNames(formFieldClasses(type, { errors, disabled, readonly })) } ref={ outerDivRef }>
<Label
label={ label }
required={ required } />
Expand All @@ -81,6 +93,7 @@ export default function Checklist(props) {
id={ prefixId(`${id}-${index}`, formId) }
type="checkbox"
onClick={ () => toggleCheckbox(v.value) }
onBlur={ onCheckboxBlur }
aria-describedby={ errorMessageId } />
</Label>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useContext, useMemo, useState, useEffect } from 'preact/hooks';
import { useCallback, useContext, useMemo, useState, useEffect, useRef } from 'preact/hooks';

import classNames from 'classnames';

Expand All @@ -23,6 +23,7 @@ export default function Datetime(props) {
const {
disabled,
errors = [],
onBlur,
field,
onChange,
readonly,
Expand All @@ -44,6 +45,7 @@ export default function Datetime(props) {

const { required } = validate;
const { formId } = useContext(FormContext);
const dateTimeGroupRef = useRef();

const getNullDateTime = () => ({ date: new Date(Date.parse(null)), time: null });

Expand All @@ -56,6 +58,14 @@ export default function Datetime(props) {
const useDatePicker = useMemo(() => subtype === DATETIME_SUBTYPES.DATE || subtype === DATETIME_SUBTYPES.DATETIME, [ subtype ]);
const useTimePicker = useMemo(() => subtype === DATETIME_SUBTYPES.TIME || subtype === DATETIME_SUBTYPES.DATETIME, [ subtype ]);

const onDateTimeBlur = useCallback((e) => {
if (e.relatedTarget && dateTimeGroupRef.current.contains(e.relatedTarget)) {
return;
}

onBlur();
}, [ onBlur ]);

useEffect(() => {

let { date, time } = getNullDateTime();
Expand Down Expand Up @@ -135,6 +145,7 @@ export default function Datetime(props) {
id,
label: dateLabel,
collapseLabelOnEmpty: !timeLabel,
onDateTimeBlur,
formId,
required,
disabled,
Expand All @@ -148,6 +159,7 @@ export default function Datetime(props) {
id,
label: timeLabel,
collapseLabelOnEmpty: !dateLabel,
onDateTimeBlur,
formId,
required,
disabled,
Expand All @@ -160,7 +172,7 @@ export default function Datetime(props) {
};

return <div class={ formFieldClasses(type, { errors: allErrors, disabled, readonly }) }>
<div class={ classNames('fjs-vertical-group') }>
<div class={ classNames('fjs-vertical-group') } ref={ dateTimeGroupRef }>
{ useDatePicker && <Datepicker { ...datePickerProps } /> }
{ useTimePicker && useDatePicker && <div class="fjs-datetime-separator" /> }
{ useTimePicker && <Timepicker { ...timePickerProps } /> }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export default function Numberfield(props) {
const {
disabled,
errors = [],
onBlur,
field,
value,
readonly,
Expand Down Expand Up @@ -191,6 +192,7 @@ export default function Numberfield(props) {
id={ prefixId(id, formId) }
onKeyDown={ onKeyDown }
onKeyPress={ onKeyPress }
onBlur={ onBlur }

// @ts-ignore
onInput={ (e) => setValue(e.target.value) }
Expand Down
Loading
Loading