import type { ListItem } from '@superlist/shared' import { queryOptions, useMutation, useMutationState, useQuery, useQueryClient, } from '@tanstack/react-query' import { useSyncExternalStore } from 'react' import { toast } from 'sonner' import { ApiError, apiFetch } from '@/lib/api-client' import { DELETE_UNDO_MS, getPendingDeletions, scheduleDeletion, subscribePendingDeletions, } from '@/lib/pending-deletions' export const itemsQueryOptions = (listId: string) => queryOptions({ queryKey: ['lists', listId, 'items'], queryFn: () => apiFetch(`/lists/${listId}/items`), }) export function useItems(listId: string) { return useQuery(itemsQueryOptions(listId)) } /** Prefix of the temporary ids given to items that are still being created. */ const OPTIMISTIC_ID_PREFIX = 'optimistic-' /** Whether the item is a placeholder whose `POST` has not been answered yet. */ export function isOptimisticItem(item: ListItem): boolean { return item.id.startsWith(OPTIMISTIC_ID_PREFIX) } export function useCreateItem(listId: string) { const queryClient = useQueryClient() const { queryKey } = itemsQueryOptions(listId) return useMutation({ mutationFn: (input: { name: string; quantity?: string; notes?: string }) => apiFetch(`/lists/${listId}/items`, { method: 'POST', body: JSON.stringify(input), }), // The item shows up right away; the POST response then swaps the placeholder // for the real row, so no refetch of the whole list is needed (other members // still get it through the SSE stream). onMutate: async (input) => { await queryClient.cancelQueries({ queryKey }) const now = new Date().toISOString() const optimistic: ListItem = { id: `${OPTIMISTIC_ID_PREFIX}${crypto.randomUUID()}`, listId, name: input.name.trim(), completed: false, boughtAt: null, quantity: input.quantity?.trim() || null, notes: input.notes?.trim() || null, order: 0, createdAt: now, updatedAt: now, } queryClient.setQueryData(queryKey, (items) => items && [...items, optimistic]) return { optimisticId: optimistic.id } }, onSuccess: (created, _input, context) => { queryClient.setQueryData(queryKey, (items) => items?.map((item) => (item.id === context.optimisticId ? created : item)), ) }, // Only this placeholder is removed, so other in-flight additions survive. onError: (_error, _input, context) => { queryClient.setQueryData(queryKey, (items) => items?.filter((item) => item.id !== context?.optimisticId), ) }, }) } type UpdateItemInput = { itemId: string /** New name; omitted to leave it untouched. */ name?: string /** New bought state; omitted when only the details are being changed. */ completed?: boolean /** New quantity (`null` clears it); omitted to leave it untouched. */ quantity?: string | null /** New notes (`null` clears them); omitted to leave them untouched. */ notes?: string | null } const updateItemMutationKey = (listId: string) => ['lists', listId, 'items', 'update'] export function useUpdateItem(listId: string) { const queryClient = useQueryClient() const { queryKey } = itemsQueryOptions(listId) const mutationKey = updateItemMutationKey(listId) return useMutation({ mutationKey, mutationFn: (input: UpdateItemInput) => { const body: { name?: string completed?: boolean quantity?: string | null notes?: string | null } = {} if (input.name !== undefined) body.name = input.name if (input.completed !== undefined) body.completed = input.completed if (input.quantity !== undefined) body.quantity = input.quantity if (input.notes !== undefined) body.notes = input.notes return apiFetch(`/lists/${listId}/items/${input.itemId}`, { method: 'PATCH', body: JSON.stringify(body), }) }, onMutate: async ({ itemId, name, completed, quantity, notes }) => { // Cancel the outgoing refetch so it cannot overwrite our optimistic one. await queryClient.cancelQueries({ queryKey }) const previous = queryClient.getQueryData(queryKey)?.find((item) => item.id === itemId) queryClient.setQueryData(queryKey, (items) => items?.map((item) => { if (item.id !== itemId) return item return { ...item, ...(name !== undefined ? { name: name.trim() } : {}), ...(completed !== undefined ? { completed, boughtAt: completed ? new Date().toISOString() : null } : {}), ...(quantity !== undefined ? { quantity: quantity?.trim() || null } : {}), ...(notes !== undefined ? { notes: notes?.trim() || null } : {}), } }), ) return { previous } }, // Only this item is rolled back, so other toggles in flight keep their state. onError: (error, _variables, context) => { toast.error( error instanceof ApiError ? (error.problem.detail ?? error.problem.title) : 'No pudimos guardar el cambio.', ) const previous = context?.previous if (!previous) return queryClient.setQueryData(queryKey, (items) => items?.map((item) => (item.id === previous.id ? previous : item)), ) }, // Several items can be toggled in a row: refetch once the last one settles, so an // early refetch cannot bring back the server state of a toggle still in flight. onSettled: () => { if (queryClient.isMutating({ mutationKey }) === 1) { return queryClient.invalidateQueries({ queryKey }) } }, }) } /** Ids of the items of a list whose bought state is being saved right now. */ export function usePendingItemUpdates(listId: string): string[] { return useMutationState({ filters: { mutationKey: updateItemMutationKey(listId), status: 'pending' }, select: (mutation) => (mutation.state.variables as UpdateItemInput).itemId, }) } type MoveItemInput = { itemId: string targetListId: string /** Name of the target list, only used for the confirmation toast. */ targetListName: string } export function useMoveItem(listId: string) { const queryClient = useQueryClient() const { queryKey } = itemsQueryOptions(listId) return useMutation({ mutationFn: ({ itemId, targetListId }: MoveItemInput) => apiFetch(`/lists/${listId}/items/${itemId}/move`, { method: 'POST', body: JSON.stringify({ targetListId }), }), // The item leaves this list right away; the user stays on it. onMutate: async ({ itemId }) => { await queryClient.cancelQueries({ queryKey }) const items = queryClient.getQueryData(queryKey) const index = items?.findIndex((item) => item.id === itemId) ?? -1 const previous = index >= 0 ? items?.[index] : undefined queryClient.setQueryData(queryKey, (current) => current?.filter((item) => item.id !== itemId)) return { previous, index } }, onSuccess: (_moved, { targetListId, targetListName }) => { toast.success(`Movido a «${targetListName}»`) return queryClient.invalidateQueries({ queryKey: itemsQueryOptions(targetListId).queryKey }) }, // The item goes back to where it was, so the list does not jump around. onError: (error, _variables, context) => { toast.error( error instanceof ApiError ? (error.problem.detail ?? error.problem.title) : 'No pudimos mover el artículo.', ) const previous = context?.previous if (!previous) return queryClient.setQueryData(queryKey, (items) => { if (!items || items.some((item) => item.id === previous.id)) return items const next = [...items] next.splice(Math.min(context.index, next.length), 0, previous) return next }) }, }) } /** Ids of the items hidden because they were just deleted (they can still come back). */ export function usePendingDeletions(): ReadonlySet { return useSyncExternalStore(subscribePendingDeletions, getPendingDeletions) } /** * Deletes an item with a few seconds to undo it: the row disappears at once, * a toast offers "Deshacer" and the `DELETE` is only sent once that time is * over, so undoing never has to recreate anything. */ export function useDeleteItem(listId: string) { const queryClient = useQueryClient() const { queryKey } = itemsQueryOptions(listId) return (item: ListItem) => { const undo = scheduleDeletion(item.id, async ({ keepalive }) => { try { await apiFetch(`/lists/${listId}/items/${item.id}`, { method: 'DELETE', keepalive }) queryClient.setQueryData(queryKey, (items) => items?.filter((current) => current.id !== item.id), ) } catch (error) { toast.error( error instanceof ApiError ? (error.problem.detail ?? error.problem.title) : 'No pudimos eliminar el artículo.', ) } }) toast(`«${item.name}» eliminado`, { duration: DELETE_UNDO_MS, action: { label: 'Deshacer', onClick: undo }, }) } } /** * Deletes items right away, without the undo window of `useDeleteItem`: used to undo a * dictation, which is itself the undo. The rows leave the list at once. */ export function useRemoveItems(listId: string) { const queryClient = useQueryClient() const { queryKey } = itemsQueryOptions(listId) return async (itemIds: string[]) => { const ids = new Set(itemIds) queryClient.setQueryData(queryKey, (items) => items?.filter((item) => !ids.has(item.id))) const results = await Promise.allSettled( itemIds.map((itemId) => apiFetch(`/lists/${listId}/items/${itemId}`, { method: 'DELETE' }), ), ) if (results.some((result) => result.status === 'rejected')) { toast.error('No pudimos quitar todos los artículos.') await queryClient.invalidateQueries({ queryKey }) } } }