From feb8df14c03f5f2a0cf4e96f0520ce6a144cac5e Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Tue, 20 Oct 2026 20:24:38 -0300 Subject: [PATCH] feat(items): move an item to another list with a long swipe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A longer swipe left on an item (past the edit threshold) opens a dialog with the user's other lists; picking one moves the item there while the user stays on the current list. On desktop, right-click now opens a context menu with "Editar" and "Mover a otra lista…". The API gets POST /api/lists/:listId/items/:itemId/move, which requires membership in both lists and publishes item.removed on the source list and item.created on the target, so other members see the change live. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/modules/lists/items/index.ts | 2 + .../api/src/modules/lists/items/move/route.ts | 31 +++ .../src/modules/lists/items/move/schema.ts | 8 + .../modules/lists/items/move/use-case.test.ts | 141 ++++++++++ .../src/modules/lists/items/move/use-case.ts | 72 ++++++ .../src/components/items/bought-item-list.tsx | 3 + apps/web/src/components/items/item-list.tsx | 13 + apps/web/src/components/items/item-row.tsx | 211 ++++++++++----- .../src/components/items/move-item-dialog.tsx | 94 +++++++ apps/web/src/components/ui/context-menu.tsx | 244 ++++++++++++++++++ apps/web/src/hooks/use-items.ts | 54 ++++ apps/web/src/lib/list-events.ts | 2 + packages/shared/src/events.ts | 3 + 13 files changed, 807 insertions(+), 71 deletions(-) create mode 100644 apps/api/src/modules/lists/items/move/route.ts create mode 100644 apps/api/src/modules/lists/items/move/schema.ts create mode 100644 apps/api/src/modules/lists/items/move/use-case.test.ts create mode 100644 apps/api/src/modules/lists/items/move/use-case.ts create mode 100644 apps/web/src/components/items/move-item-dialog.tsx create mode 100644 apps/web/src/components/ui/context-menu.tsx diff --git a/apps/api/src/modules/lists/items/index.ts b/apps/api/src/modules/lists/items/index.ts index 7f53970..1ec4ee9 100644 --- a/apps/api/src/modules/lists/items/index.ts +++ b/apps/api/src/modules/lists/items/index.ts @@ -4,6 +4,7 @@ import type { AppEnv } from '@/types' import { createItemRoute } from './create/route' import { listItemsRoute } from './list/route' +import { moveItemRoute } from './move/route' import { updateItemRoute } from './update/route' /** `items` sub-module of `lists`: mounted at `/lists/:listId/items`. */ @@ -11,3 +12,4 @@ export const listItemsModule = new Hono() .route('/', listItemsRoute) .route('/', createItemRoute) .route('/', updateItemRoute) + .route('/', moveItemRoute) diff --git a/apps/api/src/modules/lists/items/move/route.ts b/apps/api/src/modules/lists/items/move/route.ts new file mode 100644 index 0000000..a109333 --- /dev/null +++ b/apps/api/src/modules/lists/items/move/route.ts @@ -0,0 +1,31 @@ +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 { MoveItemSchema } from './schema' +import { MoveItem } from './use-case' + +/** POST /lists/:listId/items/:itemId/move — moves an item to another list of the user. */ +export const moveItemRoute = new Hono().post( + '/:itemId/move', + requireSession, + validate.param(ItemParamsSchema), + validate.json(MoveItemSchema), + async (c) => { + const { listId, itemId } = c.req.valid('param') + const { targetListId } = c.req.valid('json') + const result = await new MoveItem(prisma).execute({ + listId, + itemId, + userId: c.get('user').id, + targetListId, + }) + + return resultJson(c, result) + }, +) diff --git a/apps/api/src/modules/lists/items/move/schema.ts b/apps/api/src/modules/lists/items/move/schema.ts new file mode 100644 index 0000000..8654822 --- /dev/null +++ b/apps/api/src/modules/lists/items/move/schema.ts @@ -0,0 +1,8 @@ +import { z } from 'zod' + +/** Body of `POST /lists/:listId/items/:itemId/move`. */ +export const MoveItemSchema = z.object({ + targetListId: z.uuid('El identificador de la lista de destino no es válido'), +}) + +export type MoveItemInput = z.infer diff --git a/apps/api/src/modules/lists/items/move/use-case.test.ts b/apps/api/src/modules/lists/items/move/use-case.test.ts new file mode 100644 index 0000000..2529425 --- /dev/null +++ b/apps/api/src/modules/lists/items/move/use-case.test.ts @@ -0,0 +1,141 @@ +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 { MoveItem } from './use-case' + +type ItemRow = { + id: string + shoppingListId: string + name: string + completed: boolean + boughtAt: Date | null + quantity: string | null + notes: string | null + order: number + createdAt: Date + updatedAt: Date +} + +const now = new Date('2026-10-20T10:00:00.000Z') + +const item: ItemRow = { + id: 'item-1', + shoppingListId: 'list-1', + name: 'Leche', + completed: false, + boughtAt: null, + quantity: '1 L', + notes: 'sin lactosa', + order: 0, + createdAt: now, + updatedAt: now, +} + +function createDb(options: { memberOf: string[]; item: ItemRow | null }) { + const updates: unknown[] = [] + + const db = { + shoppingListMember: { + findUnique: async (args: { where: { listId_userId: { listId: string } } }) => + options.memberOf.includes(args.where.listId_userId.listId) ? { role: 'owner' } : null, + }, + listItem: { + findFirst: async () => options.item, + update: async (args: { data: Partial }) => { + updates.push(args) + return { ...options.item, ...args.data } as ItemRow + }, + }, + } + + return { db: db as unknown as Database, updates } +} + +function createBus() { + const events = new ListEvents() + const published: ListEvent[] = [] + events.subscribe('list-1', (event) => published.push(event)) + events.subscribe('list-2', (event) => published.push(event)) + + return { events, published } +} + +const input = { listId: 'list-1', itemId: 'item-1', userId: 'user-1', targetListId: 'list-2' } + +describe('MoveItem', () => { + it('answers 400 when the target is the same list', async () => { + const { db, updates } = createDb({ memberOf: ['list-1'], item }) + const { events, published } = createBus() + const result = await new MoveItem(db, events).execute({ ...input, targetListId: 'list-1' }) + + expect(result.ok).toBe(false) + if (result.ok) throw new Error('expected the use case to fail') + expect(result.error.status).toBe(400) + expect(updates).toHaveLength(0) + expect(published).toHaveLength(0) + }) + + it('answers 404 when the user does not belong to the source list', async () => { + const { db, updates } = createDb({ memberOf: ['list-2'], item }) + const { events, published } = createBus() + const result = await new MoveItem(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(updates).toHaveLength(0) + expect(published).toHaveLength(0) + }) + + it('answers 404 when the user does not belong to the target list', async () => { + const { db, updates } = createDb({ memberOf: ['list-1'], item }) + const { events, published } = createBus() + const result = await new MoveItem(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(result.error.detail).toBe('La lista de destino no existe o no tienes acceso.') + expect(updates).toHaveLength(0) + expect(published).toHaveLength(0) + }) + + it('answers 404 when the item does not belong to the source list', async () => { + const { db, updates } = createDb({ memberOf: ['list-1', 'list-2'], item: null }) + const { events, published } = createBus() + const result = await new MoveItem(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(updates).toHaveLength(0) + expect(published).toHaveLength(0) + }) + + it('moves the item, keeping its details, and notifies both lists', async () => { + const { db, updates } = createDb({ memberOf: ['list-1', 'list-2'], item }) + const { events, published } = createBus() + const result = await new MoveItem(db, events).execute(input) + + expect(result.ok).toBe(true) + if (!result.ok) throw new Error('expected the use case to succeed') + + expect(updates).toEqual([{ where: { id: 'item-1' }, data: { shoppingListId: 'list-2' } }]) + expect(result.value).toMatchObject({ + id: 'item-1', + listId: 'list-2', + name: 'Leche', + quantity: '1 L', + notes: 'sin lactosa', + completed: false, + }) + + expect(published).toEqual([ + { type: 'item.removed', listId: 'list-1', itemId: 'item-1' }, + { type: 'item.created', listId: 'list-2', item: result.value }, + ]) + }) +}) diff --git a/apps/api/src/modules/lists/items/move/use-case.ts b/apps/api/src/modules/lists/items/move/use-case.ts new file mode 100644 index 0000000..b46cd70 --- /dev/null +++ b/apps/api/src/modules/lists/items/move/use-case.ts @@ -0,0 +1,72 @@ +import { + Failure, + type ListItem, + Ok, + type ProblemDetails, + problems, + type Result, +} from '@superlist/shared' + +import { type ListEvents, listEvents } from '@/lib/events' +import type { Database } from '@/lib/prisma' + +import { toListItem } from '../serialize' + +type MoveItemFields = { + listId: string + itemId: string + userId: string + targetListId: string +} + +/** + * Moves an item to another list, keeping its name, quantity, notes and bought + * state. The user has to be a member of both lists. + */ +export class MoveItem { + constructor( + private readonly db: Database, + private readonly events: ListEvents = listEvents, + ) {} + + async execute(input: MoveItemFields): Promise> { + if (input.targetListId === input.listId) { + return Failure(problems.badRequest('El artículo ya está en esa lista.')) + } + + 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 targetMembership = await this.db.shoppingListMember.findUnique({ + where: { listId_userId: { listId: input.targetListId, userId: input.userId } }, + }) + + if (!targetMembership) { + return Failure(problems.notFound('La lista de destino 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.')) + } + + const moved = await this.db.listItem.update({ + where: { id: item.id }, + data: { shoppingListId: input.targetListId }, + }) + + const dto = toListItem(moved) + this.events.publish({ type: 'item.removed', listId: input.listId, itemId: item.id }) + this.events.publish({ type: 'item.created', listId: input.targetListId, item: dto }) + + return Ok(dto) + } +} diff --git a/apps/web/src/components/items/bought-item-list.tsx b/apps/web/src/components/items/bought-item-list.tsx index 3df8e4c..02eb33a 100644 --- a/apps/web/src/components/items/bought-item-list.tsx +++ b/apps/web/src/components/items/bought-item-list.tsx @@ -13,6 +13,7 @@ type BoughtItemListProps = { savingIds: string[] /** The editing state of each row, owned by the parent so only one row edits at a time. */ editingProps: (itemId: string) => Pick + onMove: (item: ListItem) => void } /** @@ -25,6 +26,7 @@ export function BoughtItemList({ updateItem, savingIds, editingProps, + onMove, }: BoughtItemListProps) { return ( @@ -42,6 +44,7 @@ export function BoughtItemList({ updateItem={updateItem} isSaving={savingIds.includes(item.id)} {...editingProps(item.id)} + onMove={() => onMove(item)} /> ))} diff --git a/apps/web/src/components/items/item-list.tsx b/apps/web/src/components/items/item-list.tsx index 8c818ff..ee9a203 100644 --- a/apps/web/src/components/items/item-list.tsx +++ b/apps/web/src/components/items/item-list.tsx @@ -1,3 +1,4 @@ +import type { ListItem } from '@superlist/shared' import { ShoppingBasketIcon } from 'lucide-react' import { useState } from 'react' @@ -12,6 +13,7 @@ import { splitItems } from '@/lib/items' import { BoughtItemList } from './bought-item-list' import { ItemRow } from './item-row' +import { MoveItemDialog } from './move-item-dialog' type ItemListProps = { listId: string @@ -29,6 +31,13 @@ export function ItemList({ listId }: ItemListProps) { const today = useToday() // Only one row shows its inline editor at a time: opening another closes it. const [editingId, setEditingId] = useState(null) + // The item whose "move to another list" dialog is open. + const [movingItem, setMovingItem] = useState(null) + + const openMoveDialog = (item: ListItem) => { + setEditingId((current) => (current === item.id ? null : current)) + setMovingItem(item) + } const editingProps = (itemId: string) => ({ editing: editingId === itemId, @@ -94,6 +103,7 @@ export function ItemList({ listId }: ItemListProps) { updateItem={updateItem} isSaving={savingIds.includes(item.id)} {...editingProps(item.id)} + onMove={() => openMoveDialog(item)} /> ))} @@ -106,8 +116,11 @@ export function ItemList({ listId }: ItemListProps) { updateItem={updateItem} savingIds={savingIds} editingProps={editingProps} + onMove={openMoveDialog} /> )} + + setMovingItem(null)} /> ) } diff --git a/apps/web/src/components/items/item-row.tsx b/apps/web/src/components/items/item-row.tsx index ebb1bea..ad87ad8 100644 --- a/apps/web/src/components/items/item-row.tsx +++ b/apps/web/src/components/items/item-row.tsx @@ -1,9 +1,15 @@ import type { ListItem } from '@superlist/shared' -import { CheckIcon, PencilIcon } from 'lucide-react' +import { CheckIcon, FolderInputIcon, PencilIcon } from 'lucide-react' import { type PointerEvent, useRef, useState } from 'react' import { flushSync } from 'react-dom' import { ItemEditor } from '@/components/items/item-editor' +import { + ContextMenu, + ContextMenuContent, + ContextMenuItem, + ContextMenuTrigger, +} from '@/components/ui/context-menu' import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items' import { quantityLabel } from '@/lib/items' import { cn } from '@/lib/utils' @@ -16,35 +22,60 @@ export type ItemRowProps = { /** The inline editor of this row is open (only one row edits at a time). */ editing: boolean onEditingChange: (editing: boolean) => void + /** Opens the "move to another list" dialog for this item. */ + onMove: () => void } /** Horizontal drag (px) that turns a touch on the row into "edit the item". */ -const SWIPE_THRESHOLD = 48 +const EDIT_THRESHOLD = 48 + +/** A longer drag (px) that turns it into "move the item to another list". */ +const MOVE_THRESHOLD = 120 /** Furthest the row slides while dragged, so it never leaves the card. */ -const MAX_DRAG = SWIPE_THRESHOLD * 1.5 +const MAX_DRAG = MOVE_THRESHOLD * 1.25 + +/** What releasing the finger does, decided by how far the row was dragged. */ +type SwipeAction = 'edit' | 'move' /** * How far the row is drawn for a finger `dx` px to the left: it follows the - * finger up to the threshold and then resists, capped at `MAX_DRAG`. + * finger up to the move threshold and then resists, capped at `MAX_DRAG`. */ function dragOffset(dx: number): number { if (dx >= 0) return 0 const distance = -dx const resisted = - distance <= SWIPE_THRESHOLD ? distance : SWIPE_THRESHOLD + (distance - SWIPE_THRESHOLD) / 3 + distance <= MOVE_THRESHOLD ? distance : MOVE_THRESHOLD + (distance - MOVE_THRESHOLD) / 3 return -Math.min(resisted, MAX_DRAG) } +function swipeAction(dx: number): SwipeAction | null { + if (dx < -MOVE_THRESHOLD) return 'move' + if (dx < -EDIT_THRESHOLD) return 'edit' + return null +} + /** A single item row inside a grouped card: tapping it toggles its bought state. */ -export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }: ItemRowProps) { +export function ItemRow({ + item, + updateItem, + isSaving, + editing, + onEditingChange, + onMove, +}: ItemRowProps) { const [dragX, setDragX] = useState(0) const swipeStart = useRef<{ x: number; y: number } | null>(null) - // Set once a drag passes the threshold: releasing the finger then opens the - // editor, and the click that the touch may fire right after is ignored. - const swiped = useRef(false) + // Set once a drag passes a threshold: releasing the finger then runs that + // action, and the click that the touch may fire right after is ignored. + const swiped = useRef(null) + const [action, setAction] = useState(null) const quantityInputRef = useRef(null) + // "Editar" was picked in the context menu: the editor's input takes the focus + // once the menu closes, since the menu keeps it while it is open. + const focusEditorOnMenuClose = useRef(false) // A placeholder has no server id yet, so it cannot be toggled or edited. const editable = !isSaving && !isOptimisticItem(item) @@ -61,8 +92,8 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange } } const handlePointerDown = (event: PointerEvent) => { - // Mice edit through right-click; only touch drags are tracked here. - swiped.current = false + // Mice use the right-click menu; only touch drags are tracked here. + swiped.current = null if (!editable || event.pointerType === 'mouse') return swipeStart.current = { x: event.clientX, y: event.clientY } } @@ -78,20 +109,24 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange } if (!swiped.current && Math.abs(dx) <= Math.abs(dy)) return setDragX(dragOffset(dx)) - swiped.current = dx < -SWIPE_THRESHOLD + swiped.current = swipeAction(dx) + setAction(swiped.current) } const handlePointerUp = () => { - const shouldOpen = swipeStart.current !== null && swiped.current + const released = swipeStart.current !== null ? swiped.current : null swipeStart.current = null setDragX(0) - if (shouldOpen) openEditor() + setAction(null) + if (released === 'edit') openEditor() + if (released === 'move') onMove() } const handlePointerCancel = () => { swipeStart.current = null - swiped.current = false + swiped.current = null setDragX(0) + setAction(null) } const dragging = swipeStart.current !== null && dragX !== 0 @@ -101,71 +136,105 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
{dragX !== 0 && (
- + {action === 'move' ? ( + + ) : ( + + )}
)} - + + + + + + {item.name} + + {item.notes && ( + {item.notes} + )} + + {quantity && ( + {quantity} + )} + + + {/* Right-click is the desktop equivalent of the swipes. */} + { + if (!focusEditorOnMenuClose.current) return + focusEditorOnMenuClose.current = false + event.preventDefault() + quantityInputRef.current?.focus() + }} + > + { + focusEditorOnMenuClose.current = true + onEditingChange(true) + }} + > + + Editar + + + + Mover a otra lista… + + +
{editing && ( void +} + +/** + * Lets the user pick another of their lists for an item. Picking one moves the + * item there and closes the dialog; the user stays on the current list. + */ +export function MoveItemDialog({ listId, item, onClose }: MoveItemDialogProps) { + const { data: lists, isPending, error } = useLists() + const moveItem = useMoveItem(listId) + + const targets = lists?.filter((list) => list.id !== listId) ?? [] + + return ( + !open && onClose()}> + + + Mover a otra lista + + {item ? `Elige a qué lista quieres mover «${item.name}».` : null} + + + + {error ? ( + + + {error instanceof ApiError + ? (error.problem.detail ?? error.problem.title) + : 'No pudimos cargar tus listas.'} + + + ) : isPending ? ( +
+ + +
+ ) : targets.length === 0 ? ( +

+ No tienes otras listas.{' '} + + Crea una + {' '} + para poder mover artículos. +

+ ) : ( +
    + {targets.map((list) => ( +
  • + +
  • + ))} +
+ )} +
+
+ ) +} diff --git a/apps/web/src/components/ui/context-menu.tsx b/apps/web/src/components/ui/context-menu.tsx new file mode 100644 index 0000000..bea76dd --- /dev/null +++ b/apps/web/src/components/ui/context-menu.tsx @@ -0,0 +1,244 @@ +import { cn } from 'cn' +import { CheckIcon, ChevronRightIcon } from 'lucide-react' +import { ContextMenu as ContextMenuPrimitive } from 'radix-ui' +import * as React from 'react' + +function ContextMenu({ ...props }: React.ComponentProps) { + return +} + +function ContextMenuTrigger({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function ContextMenuGroup({ ...props }: React.ComponentProps) { + return +} + +function ContextMenuPortal({ ...props }: React.ComponentProps) { + return +} + +function ContextMenuSub({ ...props }: React.ComponentProps) { + return +} + +function ContextMenuRadioGroup({ + ...props +}: React.ComponentProps) { + return +} + +function ContextMenuContent({ + className, + ...props +}: React.ComponentProps & { + side?: 'top' | 'right' | 'bottom' | 'left' +}) { + return ( + + + + ) +} + +function ContextMenuItem({ + className, + inset, + variant = 'default', + ...props +}: React.ComponentProps & { + inset?: boolean + variant?: 'default' | 'destructive' +}) { + return ( + + ) +} + +function ContextMenuSubTrigger({ + className, + inset, + children, + ...props +}: React.ComponentProps & { + inset?: boolean +}) { + return ( + + {children} + + + ) +} + +function ContextMenuSubContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function ContextMenuCheckboxItem({ + className, + children, + checked, + inset, + ...props +}: React.ComponentProps & { + inset?: boolean +}) { + return ( + + + + + + + {children} + + ) +} + +function ContextMenuRadioItem({ + className, + children, + inset, + ...props +}: React.ComponentProps & { + inset?: boolean +}) { + return ( + + + + + + + {children} + + ) +} + +function ContextMenuLabel({ + className, + inset, + ...props +}: React.ComponentProps & { + inset?: boolean +}) { + return ( + + ) +} + +function ContextMenuSeparator({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function ContextMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) { + return ( + + ) +} + +export { + ContextMenu, + ContextMenuCheckboxItem, + ContextMenuContent, + ContextMenuGroup, + ContextMenuItem, + ContextMenuLabel, + ContextMenuPortal, + ContextMenuRadioGroup, + ContextMenuRadioItem, + ContextMenuSeparator, + ContextMenuShortcut, + ContextMenuSub, + ContextMenuSubContent, + ContextMenuSubTrigger, + ContextMenuTrigger, +} diff --git a/apps/web/src/hooks/use-items.ts b/apps/web/src/hooks/use-items.ts index 90118f0..3714607 100644 --- a/apps/web/src/hooks/use-items.ts +++ b/apps/web/src/hooks/use-items.ts @@ -162,3 +162,57 @@ export function usePendingItemUpdates(listId: string): string[] { 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 + }) + }, + }) +} diff --git a/apps/web/src/lib/list-events.ts b/apps/web/src/lib/list-events.ts index d113d88..6bdbae8 100644 --- a/apps/web/src/lib/list-events.ts +++ b/apps/web/src/lib/list-events.ts @@ -5,6 +5,7 @@ import type { QueryKey } from '@tanstack/react-query' export const LIST_EVENT_TYPES: readonly ListEventType[] = [ 'item.created', 'item.updated', + 'item.removed', 'invitation.created', 'member.added', 'list.updated', @@ -19,6 +20,7 @@ export function queryKeysForListEvent(type: ListEventType, listId: string): Quer switch (type) { case 'item.created': case 'item.updated': + case 'item.removed': return [['lists', listId, 'items']] case 'invitation.created': case 'member.added': diff --git a/packages/shared/src/events.ts b/packages/shared/src/events.ts index 006045e..d2bba52 100644 --- a/packages/shared/src/events.ts +++ b/packages/shared/src/events.ts @@ -4,6 +4,7 @@ import type { ListItem } from './shopping-list' export type ListEventType = | 'item.created' | 'item.updated' + | 'item.removed' | 'invitation.created' | 'member.added' | 'list.updated' @@ -15,6 +16,8 @@ export type ListEventType = */ export type ListEvent = | { type: 'item.created' | 'item.updated'; listId: string; item: ListItem } + /** The item left this list (it was moved to another one). */ + | { type: 'item.removed'; listId: string; itemId: string } | { type: 'invitation.created'; listId: string; email: string } | { type: 'member.added'; listId: string; userId: string } | { type: 'list.updated'; listId: string; name: string }