Skip to content
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
7 changes: 5 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -132,5 +132,8 @@ dist
# Storybook
storybook-static

#VScode
.vscode
# VScode
.vscode

# Local Scripts
local/
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
"zod": "^3.23.6"
},
"dependencies": {
"@douglasneuroinformatics/libjs": "^2.7.0",
"@douglasneuroinformatics/libjs": "^2.8.0",
"@douglasneuroinformatics/libui-form-types": "^0.11.0",
"@radix-ui/react-accordion": "^1.2.3",
"@radix-ui/react-alert-dialog": "^1.1.6",
Expand Down
20 changes: 15 additions & 5 deletions pnpm-lock.yaml

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

2 changes: 1 addition & 1 deletion src/components/Button/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const BUTTON_ICON_SIZE = {
};

export const buttonVariants = cva(
'flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50',
'flex items-center justify-center whitespace-nowrap cursor-pointer rounded-md text-sm font-medium transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50',
{
defaultVariants: {
size: 'md',
Expand Down
2 changes: 1 addition & 1 deletion src/components/Dialog/DialogContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const DialogContent = forwardRef<
<DialogOverlay />
<Content
className={cn(
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border p-6 shadow-lg duration-200 sm:rounded-lg',
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border p-6 shadow-lg duration-200 sm:rounded-lg',
className
)}
ref={ref}
Expand Down
2 changes: 1 addition & 1 deletion src/components/Dialog/DialogOverlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const DialogOverlay = forwardRef<
return (
<Overlay
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80 duration-200',
className
)}
ref={ref}
Expand Down
14 changes: 14 additions & 0 deletions src/components/ErrorFallback/ErrorFallback.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';

import { ErrorFallback } from './ErrorFallback';

const TEST_ID = 'error-fallback';

describe('ErrorFallback', () => {
it('should render', () => {
const error = new Error('Something went wrong');
render(<ErrorFallback error={error} />);
expect(screen.getByTestId(TEST_ID)).toBeInTheDocument();
});
});
9 changes: 6 additions & 3 deletions src/components/ErrorFallback/ErrorFallback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ export const ErrorFallback = ({ error }: ErrorFallbackProps) => {
}, [error]);

return (
<div className="flex min-h-screen flex-col items-center justify-center gap-1 p-3 text-center">
<h1 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">Unexpected Error</h1>
<div
className="flex min-h-screen flex-col items-center justify-center gap-1 p-3 text-center"
data-testid="error-fallback"
>
<h1 className="text-muted-foreground text-sm font-semibold tracking-wide uppercase">Unexpected Error</h1>
<h3 className="text-3xl font-extrabold tracking-tight sm:text-4xl md:text-5xl">Something Went Wrong</h3>
<p className="mt-2 max-w-prose text-sm text-muted-foreground sm:text-base">
<p className="text-muted-foreground mt-2 max-w-prose text-sm sm:text-base">
We apologize for the inconvenience. Please contact us for further assistance.
</p>
<div className="mt-6">
Expand Down
8 changes: 5 additions & 3 deletions src/components/Form/ErrorMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import * as React from 'react';

import { CircleAlertIcon } from 'lucide-react';

export const ErrorMessage: React.FC<{ error?: null | string[] }> = ({ error }) => {
import { cn } from '@/utils';

export const ErrorMessage: React.FC<{ className?: string; error?: null | string[] }> = ({ className, error }) => {
return error ? (
<div className="space-y-1.5">
{error.map((message) => (
<div className="flex w-full items-center text-sm font-medium text-destructive" key={message}>
<div className={cn('text-destructive flex w-full items-center text-sm font-medium', className)} key={message}>
<CircleAlertIcon className="mr-1" style={{ strokeWidth: '2px' }} />
<span>{message}</span>
<span data-testid="error-message-text">{message}</span>
</div>
)) ?? null}
</div>
Expand Down
24 changes: 24 additions & 0 deletions src/components/Form/Form.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -530,3 +530,27 @@ export const WithSuspend: StoryObj<typeof Form<z.ZodType<FormTypes.Data>, { dela
})
}
};

export const WithError: StoryObj<typeof Form> = {
args: {
content: {
name: {
kind: 'string',
label: 'Name',
variant: 'input'
}
},
beforeSubmit: (data) => {
if (data.name === 'Winston') {
return { success: true };
}
return { success: false, errorMessage: "Name must be 'Winston'" };
},
onSubmit: () => {
alert('Success!');
},
validationSchema: $SimpleExampleFormData.extend({
name: z.string().min(3)
})
}
};
65 changes: 65 additions & 0 deletions src/components/Form/Form.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Mock } from 'vitest';
import { z } from 'zod';

import { Form } from './Form';
Expand Down Expand Up @@ -114,4 +115,68 @@ describe('Form', () => {
expect(onSubmit.mock.lastCall?.[0].b).toBeUndefined();
});
});

