import clsx from "clsx"; import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import HintTooltip from "../tooltips/HintTooltip"; import { Colors } from "~/application/enums/shared/Colors"; import { CheckboxCard } from "~/ui/components/CheckboxCard"; type CheckboxCardValue = string | number; function compareCheckboxCardValue(a: CheckboxCardValue, b: CheckboxCardValue) { const aKey = `${typeof a}:${String(a)}`; const bKey = `${typeof b}:${String(b)}`; return aKey.localeCompare(bKey); } function hasSameCheckboxCardValues(a: CheckboxCardValue[] | undefined, b: CheckboxCardValue[] | undefined) { if (a === b) { return true; } if (!a || !b || a.length !== b.length) { return false; } const sortedA = [...a].sort(compareCheckboxCardValue); const sortedB = [...b].sort(compareCheckboxCardValue); return sortedA.every((value, index) => Object.is(value, sortedB[index])); } export default function InputCheckboxCards({ title, name, options, value, onChange, selectAndClearAll = false, disabled, required, help, hint, columns, display, }: { title?: string; name?: string; options: { name: string; value: CheckboxCardValue; color?: Colors; disabled?: boolean }[]; value?: CheckboxCardValue[]; onChange?: (value: CheckboxCardValue[]) => void; selectAndClearAll?: boolean; disabled?: boolean; required?: boolean; help?: string; hint?: React.ReactNode; columns?: number; display?: "name" | "value" | "nameAndValue"; }) { const { t } = useTranslation(); const [selected, setSelected] = useState(() => (value ? [...value] : [])); const [displayType, setDisplayType] = useState<"name" | "value" | "nameAndValue">("name"); useEffect(() => { if (display) { setDisplayType(display); } else { const hasNames = options.some((item) => item.name); if (!hasNames) { setDisplayType("value"); } else { const namesAreDifferent = options.some((item) => item.name !== item.value.toString()); if (namesAreDifferent) { setDisplayType("nameAndValue"); } else { setDisplayType("name"); } } } }, [display, options]); useEffect(() => { if (value && !hasSameCheckboxCardValues(selected, value)) { setSelected([...value]); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]); useEffect(() => { if (onChange && !hasSameCheckboxCardValues(selected, value)) { onChange(selected); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [selected]); function isChecked(value: CheckboxCardValue) { return selected.includes(value); } return (
{/* selected: {JSON.stringify(selected)} */}
{title && ( )}
{selectAndClearAll && (
{selected.length !== options.length && ( )} {selected.length > 0 && ( )}
)}
); }