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

Add textarea component #58

Merged
merged 5 commits into from
Nov 22, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
75 changes: 75 additions & 0 deletions src/components/ComponentConfiguration.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,81 @@ export const NumberField: Story = {
},
};

export const Textarea: Story = {
render: Template,
name: 'type: textarea',

args: {
component: {
id: 'wekruya',
type: 'textarea',
key: 'textarea',
label: 'A textarea field',
autoExpand: false,
rows: 3,
validate: {
required: false,
},
},

builderInfo: {
title: 'Textarea',
group: 'basic',
icon: 'hashtag',
schema: {placeholder: ''},
weight: 30,
},
},

play: async ({canvasElement, args}) => {
const canvas = within(canvasElement);

await expect(canvas.getByLabelText('Label')).toHaveValue('A textarea field');
await waitFor(async () => {
await expect(canvas.getByLabelText('Property Name')).toHaveValue('aTextareaField');
});
await expect(canvas.getByLabelText('Description')).toHaveValue('');
await expect(canvas.getByLabelText('Tooltip')).toHaveValue('');
await expect(canvas.getByLabelText('Show in summary')).toBeChecked();
await expect(canvas.getByLabelText('Show in email')).not.toBeChecked();
await expect(canvas.getByLabelText('Show in PDF')).toBeChecked();

// ensure that changing fields in the edit form properly update the preview
const preview = within(canvas.getByTestId('componentPreview'));

await userEvent.clear(canvas.getByLabelText('Label'));
await userEvent.type(canvas.getByLabelText('Label'), 'Updated preview label');
expect(await preview.findByText('Updated preview label'));

const previewInput = preview.getByLabelText('Updated preview label');
await expect(previewInput).toHaveDisplayValue('');

// Ensure that the manually entered key is kept instead of derived from the label,
// even when key/label components are not mounted.
const keyInput = canvas.getByLabelText('Property Name');
// fireEvent is deliberate, as userEvent.clear + userEvent.type briefly makes the field
// not have any value, which triggers the generate-key-from-label behaviour.
fireEvent.change(keyInput, {target: {value: 'customKey'}});
await userEvent.click(canvas.getByRole('tab', {name: 'Basic'}));
await userEvent.clear(canvas.getByLabelText('Label'));
await userEvent.type(canvas.getByLabelText('Label'), 'Other label', {delay: 50});
await expect(canvas.getByLabelText('Property Name')).toHaveDisplayValue('customKey');
// check that toggling the 'multiple' checkbox properly updates the preview and default
// value field. We use fireEvent because firefox borks on userEvent.click, see:
// https://github.com/testing-library/user-event/issues/1149
fireEvent.click(canvas.getByLabelText<HTMLInputElement>('Multiple values'));
await userEvent.click(preview.getByRole('button', {name: 'Add another'}));
await expect(preview.getByTestId('input-customKey[0]')).toHaveDisplayValue('');
// test for the default value inputs -> these don't have accessible labels/names :(
const addButtons = canvas.getAllByRole('button', {name: 'Add another'});
await userEvent.click(addButtons[0]);
expect(await canvas.findByTestId('input-defaultValue[0]'));

await userEvent.click(canvas.getByRole('button', {name: 'Save'}));
expect(args.onSubmit).toHaveBeenCalled();
},
};

export const DateField: Story = {
render: Template,
name: 'type: date',
Expand Down
11 changes: 10 additions & 1 deletion src/components/formio/textarea.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import clsx from 'clsx';
import {Field, useFormikContext} from 'formik';
import {useContext, useRef} from 'react';
import {useContext, useLayoutEffect, useRef} from 'react';

import {RenderContext} from '@/context';
import CharCount from '@/utils/charcount';
Expand All @@ -17,6 +17,7 @@ export interface TextAreaProps {
tooltip?: string;
description?: React.ReactNode;
showCharCount?: boolean;
autoExpand?: boolean;
onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
}

Expand All @@ -27,6 +28,7 @@ export const TextArea: React.FC<JSX.IntrinsicElements['textarea'] & TextAreaProp
tooltip = '',
description = '',
showCharCount = false,
autoExpand = false,
onChange,
...props
}) => {
Expand All @@ -37,6 +39,13 @@ export const TextArea: React.FC<JSX.IntrinsicElements['textarea'] & TextAreaProp
const inputRef = useRef<HTMLInputElement>(null);
const {bareInput} = useContext(RenderContext);

useLayoutEffect(() => {
if (autoExpand && inputRef.current) {
inputRef.current.style.height = 'inherit';
inputRef.current.style.height = `${inputRef.current.scrollHeight}px`;
}
}, [value]);
Viicos marked this conversation as resolved.
Show resolved Hide resolved

const htmlId = `editform-${name}`;
if (value === undefined && props.value === undefined) {
props = {...props, value: ''};
Expand Down
2 changes: 2 additions & 0 deletions src/registry/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import NumberField from './number';
import PhoneNumber from './phonenumber';
import Postcode from './postcode';
import Selectboxes from './selectboxes';
import Textarea from './textarea';
import TextField from './textfield';
import TimeField from './time';
import {Registry, RegistryEntry} from './types';
Expand All @@ -33,6 +34,7 @@ export const getRegistryEntry = <S extends AnyComponentSchema | FallbackSchema>(
const REGISTRY: Registry = {
textfield: TextField,
email: Email,
textarea: Textarea,
number: NumberField,
date: DateField,
datetime: DateTimeField,
Expand Down
31 changes: 31 additions & 0 deletions src/registry/textarea/edit-validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {IntlShape} from 'react-intl';
import {z} from 'zod';

import {buildCommonSchema} from '@/registry/validation';

const textareaSchema = z.string().optional();

// case for when component.multiple=false
const singleValueSchema = z
.object({multiple: z.literal(false)})
.and(z.object({defaultValue: textareaSchema}));

// case for when component.multiple=true
const multipleValueSchema = z
.object({multiple: z.literal(true)})
.and(z.object({defaultValue: textareaSchema.array()}));

// Omit `autoExpand` as it will be set in the UI via a checkbox
const textareaSpecific = z.object({
validate: z.object({
maxLength: z.number().int().gte(1).optional(),
}),
rows: z.number().int().gte(1),
sergei-maertens marked this conversation as resolved.
Show resolved Hide resolved
});

const defaultValueSchema = singleValueSchema.or(multipleValueSchema);

const schema = (intl: IntlShape) =>
buildCommonSchema(intl).and(textareaSpecific).and(defaultValueSchema);

export default schema;
Loading