describe('custom beforeSubmit error', () => {
let beforeSubmit: Mock;

beforeEach(() => {
beforeSubmit = vi.fn();
render(
<Form
beforeSubmit={beforeSubmit}
content={{
value: {
kind: 'number',
label: 'Value',
variant: 'input'
}
}}
data-testid={testid}
validationSchema={z.object({
value: z.number({ message: 'Please enter a number' })
})}
onError={onError}
onSubmit={onSubmit}
/>
);
});

afterEach(() => {
vi.clearAllMocks();
});

it('should render', () => {
expect(screen.getByTestId(testid)).toBeInTheDocument();
});

it('should not allow submitting the form with a zod error', async () => {
fireEvent.submit(screen.getByTestId(testid));
await waitFor(() =>
expect(screen.getAllByTestId('error-message-text').map((e) => e.innerHTML)).toMatchObject([
'Please enter a number'
])
);
expect(beforeSubmit).not.toHaveBeenCalled();
expect(onSubmit).not.toHaveBeenCalled();
});

it('should not allow submitting the form with the beforeSubmit error', async () => {
beforeSubmit.mockResolvedValueOnce({ errorMessage: 'Invalid!', success: false });
const field: HTMLInputElement = screen.getByLabelText('Value');
await userEvent.type(field, '-1');
fireEvent.submit(screen.getByTestId(testid));
await waitFor(() =>
expect(screen.getAllByTestId('error-message-text').map((e) => e.innerHTML)).toMatchObject(['Invalid!'])
);
expect(onSubmit).not.toHaveBeenCalled();
});

it('should allow submitting the form if beforeSubmit returns true', async () => {
beforeSubmit.mockResolvedValueOnce({ success: true });
const field: HTMLInputElement = screen.getByLabelText('Value');
await userEvent.type(field, '-1');
fireEvent.submit(screen.getByTestId(testid));
await waitFor(() => expect(onSubmit).toHaveBeenCalledOnce());
});
});
});
28 changes: 23 additions & 5 deletions src/components/Form/Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,13 @@ type FormProps<TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<T
left?: React.ReactNode;
right?: React.ReactNode;
};
beforeSubmit?: (data: NoInfer<TData>) => Promisable<{ errorMessage: string; success: false } | { success: true }>;
className?: string;
content: FormContent<TData>;
customStyles?: {
resetBtn?: string;
submitBtn?: string;
};
fieldsFooter?: React.ReactNode;
id?: string;
initialValues?: PartialNullableFormDataType<NoInfer<TData>>;
Expand All @@ -47,8 +52,10 @@ type FormProps<TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<T

const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TSchema> = z.TypeOf<TSchema>>({
additionalButtons,
beforeSubmit,
className,
content,
customStyles,
fieldsFooter,
id,
initialValues,
Expand All @@ -73,6 +80,7 @@ const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TS

const handleError = (error: z.ZodError<TData>) => {
const fieldErrors: FormErrors<TData> = {};
const rootErrors: string[] = [];
for (const issue of error.issues) {
if (issue.path.length > 0) {
const current = get(fieldErrors, issue.path) as string[] | undefined;
Expand All @@ -82,10 +90,11 @@ const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TS
set(fieldErrors, issue.path, [issue.message]);
}
} else {
setRootErrors((prevErrors) => [...prevErrors, issue.message]);
rootErrors.push(issue.message);
}
}
setErrors(fieldErrors);
setRootErrors(rootErrors);
if (onError) {
onError(error);
}
Expand All @@ -107,6 +116,15 @@ const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TS
handleError(result.error);
return;
}
if (beforeSubmit) {
const beforeSubmitResult = await beforeSubmit(result.data);
if (!beforeSubmitResult.success) {
setErrors({});
setRootErrors([beforeSubmitResult.errorMessage]);
return;
}
}

try {
setIsSubmitting(true);
await Promise.all([
Expand Down Expand Up @@ -164,7 +182,7 @@ const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TS
</Heading>
)}
{fieldGroup.description && (
<p className="text-sm italic leading-tight text-muted-foreground">{fieldGroup.description}</p>
<p className="text-muted-foreground text-sm leading-tight italic">{fieldGroup.description}</p>
)}
</div>
<FieldsComponent
Expand All @@ -188,13 +206,14 @@ const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TS
values={values}
/>
)}
{Boolean(rootErrors.length) && <ErrorMessage className="-mt-3" error={rootErrors} />}
{fieldsFooter}
<div className="flex w-full gap-3">
{additionalButtons?.left}
{/** Note - aria-label is used for testing in downstream packages */}
<Button
aria-label="Submit"
className="flex w-full items-center justify-center gap-2"
className={cn('flex w-full items-center justify-center gap-2', customStyles?.submitBtn)}
disabled={readOnly || isSuspended}
type="submit"
variant="primary"
Expand All @@ -218,7 +237,7 @@ const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TS
{resetBtn && (
<Button
aria-label="Reset"
className="block w-full"
className={cn('block w-full', customStyles?.resetBtn)}
disabled={readOnly}
type="button"
variant="secondary"
Expand All @@ -229,7 +248,6 @@ const Form = <TSchema extends z.ZodType<FormDataType>, TData extends z.TypeOf<TS
)}
{additionalButtons?.right}
</div>
{Boolean(rootErrors.length) && <ErrorMessage error={rootErrors} />}
</form>
);
};
Expand Down
6 changes: 4 additions & 2 deletions src/components/Form/NumberField/NumberFieldInput.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useId, useRef, useState } from 'react';

import { parseNumber } from '@douglasneuroinformatics/libjs';
import type { NumberFormField } from '@douglasneuroinformatics/libui-form-types';
Expand Down Expand Up @@ -27,6 +27,7 @@ export const NumberFieldInput = ({
setValue,
value
}: NumberFieldInputProps) => {
const id = useId();
const [inputValue, setInputValue] = useState(value?.toString() ?? '');
const valueRef = useRef<number | undefined>(value);

Expand Down Expand Up @@ -65,11 +66,12 @@ export const NumberFieldInput = ({
return (
<FieldGroup name={name}>
<FieldGroup.Row>
<Label>{label}</Label>
<Label htmlFor={id}>{label}</Label>
<FieldGroup.Description description={description} />
</FieldGroup.Row>
<Input
disabled={disabled || readOnly}
id={id}
max={max}
min={min}
name={name}
Expand Down
Loading