import * as React from "react"; import { useTranslation } from "react-i18next"; import { Image } from "~/components/Image"; import type { FormFieldItemsWithImage, FormFieldProps } from "../types"; import { FormFieldWrapper } from "./FormFieldWrapper"; type RadioGroupFormFieldProps = Omit< FormFieldProps<"radio-group">, "items" > & { items: FormFieldItemsWithImage; value: V; onChange: (value: V) => void; }; export function RadioGroupFormField({ name, label, bottomText, items, error, onBlur, value, onChange, minLength, }: RadioGroupFormFieldProps) { const id = React.useId(); const itemsWithLabels = useItemsWithResolvedLabels(items); const required = typeof minLength !== "number" || minLength > 0; return (
{itemsWithLabels.map((item) => (
onChange(item.value)} onBlur={() => onBlur?.()} />
))}
); } type CheckboxGroupFormFieldProps = Omit< FormFieldProps<"checkbox-group">, "items" > & { items: FormFieldItemsWithImage; value: V[]; onChange: (value: V[]) => void; }; export function CheckboxGroupFormField({ name, label, bottomText, items, error, onBlur, value, onChange, minLength, }: CheckboxGroupFormFieldProps) { const id = React.useId(); const itemsWithLabels = useItemsWithResolvedLabels(items); const required = typeof minLength !== "number" || minLength > 0; const handleChange = (itemValue: V, checked: boolean) => { if (checked) { onChange([...value, itemValue]); } else { onChange(value.filter((v) => v !== itemValue)); } }; return (
{itemsWithLabels.map((item) => (
handleChange(item.value, e.target.checked)} onClick={() => onBlur?.()} />
))}
); } function useItemsWithResolvedLabels( items: FormFieldItemsWithImage, ) { const { t, i18n } = useTranslation(); return items.map((item) => { const itemLabel = item.label; const resolvedLabel = typeof itemLabel === "function" ? itemLabel(i18n.language) : typeof itemLabel === "string" && itemLabel.includes(":") ? t(itemLabel as never) : String(itemLabel); return { ...item, resolvedLabel, }; }); }