"use client"; import { useState, useTransition } from "react"; import { useCollections } from "@/lib/app-context"; import type { Dispatch } from "@/lib/app-state"; import { Icons } from "@/components/icons"; import { addPlaceToCollection, removePlaceFromCollection, } from "@/lib/db/actions"; export function SaveToCollectionSheet({ placeId, onClose, dispatch, }: { placeId: number; onClose: () => void; dispatch: Dispatch; }) { const collections = useCollections(); // Initial membership state derived from server data. const [membership, setMembership] = useState>(() => Object.fromEntries(collections.map((c) => [c.id, c.place_ids.includes(placeId)])), ); const [, startTransition] = useTransition(); const editable = collections.filter((c) => c.my_role !== "viewer"); const toggle = (cid: number) => { const wasIn = !!membership[cid]; setMembership({ ...membership, [cid]: !wasIn }); startTransition(() => { const op = wasIn ? removePlaceFromCollection(cid, placeId) : addPlaceToCollection(cid, placeId); op.catch(() => { setMembership({ ...membership, [cid]: wasIn }); dispatch({ type: "TOAST", value: "Lưu thất bại" }); }); }); }; return ( <>
Lưu vào bộ sưu tập
{editable.length === 0 ? (
Bạn chưa có bộ sưu tập nào có quyền chỉnh sửa. Tạo bộ sưu tập trước từ tab "Bộ sưu tập".
) : ( editable.map((c) => { const inIt = !!membership[c.id]; const Icon = c.type === "trip" ? Icons.Plane : Icons.Folder; return ( ); }) )}
); }