import { t } from "@lingui/core/macro"; import { HiMiniPlus } from "react-icons/hi2"; import Badge from "~/components/Badge"; import CheckboxDropdown from "~/components/CheckboxDropdown"; import { useModal } from "~/providers/modal"; import { usePopup } from "~/providers/popup"; import { api } from "~/utils/api"; interface LabelSelectorProps { cardPublicId: string; labels: { key: string; value: string; selected: boolean; leftIcon: React.ReactNode; }[]; isLoading: boolean; } export default function LabelSelector({ cardPublicId, labels, isLoading, }: LabelSelectorProps) { const utils = api.useUtils(); const { openModal } = useModal(); const { showPopup } = usePopup(); const addOrRemoveLabel = api.card.addOrRemoveLabel.useMutation({ onMutate: async (update) => { await utils.card.byId.cancel(); const previousCard = utils.card.byId.getData({ cardPublicId }); utils.card.byId.setData({ cardPublicId }, (oldCard) => { if (!oldCard) return oldCard; const hasLabel = oldCard.labels.some( (label) => label.publicId === update.labelPublicId, ); const labelToAdd = oldCard.labels.find( (label) => label.publicId === update.labelPublicId, ); const updatedLabels = hasLabel ? oldCard.labels.filter( (label) => label.publicId !== update.labelPublicId, ) : [ ...oldCard.labels, { publicId: update.labelPublicId, name: labelToAdd?.name ?? "", colourCode: labelToAdd?.colourCode ?? "", }, ]; return { ...oldCard, labels: updatedLabels, }; }); return { previousCard }; }, onError: (_error, _newList, context) => { utils.card.byId.setData({ cardPublicId }, context?.previousCard); showPopup({ header: t`Unable to update labels`, message: t`Please try again later, or contact customer support.`, icon: "error", }); }, onSettled: async () => { await utils.card.byId.invalidate({ cardPublicId }); }, }); const selectedLabels = labels.filter((label) => label.selected); return ( <> {isLoading ? (
) : ( { addOrRemoveLabel.mutate({ cardPublicId, labelPublicId: label.key }); }} handleEdit={(labelPublicId) => openModal("EDIT_LABEL", labelPublicId)} handleCreate={() => openModal("NEW_LABEL")} createNewItemLabel={t`Create new label`} asChild > {selectedLabels.length ? (
{selectedLabels.map((label) => ( ))} } />
) : (
{t`Add label`}
)}
)} ); }