Reorganise components

This commit is contained in:
Timothy Armes
2023-09-14 11:35:30 +02:00
parent bff704077c
commit ac467d7c38
21 changed files with 14 additions and 14 deletions
@@ -0,0 +1,54 @@
import React from "react";
import { format } from "date-fns";
import { enGB, fr } from "date-fns/locale";
import { useLocale } from "next-intl";
import { ReactDatePickerCustomHeaderProps } from "react-datepicker";
import { IoChevronBack, IoChevronForward } from "react-icons/io5";
import { twMerge } from "tailwind-merge";
const chevronClasses = {
chevronRoot: "h-4 w-4 dark:text-white",
chevronClassDisabled: "!text-neutral-500",
};
export const DatePickerCustomHeader = ({
date,
decreaseMonth,
increaseMonth,
prevMonthButtonDisabled,
nextMonthButtonDisabled,
}: ReactDatePickerCustomHeaderProps) => {
// Bit of a hack. inputRef doesn't work because DatePicker doesn't correctly propagate props
const locale = useLocale();
return (
<div className="mb-2 flex !w-full items-center justify-between border-b border-neutral-500 px-6 pb-4">
<button
onClick={decreaseMonth}
disabled={prevMonthButtonDisabled}
className={chevronClasses.chevronRoot}
>
<IoChevronBack
className={twMerge(
chevronClasses.chevronRoot,
prevMonthButtonDisabled && chevronClasses.chevronClassDisabled,
)}
/>
</button>
{format(date, "LLLL yyyy", { locale: locale === "fr" ? fr : enGB })}
<button
onClick={increaseMonth}
disabled={nextMonthButtonDisabled}
className={chevronClasses.chevronRoot}
>
<IoChevronForward
className={twMerge(
chevronClasses.chevronRoot,
nextMonthButtonDisabled && chevronClasses.chevronClassDisabled,
)}
/>
</button>
</div>
);
};
@@ -0,0 +1,65 @@
import React, { forwardRef } from "react";
import InputMask from "react-input-mask";
import { twMerge } from "tailwind-merge";
interface InputProps {
error?: boolean;
className?: string;
inputContainerClass?: string;
inputClass?: string;
mask?: string | (string | RegExp)[];
}
type AllProps = React.DetailedHTMLProps<
React.InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
> &
InputProps;
export const InputDatePicker = forwardRef<HTMLInputElement, AllProps>(
(
{
error,
className,
children,
inputContainerClass,
inputClass,
mask,
...props
},
inputRef,
) => {
return (
<div
className={twMerge(
"flex w-full content-center rounded-lg border p-3 text-sm",
"border-gray-300 bg-gray-50 text-gray-900 shadow-sm",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 ",
!error &&
"focus-within:border-primary-500 focus-within:ring-primary-500 dark:focus-within:border-primary-500 dark:focus-within:ring-primary-500",
error && "!border-orange-700 focus:!border-orange-700",
inputContainerClass,
)}
>
<InputMask
ref={inputRef as any}
mask={mask ?? ""}
className={twMerge(
"w-full border-none bg-transparent text-sm outline-none ring-0 focus:outline-none focus:ring-0 focus:ring-offset-0",
"text-gray-900 dark:text-white",
inputClass,
)}
onKeyDown={(e) => {
if (e.code === "Enter") {
e.stopPropagation();
}
}}
{...props}
/>
</div>
);
},
);
InputDatePicker.displayName = "InputDatePicker";
@@ -0,0 +1 @@
export * from "./InputDatePicker";
+129
View File
@@ -0,0 +1,129 @@
import React, { useRef } from "react";
import { getYear, isValid, parse } from "date-fns";
import fr from "date-fns/locale/fr";
import { get, range } from "lodash";
import { useLocale, useTranslations } from "next-intl";
import DatePicker from "react-datepicker";
import { registerLocale } from "react-datepicker";
import { Controller, useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "../Field";
import { InputDatePicker } from "./components";
import { DatePickerCustomHeader } from "./components/DatePickerCustomHeader";
registerLocale("fr", fr);
type DateFieldProps = FieldProps & {
maxDate?: Date;
minDate?: Date;
dateFormat?: string;
className?: string;
datePickerPopperClass?: string;
required?: boolean;
};
export const DateField = ({
minDate,
maxDate,
dateFormat = "dd/MM/yyyy",
className,
datePickerPopperClass,
name,
...otherFieldProps
}: DateFieldProps) => {
const locale = useLocale();
const at = useTranslations("App");
const min = minDate ? minDate.getFullYear() : 1900;
const inputRef = useRef(null);
const form = useFormContext();
const {
formState: { errors },
} = form;
const hasError = name && !!get(errors, name)?.message;
return (
<Field name={name} {...otherFieldProps}>
<div className={twMerge("relative flex w-full flex-col", className)}>
<Controller
control={form.control}
name={name}
render={({ field }) => (
<DatePicker
locale={locale}
closeOnScroll={true}
placeholderText={at("datePlaceholder")}
portalId="calendar-portal"
dateFormat={dateFormat}
disabledKeyboardNavigation={true}
formatWeekDay={(day: string) => (
<div className="flex h-8 flex-col items-center justify-center">
{day.slice(0, 3)}
</div>
)}
weekDayClassName={() =>
"text-xs h-8 w-8 flex-1 bg-gray-50 text-gray-900 dark:bg-gray-700 dark:text-white"
}
dayClassName={() =>
"text-xs h-8 w-8 flex-1 bg-gray-50 cursor-pointer hover:font-bold text-gray-900 dark:bg-gray-700 dark:text-white"
}
value={field.value}
selected={field.value}
onSelect={field.onChange}
onChange={field.onChange}
onChangeRaw={(e) => {
// Called when the user types in the input
if (e.currentTarget.value) {
const value = e.currentTarget.value;
const date = parse(value, at("dateParseFormat"), new Date());
if (
isValid(date) &&
date.getFullYear() >= min &&
maxDate &&
getYear(maxDate) >= getYear(date)
) {
field.onChange(date);
}
}
}}
popperPlacement="bottom-start"
popperClassName={twMerge(
"z-50 mt-[12px] rounded border",
"border-gray-300 bg-gray-50 text-gray-900",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white",
datePickerPopperClass,
)}
showPopperArrow={false}
calendarClassName={twMerge(
"border-gray-300 bg-gray-50 text-gray-900",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white",
)}
minDate={minDate}
showFullMonthYearPicker
maxDate={maxDate}
renderCustomHeader={(props) => (
<DatePickerCustomHeader {...props} />
)}
customInput={
<InputDatePicker
mask={at("dateMask")}
inputClass="p-0"
className="text-left"
ref={inputRef}
error={!!hasError}
/>
}
/>
)}
/>
</div>
</Field>
);
};
+21
View File
@@ -0,0 +1,21 @@
import { useTranslations } from "next-intl";
type ErrorMessageProps = {
errorMessage: string;
};
export const ErrorMessage = ({ errorMessage }: ErrorMessageProps) => {
const t = useTranslations();
type TranslationKey = Parameters<typeof t>[0];
return errorMessage !== undefined ? (
<div className="mt-2 font-medium text-orange-700">
<p>
{errorMessage.startsWith("FormValidation")
? t(errorMessage as TranslationKey)
: errorMessage}
</p>
</div>
) : null;
};
+68
View File
@@ -0,0 +1,68 @@
import { ReactNode } from "react";
import { get } from "lodash";
import { useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { ErrorMessage } from "./ErrorMessage";
import { Label } from "./Label";
export type FieldProps = {
name: string;
className?: string;
labelClassName?: string;
childrenWrapperClassName?: string;
label?: React.ReactNode;
hideErrorMessage?: boolean;
};
export const Field = (
props: Omit<FieldProps, "name"> & {
required?: boolean;
name?: string;
children: ReactNode;
},
) => {
const {
name,
className,
labelClassName,
childrenWrapperClassName,
label,
children,
required,
hideErrorMessage = false,
} = props;
const form = useFormContext();
const {
formState: { errors },
} = form;
const hasError = name && !!get(errors, name)?.message;
return (
<div className={twMerge("flex w-full flex-col items-start", className)}>
{label ? (
<Label htmlFor={name} required={required} className={labelClassName}>
{label}
</Label>
) : null}
<div
className={twMerge(
"flex w-full",
label && "mt-2",
childrenWrapperClassName,
)}
>
{children}
</div>
{hideErrorMessage || !hasError ? null : (
<ErrorMessage errorMessage={String(get(errors, name)?.message)} />
)}
</div>
);
};
+31
View File
@@ -0,0 +1,31 @@
import { twMerge } from "tailwind-merge";
type LabelProps = React.DetailedHTMLProps<
React.LabelHTMLAttributes<HTMLLabelElement>,
HTMLLabelElement
> & {
required?: boolean;
className?: string;
tooltip?: React.ReactNode;
};
export const Label = ({
required,
className,
children,
tooltip,
...labelProps
}: LabelProps) => {
return (
<label
{...labelProps}
className={twMerge(
"flex items-center text-sm font-medium text-gray-900 dark:text-gray-300",
required && "after:ml-0.5 after:content-['*']",
className,
)}
>
<div>{children}</div>
</label>
);
};
+200
View File
@@ -0,0 +1,200 @@
import { Fragment, useRef } from "react";
import { Listbox, Transition } from "@headlessui/react";
import { useTranslations } from "next-intl";
import { Controller, useFormContext } from "react-hook-form";
import {
IoChevronDown,
IoCloseOutline,
IoSearchOutline,
} from "react-icons/io5";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "./Field";
export type SelectOption = {
value: string;
label: React.ReactNode;
selectedLabel?: React.ReactNode;
disabled?: boolean;
};
type SelectFieldProps = FieldProps & {
required?: boolean;
placeholder?: string;
noOptionsMessage?: string;
options: SelectOption[];
searchable?: boolean;
listboxClassName?: string;
dropdownClassName?: string;
searchValue?: string;
onChangeSearchValue?: (value: string) => void;
onOptionSelected?: (option: SelectOption) => void;
};
export const SelectField = ({
name,
label,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage = false,
required,
placeholder,
noOptionsMessage,
options,
searchable,
searchValue = "",
onChangeSearchValue,
onOptionSelected,
listboxClassName,
dropdownClassName,
}: SelectFieldProps) => {
const at = useTranslations("App");
const form = useFormContext();
// We need to keep track of the selected option to be able to continue to
// display it when the user searches for something else
const curOption = useRef<SelectOption | null>(null);
return (
<Field
{...{
name,
label,
required,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage,
}}
>
<div className="flex w-full flex-col">
<Controller
control={form.control}
name={name}
render={({ field: { onChange, value, name } }) => {
const selectedOption =
curOption.current?.value === value
? curOption.current
: options.find((option) => option.value === value);
return (
<Listbox
value={value ?? null}
name={name}
onChange={(value) => {
curOption.current =
options.find((option) => option.value === value) ?? null;
onChangeSearchValue?.("");
onChange(value);
onOptionSelected?.(curOption.current!);
}}
>
{({ open }) => (
<div className="relative w-full">
<Listbox.Button
className={twMerge(
"group flex w-full items-center justify-between rounded-lg border p-3 text-sm",
"border-gray-300 bg-gray-50 text-gray-900 shadow-sm focus-within:border-primary-500 focus-within:ring-primary-500",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus-within:border-primary-500 dark:focus-within:ring-primary-500",
listboxClassName,
)}
>
<span className="block truncate pr-2 text-gray-900 dark:text-white">
{selectedOption?.selectedLabel ??
selectedOption?.label ??
placeholder ??
at("selectPlaceholder")}
</span>
<span className="pointer-events-none flex items-center pr-2">
<IoChevronDown
className="h-3 w-3 text-gray-900 dark:text-white"
aria-hidden="true"
/>
</span>
</Listbox.Button>
<Transition
as={Fragment}
show={open}
leave="transition ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div
className={twMerge(
"absolute z-10 mt-1 flex w-full flex-col overflow-y-hidden rounded border py-3 text-white focus:outline-none [&>ul]:outline-none",
"border-gray-300 bg-gray-50 text-gray-900",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white",
dropdownClassName,
)}
>
<Listbox.Options className="flex max-h-[180px] flex-1 flex-col justify-stretch">
{searchable && (
<div className="mx-3 mb-4 flex h-[40px] w-auto flex-1 items-center justify-between rounded border px-4 dark:border-neutral-500 dark:bg-neutral-600 focus-within:dark:border-neutral-200">
<IoSearchOutline
width="16px"
className="h-4 w-4 flex-shrink-0 text-gray-900 dark:text-white"
/>
<input
className="w-full flex-1 border-none bg-transparent ring-0 focus:outline-none focus:ring-0 focus:ring-offset-0"
value={searchValue}
onChange={
onChangeSearchValue
? (e) => onChangeSearchValue(e.target.value)
: undefined
}
placeholder={at("searchPlaceholder")}
type="search"
/>
{searchValue.trim() !== "" && (
<button
className="flex h-4 w-4 flex-shrink-0 items-center justify-center"
type="button"
onClick={() => onChangeSearchValue?.("")}
>
<IoCloseOutline className="h-4 w-4 text-gray-900 transition-all duration-200 dark:text-white" />
</button>
)}
</div>
)}
{options.length === 0 ? (
<div className="w-full text-center">
{noOptionsMessage ?? at("noOptionsMessage")}
</div>
) : (
<div className="flex-1 overflow-scroll">
{options.map((option) => (
<Listbox.Option
key={option.value}
value={option.value}
disabled={option.disabled}
className={twMerge(
"w-full px-3 py-2 text-left",
!option.disabled &&
"hover:bg-primary-500 hover:text-white",
option.disabled && "opacity-50",
)}
>
{option.label}
</Listbox.Option>
))}
</div>
)}
</Listbox.Options>
</div>
</Transition>
</div>
)}
</Listbox>
);
}}
/>
</div>
</Field>
);
};
+60
View File
@@ -0,0 +1,60 @@
import React from "react";
import { Switch, SwitchProps } from "@headlessui/react";
import { Controller, useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "./Field";
export const SwitchField = (props: FieldProps & SwitchProps<"button">) => {
const {
name,
label,
disabled,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage,
...rest
} = props;
const form = useFormContext();
return (
<Field
{...{
name,
type: "checkbox",
label,
disabled,
className,
labelClassName,
}}
>
<div className="flex w-full flex-col">
<Controller
control={form.control}
name={name}
render={({ field }) => (
<div className="flex h-[40px] items-center">
<Switch
checked={field.value}
onChange={field.onChange}
className={twMerge(
"relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none",
"ui-not-checked:bg-neutral-300 ui-not-checked:hover:bg-neutral-400",
"ui-not-checked:dark:bg-neutral-500 ui-not-checked:dark:hover:bg-neutral-600",
"ui-checked:bg-primary-500 ui-checked:hover:bg-primary-600",
)}
{...rest}
>
<span className="ui-checked:translate-x-[19px] ui-not-checked:translate-x-[3px] inline-block h-[14px] w-[14px] transform rounded-full bg-white transition-transform" />
</Switch>
</div>
)}
/>
</div>
</Field>
);
};
+88
View File
@@ -0,0 +1,88 @@
import React from "react";
import { get } from "lodash";
import { Controller, useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "./Field";
export const TextAreaField = (
props: FieldProps &
React.HTMLProps<HTMLTextAreaElement> & {
handleChanged?: (props: { name: string }) => void;
startIcon?: React.ReactNode;
},
) => {
const {
name,
label,
required,
disabled,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage = false,
startIcon,
handleChanged,
...rest
} = props;
const form = useFormContext();
const {
formState: { errors },
} = form;
const hasError = !!get(errors, name)?.message;
return (
<Field
{...{
name,
label,
required,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage,
}}
>
<div className="flex w-full flex-col">
<Controller
control={form.control}
name={name}
render={({ field }) => (
<div className="relative">
{startIcon && (
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
{startIcon}
</div>
)}
<textarea
{...form.register(name, {
required,
})}
aria-required={required}
aria-invalid={hasError}
disabled={disabled}
className={twMerge(
"flex w-full content-center rounded-lg border p-3 text-sm",
"border-gray-300 bg-gray-50 text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500",
hasError && "!border-orange-700 focus:!border-orange-700",
disabled && "dark:bg-gray-50",
)}
{...rest}
onChange={(e) => {
field.onChange(e);
}}
value={field.value}
/>
</div>
)}
/>
</div>
</Field>
);
};
+111
View File
@@ -0,0 +1,111 @@
import React from "react";
import { get } from "lodash";
import { Controller, useFormContext } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { Field, FieldProps } from "./Field";
export const TextField = (
props: FieldProps &
React.HTMLProps<HTMLInputElement> & {
handleChanged?: (props: { name: string }) => void;
startIcon?: React.ReactNode;
},
) => {
const {
name,
type = "text",
label,
required,
disabled,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage = false,
startIcon,
handleChanged,
...rest
} = props;
const form = useFormContext();
const {
formState: { errors },
} = form;
const hasError = !!get(errors, name)?.message;
const input = (value: string | number) => {
return typeof value === "number"
? isNaN(value)
? ""
: value.toString()
: value ?? "";
};
const output =
type === "number"
? (e: React.ChangeEvent<HTMLInputElement>) => {
const output = parseFloat(e.target.value);
return isNaN(output) ? 0 : output;
}
: (e: React.ChangeEvent<HTMLInputElement>) => e.target.value;
return (
<Field
{...{
name,
label,
required,
className,
labelClassName,
childrenWrapperClassName,
hideErrorMessage,
}}
>
<div className="flex w-full flex-col">
<Controller
control={form.control}
name={name}
render={({ field }) => (
<div className="relative">
{startIcon && (
<div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
{startIcon}
</div>
)}
<input
type={type}
{...form.register(name, {
valueAsNumber: type === "number",
required,
})}
aria-required={required}
aria-invalid={hasError}
disabled={disabled}
className={twMerge(
"flex w-full content-center rounded-lg border p-3 text-sm",
"border-gray-300 bg-gray-50 text-gray-900 shadow-sm focus:border-primary-500 focus:ring-primary-500",
"dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-primary-500 dark:focus:ring-primary-500",
hasError && "!border-orange-700 focus:!border-orange-700",
disabled && "dark:bg-gray-50",
startIcon && "pl-10",
)}
{...rest}
onChange={(e) => {
field.onChange(output(e));
}}
value={input(field.value)}
onBlur={() => {
if (handleChanged) handleChanged({ name });
}}
/>
</div>
)}
/>
</div>
</Field>
);
};