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

Implement multiple #46

Closed
wants to merge 5 commits into from
Closed
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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@
},
"dependencies": {
"clsx": "^1.2.1",
"formik": "^2.2.9"
"formik": "^2.2.9",
"lodash": "^4.17.21"
},
"resolutions": {
"react-formio/formiojs": "~4.13.0"
Expand Down
2 changes: 1 addition & 1 deletion src/components/formio/textfield/textfield.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export const TextField: React.FC<ITextFieldProps> = ({callbacks, component, valu
{..._callbacks}
/>

{!pristineState && component.showCharCount && <CharCount value={value} />}
{!pristineState && component.showCharCount && value && <CharCount value={value} />}
{component.description && <Description description={component.description} />}
{!pristineState && errors?.length > 0 && <Errors componentId={componentId} errors={errors} />}
</Component>
Expand Down
7 changes: 4 additions & 3 deletions src/components/utils/errors/errors.component.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import {ValidationError} from '@lib/validation';
import clsx from 'clsx';
import React from 'react';

export interface IErrorsProps {
componentId: string;
errors: string[];
errors: ValidationError[];
}

/**
Expand All @@ -16,11 +17,11 @@ export const Errors: React.FC<IErrorsProps> = ({componentId, errors}) => {

return (
<ul className={className} aria-describedby={componentId}>
{errors?.map((error: string, index: number) => {
{errors?.map((error, index: number) => {
return (
<li key={index} className={listItemClassName}>
<label className={labelClassName} htmlFor={componentId} role="alert">
{error}
{error.message}
</label>
</li>
);
Expand Down
6 changes: 5 additions & 1 deletion src/components/utils/errors/errors.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ export default meta;

export const errors: ComponentStory<typeof Errors> = args => <Errors {...args} />;
errors.args = {
errors: ['Postcode is required', 'Postcode does not match the pattern ^\\d{4}\\s?[a-zA-Z]{2}$'],
// errors: [{message: 'Postcode is required'}, {message: 'Postcode does not match the pattern ^\\d{4}\\s?[a-zA-Z]{2}$'}],
errors: [
{name: 'required', message: 'Postcode is required'},
{name: 'pattern', message: 'Postcode does not match the pattern ^\\d{4}\\s?[a-zA-Z]{2}$'},
],
};
errors.play = async ({canvasElement}) => {
const canvas = within(canvasElement);
Expand Down
1 change: 1 addition & 0 deletions src/containers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './multiple';
1 change: 1 addition & 0 deletions src/containers/multiple/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './multiple.container';
84 changes: 84 additions & 0 deletions src/containers/multiple/multiple.container.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import {Component, Description, Label} from '@components';
import {IRenderable, RenderComponent} from '@lib/renderer';
import {IComponentProps, Value, Values} from '@types';
import {ArrayHelpers, FieldArray} from 'formik';
import {ComponentSchema} from 'formiojs';
import React from 'react';

export interface IMultipleComponent extends ComponentSchema {
key: string;
type: string;
}

export interface IMultipleProps extends IComponentProps {
component: IMultipleComponent;
value: Values;
}

/**
* Implements `multiple: true` behaviour.
*
* Provide a thin wrapper around a component with controls for adding multiple instances. Utilizes
* <RenderComponent/> to render individual instances.
*/
export const Multiple: React.FC<IMultipleProps> = props => {
const {component, form, path, value = []} = props; // FIXME: Awaits future pr.

/** Renders individual components utilizing <RenderComponent/>. */
const renderComponent = (value: Value, index: number, remove: ArrayHelpers['remove']) => {
// Clone and adjust component to fit nested needs.
const renderable: IRenderable = {
...structuredClone(component),
key: `${path}.${index}`, // Trigger Formik array values.
multiple: false, // Handled by <Multiple/>
description: '', // One description rendered for all components.
label: '', // One label rendered for all components.
};

return (
<tr key={index}>
<td>
<RenderComponent
component={renderable}
form={form}
path={`${path}.${index}`}
value={value}
/>
</td>
<td>
<button type="button" aria-controls={renderable.key} onClick={() => remove(index)}>
Remove item
</button>
</td>
</tr>
);
};

return (
<Component {...props}>
{props.component.label && (
<Label label={props.component.label} componentId={props.component.key as string} />
)}
<FieldArray
name={component.key}
render={({push, remove}) => (
<table>
<tbody>
{value.map((value: Value, index: number) => renderComponent(value, index, remove))}
</tbody>
<tfoot>
<tr>
<td>
<button type="button" onClick={() => push(component.defaultValue || null)}>
Add another
</button>
</td>
</tr>
</tfoot>
</table>
)}
/>
{props.component.description && <Description description={props.component.description} />}
</Component>
);
};
114 changes: 114 additions & 0 deletions src/containers/multiple/multiple.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import {DEFAULT_RENDER_CONFIGURATION, RenderForm} from '@lib/renderer';
import {expect} from '@storybook/jest';
import type {ComponentStory, Meta} from '@storybook/react';
import {userEvent, waitFor, within} from '@storybook/testing-library';

import {Multiple} from './multiple.container';

const meta: Meta<typeof Multiple> = {
title: 'Containers / Multiple',
component: Multiple,
decorators: [],
parameters: {},
};
export default meta;

export const multipleTextfields: ComponentStory<typeof RenderForm> = args => (
<RenderForm {...args} />
);
multipleTextfields.args = {
configuration: DEFAULT_RENDER_CONFIGURATION,
form: {
display: 'form',
components: [
{
type: 'textfield',
key: 'multiple-inputs',
description: 'Array of strings instead of a single string value',
label: 'Multiple inputs',
multiple: true,
showCharCount: true,
validate: {
required: true,
maxLength: 3,
minLength: 1,
},
},
],
},
initialValues: {
'multiple-inputs': ['first value'],
},
};
multipleTextfields.play = async ({canvasElement}) => {
const canvas = within(canvasElement);

// check that new items can be added
await userEvent.click(canvas.getByRole('button', {name: 'Add another'}));
const input1 = await canvas.getAllByRole('textbox')[0];
expect(input1).toHaveDisplayValue('first value');
await userEvent.clear(input1);
await userEvent.type(input1, 'Foo');
expect(input1).toHaveDisplayValue('Foo');

const input2 = await canvas.getAllByRole('textbox')[1];
expect(input2).toHaveDisplayValue('');

// the label & description should be rendered only once, even with > 1 inputs
expect(canvas.queryAllByText('Multiple inputs')).toHaveLength(1);
expect(canvas.queryAllByText('Array of strings instead of a single string value')).toHaveLength(
1
);

// finally, it should be possible delete rows again
const removeButtons = await canvas.findAllByRole('button', {name: 'Remove item'});
expect(removeButtons).toHaveLength(2);
await userEvent.click(removeButtons[0]);
expect(await canvas.getAllByRole('textbox')[0]).toHaveDisplayValue('');
expect(await canvas.getAllByRole('textbox')).toHaveLength(1);
};

export const multipleTextfieldsWithValidation: ComponentStory<typeof RenderForm> = args => (
<RenderForm {...args} />
);
multipleTextfieldsWithValidation.args = {
configuration: DEFAULT_RENDER_CONFIGURATION,
form: {
display: 'form',
components: [
{
type: 'textfield',
key: 'multiple-inputs',
description: 'Array of strings instead of a single string value',
label: 'Multiple inputs',
multiple: true,
showCharCount: true,
validate: {
required: true,
},
},
],
},
initialValues: {
'multiple-inputs': ['first value'],
},
};
multipleTextfieldsWithValidation.play = async ({canvasElement}) => {
const canvas = within(canvasElement);

// check that new items can be added
await userEvent.click(canvas.getByRole('button', {name: 'Add another'}));
const input1 = await canvas.getAllByRole('textbox')[0];
const input2 = await canvas.getAllByRole('textbox')[1];

await userEvent.type(input1, 'foo', {delay: 300});
await userEvent.type(input2, 'bar', {delay: 300});

await userEvent.clear(input1);
expect(await canvas.findAllByText('Multiple inputs is required')).toHaveLength(1);

await userEvent.clear(input2);
waitFor(async () => {
expect(await canvas.findAllByText('Multiple inputs is required')).toHaveLength(2);
});
};
Loading