feat(items): move an item to another list with a long swipe

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 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-20 20:24:38 -03:00
parent 86d4796d88
commit feb8df14c0
13 changed files with 807 additions and 71 deletions

View File

@@ -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<AppEnv>()
.route('/', listItemsRoute)
.route('/', createItemRoute)
.route('/', updateItemRoute)
.route('/', moveItemRoute)

View File

@@ -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<AppEnv>().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)
},
)

View File

@@ -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<typeof MoveItemSchema>

View File

@@ -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<ItemRow> }) => {
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 },
])
})
})

View File

@@ -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<Result<ListItem, ProblemDetails>> {
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)
}
}

View File

@@ -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<ItemRowProps, 'editing' | 'onEditingChange'>
onMove: (item: ListItem) => void
}
/**
@@ -25,6 +26,7 @@ export function BoughtItemList({
updateItem,
savingIds,
editingProps,
onMove,
}: BoughtItemListProps) {
return (
<Collapsible defaultOpen asChild>
@@ -42,6 +44,7 @@ export function BoughtItemList({
updateItem={updateItem}
isSaving={savingIds.includes(item.id)}
{...editingProps(item.id)}
onMove={() => onMove(item)}
/>
))}
</ul>

View File

@@ -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<string | null>(null)
// The item whose "move to another list" dialog is open.
const [movingItem, setMovingItem] = useState<ListItem | null>(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)}
/>
))}
</ul>
@@ -106,8 +116,11 @@ export function ItemList({ listId }: ItemListProps) {
updateItem={updateItem}
savingIds={savingIds}
editingProps={editingProps}
onMove={openMoveDialog}
/>
)}
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
</div>
)
}

View File

@@ -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<SwipeAction | null>(null)
const [action, setAction] = useState<SwipeAction | null>(null)
const quantityInputRef = useRef<HTMLInputElement>(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<HTMLButtonElement>) => {
// 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,13 +136,26 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
<div className="relative overflow-hidden">
{dragX !== 0 && (
<div
className="bg-primary/15 text-primary absolute inset-y-0 right-0 flex items-center justify-center"
className={cn(
'absolute inset-y-0 right-0 flex items-center justify-center transition-colors',
// Past the move threshold the background changes, so the user
// knows releasing now moves the item instead of editing it.
action === 'move'
? 'bg-primary text-primary-foreground'
: 'bg-primary/15 text-primary',
)}
style={{ width: -dragX }}
aria-hidden
>
{action === 'move' ? (
<FolderInputIcon className="size-5" />
) : (
<PencilIcon className="size-5" />
)}
</div>
)}
<ContextMenu>
<ContextMenuTrigger asChild disabled={!editable}>
<button
type="button"
aria-pressed={item.completed}
@@ -115,7 +163,7 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
disabled={!editable}
onClick={() => {
if (swiped.current) {
swiped.current = false
swiped.current = null
return
}
@@ -125,12 +173,6 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerCancel}
// Right-click is the desktop equivalent of the swipe: edit the item.
onContextMenu={(event) => {
if (!editable) return
event.preventDefault()
openEditor()
}}
style={dragX !== 0 ? { transform: `translateX(${dragX}px)` } : undefined}
className={cn(
'bg-card hover:bg-muted/50 focus-visible:bg-muted/50 relative flex w-full cursor-pointer touch-pan-y items-center gap-4 px-4 py-3.5 text-left outline-none disabled:cursor-default disabled:opacity-60',
@@ -164,8 +206,35 @@ export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }
<span className="text-muted-foreground truncate text-sm">{item.notes}</span>
)}
</span>
{quantity && <span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>}
{quantity && (
<span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>
)}
</button>
</ContextMenuTrigger>
{/* Right-click is the desktop equivalent of the swipes. */}
<ContextMenuContent
onCloseAutoFocus={(event) => {
if (!focusEditorOnMenuClose.current) return
focusEditorOnMenuClose.current = false
event.preventDefault()
quantityInputRef.current?.focus()
}}
>
<ContextMenuItem
onSelect={() => {
focusEditorOnMenuClose.current = true
onEditingChange(true)
}}
>
<PencilIcon />
Editar
</ContextMenuItem>
<ContextMenuItem onSelect={onMove}>
<FolderInputIcon />
Mover a otra lista…
</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
</div>
{editing && (
<ItemEditor

View File

@@ -0,0 +1,94 @@
import type { ListItem } from '@superlist/shared'
import { Link } from '@tanstack/react-router'
import { ChevronRightIcon, ListIcon } from 'lucide-react'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Skeleton } from '@/components/ui/skeleton'
import { useMoveItem } from '@/hooks/use-items'
import { useLists } from '@/hooks/use-lists'
import { ApiError } from '@/lib/api-client'
type MoveItemDialogProps = {
listId: string
/** The item being moved; `null` keeps the dialog closed. */
item: ListItem | null
onClose: () => 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 (
<Dialog open={item !== null} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Mover a otra lista</DialogTitle>
<DialogDescription>
{item ? `Elige a qué lista quieres mover «${item.name}».` : null}
</DialogDescription>
</DialogHeader>
{error ? (
<Alert variant="destructive">
<AlertDescription>
{error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'No pudimos cargar tus listas.'}
</AlertDescription>
</Alert>
) : isPending ? (
<div className="flex flex-col gap-2">
<Skeleton className="h-11 w-full" />
<Skeleton className="h-11 w-full" />
</div>
) : targets.length === 0 ? (
<p className="text-muted-foreground text-sm">
No tienes otras listas.{' '}
<Link to="/lists" className="text-primary underline-offset-4 hover:underline">
Crea una
</Link>{' '}
para poder mover artículos.
</p>
) : (
<ul className="-mx-2 flex flex-col">
{targets.map((list) => (
<li key={list.id}>
<button
type="button"
className="hover:bg-muted focus-visible:bg-muted flex w-full items-center gap-3 rounded-md px-2 py-3 text-left outline-none transition-colors"
onClick={() => {
if (!item) return
moveItem.mutate({
itemId: item.id,
targetListId: list.id,
targetListName: list.name,
})
onClose()
}}
>
<ListIcon className="text-muted-foreground size-5 shrink-0" />
<span className="min-w-0 flex-1 truncate text-base">{list.name}</span>
<ChevronRightIcon className="text-muted-foreground size-4 shrink-0" />
</button>
</li>
))}
</ul>
)}
</DialogContent>
</Dialog>
)
}

View File

@@ -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<typeof ContextMenuPrimitive.Root>) {
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
}
function ContextMenuTrigger({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
return (
<ContextMenuPrimitive.Trigger
data-slot="context-menu-trigger"
className={cn('select-none', className)}
{...props}
/>
)
}
function ContextMenuGroup({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
return <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
}
function ContextMenuPortal({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
return <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
}
function ContextMenuSub({ ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
}
function ContextMenuRadioGroup({
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
return <ContextMenuPrimitive.RadioGroup data-slot="context-menu-radio-group" {...props} />
}
function ContextMenuContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Content> & {
side?: 'top' | 'right' | 'bottom' | 'left'
}) {
return (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
data-slot="context-menu-content"
className={cn(
'z-50 max-h-(--radix-context-menu-content-available-height) min-w-36 origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className,
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
)
}
function ContextMenuItem({
className,
inset,
variant = 'default',
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
inset?: boolean
variant?: 'default' | 'destructive'
}) {
return (
<ContextMenuPrimitive.Item
data-slot="context-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"group/context-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 focus:*:[svg]:text-accent-foreground data-[variant=destructive]:*:[svg]:text-destructive",
className,
)}
{...props}
/>
)
}
function ContextMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.SubTrigger
data-slot="context-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</ContextMenuPrimitive.SubTrigger>
)
}
function ContextMenuSubContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
return (
<ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content"
className={cn(
'z-50 min-w-32 origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className,
)}
{...props}
/>
)
}
function ContextMenuCheckboxItem({
className,
children,
checked,
inset,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.CheckboxItem
data-slot="context-menu-checkbox-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute right-2">
<ContextMenuPrimitive.ItemIndicator>
<CheckIcon />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
)
}
function ContextMenuRadioItem({
className,
children,
inset,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.RadioItem
data-slot="context-menu-radio-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute right-2">
<ContextMenuPrimitive.ItemIndicator>
<CheckIcon />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
)
}
function ContextMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<ContextMenuPrimitive.Label
data-slot="context-menu-label"
data-inset={inset}
className={cn(
'px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7',
className,
)}
{...props}
/>
)
}
function ContextMenuSeparator({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
return (
<ContextMenuPrimitive.Separator
data-slot="context-menu-separator"
className={cn('-mx-1 my-1 h-px bg-border', className)}
{...props}
/>
)
}
function ContextMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="context-menu-shortcut"
className={cn(
'ml-auto text-xs tracking-widest text-muted-foreground group-focus/context-menu-item:text-accent-foreground',
className,
)}
{...props}
/>
)
}
export {
ContextMenu,
ContextMenuCheckboxItem,
ContextMenuContent,
ContextMenuGroup,
ContextMenuItem,
ContextMenuLabel,
ContextMenuPortal,
ContextMenuRadioGroup,
ContextMenuRadioItem,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuTrigger,
}

View File

@@ -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<ListItem>(`/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
})
},
})
}

View File

@@ -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':

View File

@@ -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 }