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 React Hook Form and Zod #1306

Merged
merged 23 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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: 6 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
"@babel/core": "^7.23.2",
"@babel/plugin-syntax-flow": "^7.22.5",
"@babel/plugin-transform-react-jsx": "^7.22.15",
"@hookform/resolvers": "^3.9.0",
"@radix-ui/react-slot": "^1.1.0",
"axios": "^1.5.1",
"classnames": "^2.3.2",
"cmdk": "^0.2.0",
Expand All @@ -42,6 +44,7 @@
"react-cookie": "^6.1.1",
"react-dom": "^18.2.0",
"react-helmet-async": "^1.3.0",
"react-hook-form": "^7.53.0",
"react-loading-skeleton": "^3.3.1",
"react-markdown": "^9.0.0",
"react-modal": "^3.16.1",
Expand All @@ -50,7 +53,9 @@
"react-toastify": "^9.1.3",
"require-from-string": "^2.0.2",
"vite-plugin-svgr": "^4.1.0",
"web-vitals": "^3.5.0"
"web-vitals": "^3.5.0",
"zod": "^3.23.8",
"zod-i18n-map": "^2.27.0"
},
"devDependencies": {
"@iconify/react": "^4.1.1",
Expand Down
7 changes: 7 additions & 0 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,20 @@ import 'react-toastify/dist/ReactToastify.min.css';
// Neccessary import for translations.
import { CommandMenu, UserFeedback, useScrollToTop } from './Components';
import './i18n/i18n';
import { useTranslation } from 'react-i18next';
import { z } from 'zod';
import { makeZodI18nMap } from 'zod-i18n-map';

export function App() {
const goatCounterCode = import.meta.env.VITE_GOATCOUNTER_CODE;
const isDev = import.meta.env.DEV;
const localSetup = isDev ? '{"allow_local": true}' : undefined;
const isDarkTheme = useIsDarkTheme();

// Make form error messages automatically translate
const { t } = useTranslation();
z.setErrorMap(makeZodI18nMap({ t, handlePath: false }));

// Must be called within <BrowserRouter> because it uses hook useLocation().
useGoatCounter();
useScrollToTop();
Expand Down
47 changes: 6 additions & 41 deletions frontend/src/Components/Checkbox/Checkbox.tsx
Original file line number Diff line number Diff line change
@@ -1,56 +1,21 @@
import classNames from 'classnames';
import { useState } from 'react';
import styles from './Checkbox.module.scss';

type Alignment = 'left' | 'right';
import React from 'react';

export type CheckboxProps = {
name?: string;
label?: string;
disabled?: boolean;
checked?: boolean;
onClick?: () => void;
alignment?: Alignment;
className?: string;
onChange?: (value: boolean) => void;
error?: string | boolean;
value?: boolean;
onChange?: (...event: unknown[]) => void;
};

// TODO: Add error handling, eg. display red text when error is set
export function Checkbox({
name,
onClick,
disabled,
checked,
className,
alignment = 'left',
label,
onChange,
}: CheckboxProps) {
const [isChecked, setIsChecked] = useState(checked ?? false);

function handleChange() {
setIsChecked(!isChecked);
if (onChange !== undefined) {
return onChange?.(isChecked);
}
return onClick;
}

export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(({ className, ...props }, ref) => {
return (
<label className={styles.checkbox}>
{alignment == 'left' && label}
<input
className={classNames(styles.checkbox__input, className)}
type="checkbox"
name={name}
onClick={handleChange}
disabled={disabled}
checked={isChecked}
/>
<input type="checkbox" ref={ref} className={classNames(styles.checkbox__input, className)} {...props} />
<div className={styles.checkbox__box}></div>
{alignment == 'right' && label}
</label>
);
}
});
Checkbox.displayName = 'Checkbox';
38 changes: 25 additions & 13 deletions frontend/src/Components/Dropdown/Dropdown.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Icon } from '@iconify/react';
import { default as classNames, default as classnames } from 'classnames';
import { ChangeEvent, ReactElement } from 'react';
import React, { ChangeEvent, ReactElement } from 'react';
import styles from './Dropdown.module.scss';

export type DropDownOption<T> = {
Expand All @@ -21,18 +21,21 @@ export type DropdownProps<T> = {
onChange?: (value?: T) => void;
};

export function Dropdown<T>({
options = [],
defaultValue,
initialValue,
onChange,
className,
classNameSelect,
label,
disabled = false,
disableIcon = false,
error,
}: DropdownProps<T>) {
function DropdownInner<T>(
{
options = [],
defaultValue,
initialValue,
onChange,
className,
classNameSelect,
label,
disabled = false,
disableIcon = false,
error,
}: DropdownProps<T>,
ref: React.Ref<HTMLSelectElement>,
) {
/**
* Handles the raw change event from <option>
* The raw value choice is an index where -1 is reserved for
Expand All @@ -48,10 +51,12 @@ export function Dropdown<T>({
onChange?.(defaultValue?.value ?? undefined);
}
}

return (
<label className={classnames(className, styles.select_wrapper)}>
{label}
<select
ref={ref}
className={classNames(
classNameSelect,
styles.samf_select,
Expand Down Expand Up @@ -79,3 +84,10 @@ export function Dropdown<T>({
</label>
);
}

export const Dropdown = React.forwardRef(DropdownInner) as <T>(
props: DropdownProps<T> & {
ref?: React.Ref<HTMLSelectElement>;
},
) => ReturnType<typeof DropdownInner>;
(Dropdown as React.ForwardRefExoticComponent<unknown>).displayName = 'Dropdown';
134 changes: 134 additions & 0 deletions frontend/src/Components/Forms/Form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { Slot } from '@radix-ui/react-slot';
import * as React from 'react';
import {
Controller,
type ControllerProps,
type FieldPath,
type FieldValues,
FormProvider,
useFormContext,
} from 'react-hook-form';

import styles from './Forms.module.scss';
import classNames from 'classnames';

export const Form = FormProvider;

type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName;
};

const FormFieldContext = React.createContext<FormFieldContextValue>({} as FormFieldContextValue);

export const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
};

export const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();

const fieldState = getFieldState(fieldContext.name, formState);

if (!fieldContext) {
throw new Error('useFormField should be used within <FormField>');
}

const { id } = itemContext;

return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};

type FormItemContextValue = {
id: string;
};

const FormItemContext = React.createContext<FormItemContextValue>({} as FormItemContextValue);

export const FormItem = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ ...props }, ref) => {
const id = React.useId();

return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} {...props} />
</FormItemContext.Provider>
);
});
FormItem.displayName = 'FormItem';

interface FormLabelProps extends React.HTMLAttributes<HTMLLabelElement> {
className?: string;
}

export const FormLabel = React.forwardRef<
React.ElementRef<'label'>,
React.ComponentPropsWithoutRef<'label'> & FormLabelProps
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField();

return (
<label
ref={ref}
className={classNames(styles.label, error && styles.error, className)}
htmlFor={formItemId}
{...props}
/>
);
});
FormLabel.displayName = 'FormLabel';

export const FormControl = React.forwardRef<React.ElementRef<typeof Slot>, React.ComponentPropsWithoutRef<typeof Slot>>(
({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField();

return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={!error ? `${formDescriptionId}` : `${formDescriptionId} ${formMessageId}`}
aria-invalid={!!error}
{...props}
/>
);
},
);
FormControl.displayName = 'FormControl';

export const FormMessage = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(
// eslint-disable-next-line react/prop-types
({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message) : children;

if (!body) {
return null;
}

return (
<p ref={ref} id={formMessageId} className={classNames(styles.error, className)} {...props}>
{body}
</p>
);
},
);
FormMessage.displayName = 'FormMessage';
12 changes: 12 additions & 0 deletions frontend/src/Components/Forms/Forms.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
@import 'src/constants';

@import 'src/mixins';

.error {
color: $red;
}

.label {
margin-bottom: 0;
margin-top: 0.5rem;
}
1 change: 1 addition & 0 deletions frontend/src/Components/Forms/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { Form, FormItem, FormMessage, FormControl, FormLabel, FormField, useFormField } from './Form';
40 changes: 40 additions & 0 deletions frontend/src/Components/Input/Input.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
@import 'src/constants';

@import 'src/mixins';

.input_field {
@include rounded-lighter;
padding: 0.75rem 1rem;
border: 1px solid $grey-35;
margin-top: 0.5em; // Make sure this is the same for all inputs that should be used together
outline: none;
font-weight: initial;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
width: 100%;

&:focus {
border-color: $grey-3;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.1);
outline: 1px solid rgba(0, 0, 0, 0.1);
}
&.error {
border: 1px solid $red;
}

@include theme-dark {
border-color: $grey-0;
&:focus {
border-color: $grey-1;
outline: 1px solid rgba(255, 255, 255, 0.6);
}
}
}

// Hide up and down buttons unless hover/focus
.number_input {
-webkit-appearance: textfield;

&:hover, &:focus {
-moz-appearance: initial;
}
}
20 changes: 20 additions & 0 deletions frontend/src/Components/Input/Input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import * as React from 'react';
import styles from './Input.module.scss';
import classNames from 'classnames';

export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
onChange: (...event: unknown[]) => void;
}

export const Input = React.forwardRef<HTMLInputElement, InputProps>(({ className, type, onChange, ...props }, ref) => {
return (
<input
type={type}
className={classNames(styles.input_field, type === 'number' && styles.number_input, className)}
onChange={(event) => (type === 'number' ? onChange?.(+event.target.value) : onChange?.(event.target.value))}
ref={ref}
{...props}
/>
);
});
Input.displayName = 'Input';
1 change: 1 addition & 0 deletions frontend/src/Components/Input/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { Input, type InputProps } from './Input';
Loading
Loading