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:
27
apps/api/src/modules/lists/items/delete/route.ts
Normal file
27
apps/api/src/modules/lists/items/delete/route.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
import { requireSession } from '@/lib/auth-session'
|
||||||
|
import { prisma } from '@/lib/prisma'
|
||||||
|
import { resultJson } from '@/lib/result-json'
|
||||||
|
import { validate } from '@/lib/validate'
|
||||||
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
|
import { ItemParamsSchema } from '../update/schema'
|
||||||
|
import { DeleteItem } from './use-case'
|
||||||
|
|
||||||
|
/** DELETE /lists/:listId/items/:itemId — deletes an item from a list the user belongs to. */
|
||||||
|
export const deleteItemRoute = new Hono<AppEnv>().delete(
|
||||||
|
'/:itemId',
|
||||||
|
requireSession,
|
||||||
|
validate.param(ItemParamsSchema),
|
||||||
|
async (c) => {
|
||||||
|
const { listId, itemId } = c.req.valid('param')
|
||||||
|
const result = await new DeleteItem(prisma).execute({
|
||||||
|
listId,
|
||||||
|
itemId,
|
||||||
|
userId: c.get('user').id,
|
||||||
|
})
|
||||||
|
|
||||||
|
return resultJson(c, result, { status: 204 })
|
||||||
|
},
|
||||||
|
)
|
||||||
75
apps/api/src/modules/lists/items/delete/use-case.test.ts
Normal file
75
apps/api/src/modules/lists/items/delete/use-case.test.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import { describe, expect, it } from 'bun:test'
|
||||||
|
import type { ListEvent } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { ListEvents } from '@/lib/events'
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
import { DeleteItem } from './use-case'
|
||||||
|
|
||||||
|
function createDb(options: { membership: unknown; item: { id: string } | null }) {
|
||||||
|
const deletes: unknown[] = []
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
shoppingListMember: {
|
||||||
|
findUnique: async () => options.membership,
|
||||||
|
},
|
||||||
|
listItem: {
|
||||||
|
findFirst: async () => options.item,
|
||||||
|
delete: async (args: unknown) => {
|
||||||
|
deletes.push(args)
|
||||||
|
return options.item
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
return { db: db as unknown as Database, deletes }
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBus() {
|
||||||
|
const events = new ListEvents()
|
||||||
|
const published: ListEvent[] = []
|
||||||
|
events.subscribe('list-1', (event) => published.push(event))
|
||||||
|
|
||||||
|
return { events, published }
|
||||||
|
}
|
||||||
|
|
||||||
|
const input = { listId: 'list-1', itemId: 'item-1', userId: 'user-1' }
|
||||||
|
|
||||||
|
describe('DeleteItem', () => {
|
||||||
|
it('answers 404 when the user does not belong to the list', async () => {
|
||||||
|
const { db, deletes } = createDb({ membership: null, item: { id: 'item-1' } })
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new DeleteItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(404)
|
||||||
|
expect(deletes).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('answers 404 when the item does not belong to the list', async () => {
|
||||||
|
const { db, deletes } = createDb({ membership: { role: 'owner' }, item: null })
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new DeleteItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(false)
|
||||||
|
if (result.ok) throw new Error('expected the use case to fail')
|
||||||
|
expect(result.error.status).toBe(404)
|
||||||
|
expect(deletes).toHaveLength(0)
|
||||||
|
expect(published).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('deletes the item and publishes item.removed', async () => {
|
||||||
|
const { db, deletes } = createDb({
|
||||||
|
membership: { role: 'collaborator' },
|
||||||
|
item: { id: 'item-1' },
|
||||||
|
})
|
||||||
|
const { events, published } = createBus()
|
||||||
|
const result = await new DeleteItem(db, events).execute(input)
|
||||||
|
|
||||||
|
expect(result.ok).toBe(true)
|
||||||
|
expect(deletes).toEqual([{ where: { id: 'item-1' } }])
|
||||||
|
expect(published).toEqual([{ type: 'item.removed', listId: 'list-1', itemId: 'item-1' }])
|
||||||
|
})
|
||||||
|
})
|
||||||
42
apps/api/src/modules/lists/items/delete/use-case.ts
Normal file
42
apps/api/src/modules/lists/items/delete/use-case.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { Failure, Ok, type ProblemDetails, problems, type Result } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { type ListEvents, listEvents } from '@/lib/events'
|
||||||
|
import type { Database } from '@/lib/prisma'
|
||||||
|
|
||||||
|
type DeleteItemFields = {
|
||||||
|
listId: string
|
||||||
|
itemId: string
|
||||||
|
userId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deletes an item from a list. Only members can do it. */
|
||||||
|
export class DeleteItem {
|
||||||
|
constructor(
|
||||||
|
private readonly db: Database,
|
||||||
|
private readonly events: ListEvents = listEvents,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async execute(input: DeleteItemFields): Promise<Result<void, ProblemDetails>> {
|
||||||
|
const membership = await this.db.shoppingListMember.findUnique({
|
||||||
|
where: { listId_userId: { listId: input.listId, userId: input.userId } },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!membership) {
|
||||||
|
return Failure(problems.notFound('La lista no existe o no tienes acceso.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await this.db.listItem.findFirst({
|
||||||
|
where: { id: input.itemId, shoppingListId: input.listId },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!item) {
|
||||||
|
return Failure(problems.notFound('El artículo no existe en esta lista.'))
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.db.listItem.delete({ where: { id: item.id } })
|
||||||
|
|
||||||
|
this.events.publish({ type: 'item.removed', listId: input.listId, itemId: item.id })
|
||||||
|
|
||||||
|
return Ok(undefined)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { Hono } from 'hono'
|
|||||||
import type { AppEnv } from '@/types'
|
import type { AppEnv } from '@/types'
|
||||||
|
|
||||||
import { createItemRoute } from './create/route'
|
import { createItemRoute } from './create/route'
|
||||||
|
import { deleteItemRoute } from './delete/route'
|
||||||
import { listItemsRoute } from './list/route'
|
import { listItemsRoute } from './list/route'
|
||||||
import { moveItemRoute } from './move/route'
|
import { moveItemRoute } from './move/route'
|
||||||
import { updateItemRoute } from './update/route'
|
import { updateItemRoute } from './update/route'
|
||||||
@@ -13,3 +14,4 @@ export const listItemsModule = new Hono<AppEnv>()
|
|||||||
.route('/', createItemRoute)
|
.route('/', createItemRoute)
|
||||||
.route('/', updateItemRoute)
|
.route('/', updateItemRoute)
|
||||||
.route('/', moveItemRoute)
|
.route('/', moveItemRoute)
|
||||||
|
.route('/', deleteItemRoute)
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ type BoughtItemListProps = {
|
|||||||
/** The editing state of each row, owned by the parent so only one row edits at a time. */
|
/** The editing state of each row, owned by the parent so only one row edits at a time. */
|
||||||
editingProps: (itemId: string) => Pick<ItemRowProps, 'editing' | 'onEditingChange'>
|
editingProps: (itemId: string) => Pick<ItemRowProps, 'editing' | 'onEditingChange'>
|
||||||
onMove: (item: ListItem) => void
|
onMove: (item: ListItem) => void
|
||||||
|
onDelete: (item: ListItem) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,6 +28,7 @@ export function BoughtItemList({
|
|||||||
savingIds,
|
savingIds,
|
||||||
editingProps,
|
editingProps,
|
||||||
onMove,
|
onMove,
|
||||||
|
onDelete,
|
||||||
}: BoughtItemListProps) {
|
}: BoughtItemListProps) {
|
||||||
return (
|
return (
|
||||||
<Collapsible defaultOpen asChild>
|
<Collapsible defaultOpen asChild>
|
||||||
@@ -45,6 +47,7 @@ export function BoughtItemList({
|
|||||||
isSaving={savingIds.includes(item.id)}
|
isSaving={savingIds.includes(item.id)}
|
||||||
{...editingProps(item.id)}
|
{...editingProps(item.id)}
|
||||||
onMove={() => onMove(item)}
|
onMove={() => onMove(item)}
|
||||||
|
onDelete={() => onDelete(item)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -5,7 +5,13 @@ import { useState } from 'react'
|
|||||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||||
import { Card, CardContent } from '@/components/ui/card'
|
import { Card, CardContent } from '@/components/ui/card'
|
||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import { useItems, usePendingItemUpdates, useUpdateItem } from '@/hooks/use-items'
|
import {
|
||||||
|
useDeleteItem,
|
||||||
|
useItems,
|
||||||
|
usePendingDeletions,
|
||||||
|
usePendingItemUpdates,
|
||||||
|
useUpdateItem,
|
||||||
|
} from '@/hooks/use-items'
|
||||||
import { useListEvents } from '@/hooks/use-list-events'
|
import { useListEvents } from '@/hooks/use-list-events'
|
||||||
import { useToday } from '@/hooks/use-today'
|
import { useToday } from '@/hooks/use-today'
|
||||||
import { ApiError } from '@/lib/api-client'
|
import { ApiError } from '@/lib/api-client'
|
||||||
@@ -28,12 +34,20 @@ export function ItemList({ listId }: ItemListProps) {
|
|||||||
const { data: items, isPending, error } = useItems(listId)
|
const { data: items, isPending, error } = useItems(listId)
|
||||||
const updateItem = useUpdateItem(listId)
|
const updateItem = useUpdateItem(listId)
|
||||||
const savingIds = usePendingItemUpdates(listId)
|
const savingIds = usePendingItemUpdates(listId)
|
||||||
|
const deleteItem = useDeleteItem(listId)
|
||||||
|
// Just-deleted items stay hidden while they can still be restored.
|
||||||
|
const deletingIds = usePendingDeletions()
|
||||||
const today = useToday()
|
const today = useToday()
|
||||||
// Only one row shows its inline editor at a time: opening another closes it.
|
// Only one row shows its inline editor at a time: opening another closes it.
|
||||||
const [editingId, setEditingId] = useState<string | null>(null)
|
const [editingId, setEditingId] = useState<string | null>(null)
|
||||||
// The item whose "move to another list" dialog is open.
|
// The item whose "move to another list" dialog is open.
|
||||||
const [movingItem, setMovingItem] = useState<ListItem | null>(null)
|
const [movingItem, setMovingItem] = useState<ListItem | null>(null)
|
||||||
|
|
||||||
|
const handleDelete = (item: ListItem) => {
|
||||||
|
setEditingId((current) => (current === item.id ? null : current))
|
||||||
|
deleteItem(item)
|
||||||
|
}
|
||||||
|
|
||||||
const openMoveDialog = (item: ListItem) => {
|
const openMoveDialog = (item: ListItem) => {
|
||||||
setEditingId((current) => (current === item.id ? null : current))
|
setEditingId((current) => (current === item.id ? null : current))
|
||||||
setMovingItem(item)
|
setMovingItem(item)
|
||||||
@@ -71,7 +85,10 @@ export function ItemList({ listId }: ItemListProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const { pending, boughtToday } = splitItems(items, today)
|
const { pending, boughtToday } = splitItems(
|
||||||
|
items.filter((item) => !deletingIds.has(item.id)),
|
||||||
|
today,
|
||||||
|
)
|
||||||
|
|
||||||
if (pending.length === 0 && boughtToday.length === 0) {
|
if (pending.length === 0 && boughtToday.length === 0) {
|
||||||
return (
|
return (
|
||||||
@@ -104,6 +121,7 @@ export function ItemList({ listId }: ItemListProps) {
|
|||||||
isSaving={savingIds.includes(item.id)}
|
isSaving={savingIds.includes(item.id)}
|
||||||
{...editingProps(item.id)}
|
{...editingProps(item.id)}
|
||||||
onMove={() => openMoveDialog(item)}
|
onMove={() => openMoveDialog(item)}
|
||||||
|
onDelete={() => handleDelete(item)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
@@ -117,6 +135,7 @@ export function ItemList({ listId }: ItemListProps) {
|
|||||||
savingIds={savingIds}
|
savingIds={savingIds}
|
||||||
editingProps={editingProps}
|
editingProps={editingProps}
|
||||||
onMove={openMoveDialog}
|
onMove={openMoveDialog}
|
||||||
|
onDelete={handleDelete}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { ListItem } from '@superlist/shared'
|
import type { ListItem } from '@superlist/shared'
|
||||||
import { CheckIcon, FolderInputIcon, PencilIcon } from 'lucide-react'
|
import { CheckIcon, FolderInputIcon, PencilIcon, Trash2Icon } from 'lucide-react'
|
||||||
import { type PointerEvent, useRef, useState } from 'react'
|
import { type PointerEvent, useRef, useState } from 'react'
|
||||||
import { flushSync } from 'react-dom'
|
import { flushSync } from 'react-dom'
|
||||||
|
|
||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
ContextMenu,
|
ContextMenu,
|
||||||
ContextMenuContent,
|
ContextMenuContent,
|
||||||
ContextMenuItem,
|
ContextMenuItem,
|
||||||
|
ContextMenuSeparator,
|
||||||
ContextMenuTrigger,
|
ContextMenuTrigger,
|
||||||
} from '@/components/ui/context-menu'
|
} from '@/components/ui/context-menu'
|
||||||
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
|
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
|
||||||
@@ -24,6 +25,8 @@ export type ItemRowProps = {
|
|||||||
onEditingChange: (editing: boolean) => void
|
onEditingChange: (editing: boolean) => void
|
||||||
/** Opens the "move to another list" dialog for this item. */
|
/** Opens the "move to another list" dialog for this item. */
|
||||||
onMove: () => void
|
onMove: () => void
|
||||||
|
/** Deletes the item (it can be undone for a few seconds). */
|
||||||
|
onDelete: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Horizontal drag (px) that turns a touch on the row into "edit the item". */
|
/** Horizontal drag (px) that turns a touch on the row into "edit the item". */
|
||||||
@@ -32,28 +35,32 @@ const EDIT_THRESHOLD = 48
|
|||||||
/** A longer drag (px) that turns it into "move the item to another list". */
|
/** A longer drag (px) that turns it into "move the item to another list". */
|
||||||
const MOVE_THRESHOLD = 120
|
const MOVE_THRESHOLD = 120
|
||||||
|
|
||||||
/** Furthest the row slides while dragged, so it never leaves the card. */
|
/**
|
||||||
const MAX_DRAG = MOVE_THRESHOLD * 1.25
|
* Drag (px) to the right that turns a touch into "delete the item". Longer than
|
||||||
|
* the edit swipe because it is destructive (even if it can be undone).
|
||||||
|
*/
|
||||||
|
const DELETE_THRESHOLD = 96
|
||||||
|
|
||||||
/** What releasing the finger does, decided by how far the row was dragged. */
|
/** What releasing the finger does, decided by how far the row was dragged. */
|
||||||
type SwipeAction = 'edit' | 'move'
|
type SwipeAction = 'edit' | 'move' | 'delete'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* How far the row is drawn for a finger `dx` px to the left: it follows the
|
* How far the row is drawn for a finger `dx` px away: it follows the finger up
|
||||||
* finger up to the move threshold and then resists, capped at `MAX_DRAG`.
|
* to the furthest threshold on that side and then resists, capped a bit past it
|
||||||
|
* so the row never leaves the card. Negative is to the left.
|
||||||
*/
|
*/
|
||||||
function dragOffset(dx: number): number {
|
function dragOffset(dx: number): number {
|
||||||
if (dx >= 0) return 0
|
const limit = dx < 0 ? MOVE_THRESHOLD : DELETE_THRESHOLD
|
||||||
const distance = -dx
|
const distance = Math.abs(dx)
|
||||||
const resisted =
|
const resisted = distance <= limit ? distance : limit + (distance - limit) / 3
|
||||||
distance <= MOVE_THRESHOLD ? distance : MOVE_THRESHOLD + (distance - MOVE_THRESHOLD) / 3
|
|
||||||
|
|
||||||
return -Math.min(resisted, MAX_DRAG)
|
return Math.sign(dx) * Math.min(resisted, limit * 1.25)
|
||||||
}
|
}
|
||||||
|
|
||||||
function swipeAction(dx: number): SwipeAction | null {
|
function swipeAction(dx: number): SwipeAction | null {
|
||||||
if (dx < -MOVE_THRESHOLD) return 'move'
|
if (dx < -MOVE_THRESHOLD) return 'move'
|
||||||
if (dx < -EDIT_THRESHOLD) return 'edit'
|
if (dx < -EDIT_THRESHOLD) return 'edit'
|
||||||
|
if (dx > DELETE_THRESHOLD) return 'delete'
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,6 +72,7 @@ export function ItemRow({
|
|||||||
editing,
|
editing,
|
||||||
onEditingChange,
|
onEditingChange,
|
||||||
onMove,
|
onMove,
|
||||||
|
onDelete,
|
||||||
}: ItemRowProps) {
|
}: ItemRowProps) {
|
||||||
const [dragX, setDragX] = useState(0)
|
const [dragX, setDragX] = useState(0)
|
||||||
const swipeStart = useRef<{ x: number; y: number } | null>(null)
|
const swipeStart = useRef<{ x: number; y: number } | null>(null)
|
||||||
@@ -120,6 +128,7 @@ export function ItemRow({
|
|||||||
setAction(null)
|
setAction(null)
|
||||||
if (released === 'edit') openEditor()
|
if (released === 'edit') openEditor()
|
||||||
if (released === 'move') onMove()
|
if (released === 'move') onMove()
|
||||||
|
if (released === 'delete') onDelete()
|
||||||
}
|
}
|
||||||
|
|
||||||
const handlePointerCancel = () => {
|
const handlePointerCancel = () => {
|
||||||
@@ -134,7 +143,22 @@ export function ItemRow({
|
|||||||
return (
|
return (
|
||||||
<li>
|
<li>
|
||||||
<div className="relative overflow-hidden">
|
<div className="relative overflow-hidden">
|
||||||
{dragX !== 0 && (
|
{dragX > 0 && (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'absolute inset-y-0 left-0 flex items-center justify-center transition-colors',
|
||||||
|
// Past the threshold the background turns solid: releasing deletes.
|
||||||
|
action === 'delete'
|
||||||
|
? 'bg-destructive text-white'
|
||||||
|
: 'bg-destructive/15 text-destructive',
|
||||||
|
)}
|
||||||
|
style={{ width: dragX }}
|
||||||
|
aria-hidden
|
||||||
|
>
|
||||||
|
<Trash2Icon className="size-5" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{dragX < 0 && (
|
||||||
<div
|
<div
|
||||||
className={cn(
|
className={cn(
|
||||||
'absolute inset-y-0 right-0 flex items-center justify-center transition-colors',
|
'absolute inset-y-0 right-0 flex items-center justify-center transition-colors',
|
||||||
@@ -233,6 +257,11 @@ export function ItemRow({
|
|||||||
<FolderInputIcon />
|
<FolderInputIcon />
|
||||||
Mover a otra lista…
|
Mover a otra lista…
|
||||||
</ContextMenuItem>
|
</ContextMenuItem>
|
||||||
|
<ContextMenuSeparator />
|
||||||
|
<ContextMenuItem variant="destructive" onSelect={onDelete}>
|
||||||
|
<Trash2Icon />
|
||||||
|
Eliminar
|
||||||
|
</ContextMenuItem>
|
||||||
</ContextMenuContent>
|
</ContextMenuContent>
|
||||||
</ContextMenu>
|
</ContextMenu>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,10 +6,17 @@ import {
|
|||||||
useQuery,
|
useQuery,
|
||||||
useQueryClient,
|
useQueryClient,
|
||||||
} from '@tanstack/react-query'
|
} from '@tanstack/react-query'
|
||||||
|
import { useSyncExternalStore } from 'react'
|
||||||
|
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
import { ApiError, apiFetch } from '@/lib/api-client'
|
import { ApiError, apiFetch } from '@/lib/api-client'
|
||||||
|
import {
|
||||||
|
DELETE_UNDO_MS,
|
||||||
|
getPendingDeletions,
|
||||||
|
scheduleDeletion,
|
||||||
|
subscribePendingDeletions,
|
||||||
|
} from '@/lib/pending-deletions'
|
||||||
|
|
||||||
export const itemsQueryOptions = (listId: string) =>
|
export const itemsQueryOptions = (listId: string) =>
|
||||||
queryOptions({
|
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 },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
67
apps/web/src/lib/pending-deletions.test.ts
Normal file
67
apps/web/src/lib/pending-deletions.test.ts
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import {
|
||||||
|
DELETE_UNDO_MS,
|
||||||
|
flushPendingDeletions,
|
||||||
|
getPendingDeletions,
|
||||||
|
scheduleDeletion,
|
||||||
|
} from './pending-deletions'
|
||||||
|
|
||||||
|
describe('pending deletions', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hides the item and sends the delete once the undo window is over', async () => {
|
||||||
|
const commit = vi.fn(async () => {})
|
||||||
|
scheduleDeletion('item-1', commit)
|
||||||
|
|
||||||
|
expect(getPendingDeletions().has('item-1')).toBe(true)
|
||||||
|
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS - 1)
|
||||||
|
expect(commit).not.toHaveBeenCalled()
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(1)
|
||||||
|
expect(commit).toHaveBeenCalledWith({ keepalive: false })
|
||||||
|
expect(getPendingDeletions().has('item-1')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('undo restores the item and never sends the delete', async () => {
|
||||||
|
const commit = vi.fn(async () => {})
|
||||||
|
const undo = scheduleDeletion('item-2', commit)
|
||||||
|
|
||||||
|
undo()
|
||||||
|
expect(getPendingDeletions().has('item-2')).toBe(false)
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS)
|
||||||
|
expect(commit).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows the item again when the delete fails', async () => {
|
||||||
|
const commit = vi.fn(async (_init: { keepalive: boolean }) => {
|
||||||
|
throw new Error('offline')
|
||||||
|
})
|
||||||
|
scheduleDeletion('item-3', (init) => commit(init).catch(() => {}))
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS)
|
||||||
|
expect(commit).toHaveBeenCalledOnce()
|
||||||
|
expect(getPendingDeletions().has('item-3')).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('flushes waiting deletions right away with keepalive', async () => {
|
||||||
|
const commit = vi.fn(async () => {})
|
||||||
|
scheduleDeletion('item-4', commit)
|
||||||
|
|
||||||
|
flushPendingDeletions()
|
||||||
|
await vi.advanceTimersByTimeAsync(0)
|
||||||
|
|
||||||
|
expect(commit).toHaveBeenCalledWith({ keepalive: true })
|
||||||
|
expect(getPendingDeletions().has('item-4')).toBe(false)
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(DELETE_UNDO_MS)
|
||||||
|
expect(commit).toHaveBeenCalledOnce()
|
||||||
|
})
|
||||||
|
})
|
||||||
90
apps/web/src/lib/pending-deletions.ts
Normal file
90
apps/web/src/lib/pending-deletions.ts
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
/** How long a deleted item can still be restored before its `DELETE` is sent. */
|
||||||
|
export const DELETE_UNDO_MS = 3000
|
||||||
|
|
||||||
|
/** Sends the `DELETE`; `keepalive` is set when the page is going away. */
|
||||||
|
type Commit = (init: { keepalive: boolean }) => Promise<void>
|
||||||
|
|
||||||
|
type PendingDeletion = {
|
||||||
|
/** Pending until the `DELETE` is sent; `undefined` once it is in flight. */
|
||||||
|
timer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
commit: Commit
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Items the user deleted, still hidden while they can be restored or while
|
||||||
|
* their `DELETE` is in flight. It lives outside React so navigating away does
|
||||||
|
* not cancel a deletion; rows are filtered out at render time, so a refetch
|
||||||
|
* in the meantime cannot bring them back.
|
||||||
|
*/
|
||||||
|
const pending = new Map<string, PendingDeletion>()
|
||||||
|
const listeners = new Set<() => void>()
|
||||||
|
let snapshot: ReadonlySet<string> = new Set()
|
||||||
|
|
||||||
|
function emit() {
|
||||||
|
snapshot = new Set(pending.keys())
|
||||||
|
for (const listener of listeners) listener()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `useSyncExternalStore` subscription. */
|
||||||
|
export function subscribePendingDeletions(listener: () => void): () => void {
|
||||||
|
listeners.add(listener)
|
||||||
|
return () => listeners.delete(listener)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ids of the items hidden because they are being deleted (a stable snapshot). */
|
||||||
|
export function getPendingDeletions(): ReadonlySet<string> {
|
||||||
|
return snapshot
|
||||||
|
}
|
||||||
|
|
||||||
|
async function run(itemId: string, keepalive: boolean) {
|
||||||
|
const entry = pending.get(itemId)
|
||||||
|
if (!entry) return
|
||||||
|
|
||||||
|
clearTimeout(entry.timer)
|
||||||
|
entry.timer = undefined
|
||||||
|
|
||||||
|
try {
|
||||||
|
await entry.commit({ keepalive })
|
||||||
|
} finally {
|
||||||
|
// On success the commit already dropped the item from the cache; on
|
||||||
|
// failure the row comes back.
|
||||||
|
pending.delete(itemId)
|
||||||
|
emit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hides the item and sends its `DELETE` after `DELETE_UNDO_MS`. Returns the
|
||||||
|
* undo function, which only works while the `DELETE` has not been sent.
|
||||||
|
*/
|
||||||
|
export function scheduleDeletion(itemId: string, commit: Commit): () => void {
|
||||||
|
if (!pending.has(itemId)) {
|
||||||
|
pending.set(itemId, {
|
||||||
|
timer: setTimeout(() => void run(itemId, false), DELETE_UNDO_MS),
|
||||||
|
commit,
|
||||||
|
})
|
||||||
|
emit()
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
const entry = pending.get(itemId)
|
||||||
|
if (!entry?.timer) return
|
||||||
|
|
||||||
|
clearTimeout(entry.timer)
|
||||||
|
pending.delete(itemId)
|
||||||
|
emit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sends every deletion still waiting, without waiting for the undo window. */
|
||||||
|
export function flushPendingDeletions(): void {
|
||||||
|
for (const [itemId, entry] of pending) {
|
||||||
|
if (entry.timer) void run(itemId, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Closing the tab or the installed app must not lose a deletion: `keepalive`
|
||||||
|
// lets the request outlive the page.
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.addEventListener('pagehide', flushPendingDeletions)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user