feat(items): delete an item with a swipe right, undoable for 3 seconds

A long swipe right on an item (or "Eliminar" in the desktop context menu)
hides it and shows a toast with "Deshacer". The DELETE is only sent once
the 3 seconds are over, so undoing just cancels it; pending deletions are
flushed with keepalive if the page is closed in the meantime.

The API gets DELETE /api/lists/:listId/items/:itemId, members only, which
publishes item.removed so other members see the item disappear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-20 20:40:56 -03:00
parent feb8df14c0
commit eb1f6cb2a9
10 changed files with 412 additions and 14 deletions

View File

@@ -6,10 +6,17 @@ import {
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({
@@ -216,3 +223,40 @@ export function useMoveItem(listId: string) {
},
})
}
/** Ids of the items hidden because they were just deleted (they can still come back). */
export function usePendingDeletions(): ReadonlySet<string> {
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<void>(`/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 },
})
}
}