feat(items): edit an item's quantity by swiping or right-clicking it

The PATCH endpoint now accepts quantity alongside completed (at least one
field is required), and the row shows the quantity only when its leading
number is above one. A small dialog edits it, opened by a left swipe on
touch or by right-clicking the row on desktop.
This commit is contained in:
Jose Selesan
2026-10-20 15:02:41 -03:00
parent 247ea903a9
commit db7cdd5585
10 changed files with 464 additions and 38 deletions

View File

@@ -9,7 +9,7 @@ import type { AppEnv } from '@/types'
import { ItemParamsSchema, UpdateItemSchema } from './schema'
import { UpdateItem } from './use-case'
/** PATCH /lists/:listId/items/:itemId — marks an item as bought or pending. */
/** PATCH /lists/:listId/items/:itemId — updates an item's bought state and/or quantity. */
export const updateItemRoute = new Hono<AppEnv>().patch(
'/:itemId',
requireSession,
@@ -17,12 +17,13 @@ export const updateItemRoute = new Hono<AppEnv>().patch(
validate.json(UpdateItemSchema),
async (c) => {
const { listId, itemId } = c.req.valid('param')
const { completed } = c.req.valid('json')
const { completed, quantity } = c.req.valid('json')
const result = await new UpdateItem(prisma).execute({
listId,
itemId,
userId: c.get('user').id,
completed,
quantity,
})
return resultJson(c, result)

View File

@@ -8,9 +8,14 @@ export const ItemParamsSchema = z.object({
export type ItemParams = z.infer<typeof ItemParamsSchema>
/** Body of `PATCH /lists/:listId/items/:itemId`. */
export const UpdateItemSchema = z.object({
completed: z.boolean(),
})
/** Body of `PATCH /lists/:listId/items/:itemId` — at least one field is required. */
export const UpdateItemSchema = z
.object({
completed: z.boolean().optional(),
quantity: z.string().trim().max(40, 'Máximo 40 caracteres').nullable().optional(),
})
.refine((value) => value.completed !== undefined || value.quantity !== undefined, {
message: 'Indica al menos un campo para actualizar.',
})
export type UpdateItemInput = z.infer<typeof UpdateItemSchema>

View File

@@ -45,9 +45,13 @@ function createDb(options: { membership: unknown; item: ItemRow | null }) {
},
listItem: {
findFirst: async () => options.item,
update: async (args: { data: { completed: boolean; boughtAt: Date | null } }) => {
// The use case only sends the fields it changes, so the stored row is
// simulated by merging those fields into the row the query returned.
update: async (args: {
data: Partial<Pick<ItemRow, 'completed' | 'boughtAt' | 'quantity'>>
}) => {
updates.push(args)
return itemRow(args.data.completed, args.data.boughtAt)
return { ...options.item, ...args.data } as ItemRow
},
},
}
@@ -122,6 +126,50 @@ describe('UpdateItem', () => {
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
})
it('updates only the quantity, leaving the bought state untouched', async () => {
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
const { events, published } = createBus()
const result = await new UpdateItem(db, events).execute({
listId: 'list-1',
itemId: 'item-1',
userId: 'user-1',
quantity: ' 3 ',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
expect(updates).toHaveLength(1)
const data = updates[0] as {
data: { completed?: boolean; boughtAt?: Date | null; quantity?: string | null }
}
expect(data.data).toEqual({ quantity: '3' })
expect(data.data.completed).toBeUndefined()
expect(result.value.completed).toBe(false)
expect(result.value.quantity).toBe('3')
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
})
it('clears the quantity when an empty value is sent', async () => {
const { db, updates } = createDb({ membership: { role: 'owner' }, item: itemRow(false, null) })
const { events } = createBus()
const result = await new UpdateItem(db, events).execute({
listId: 'list-1',
itemId: 'item-1',
userId: 'user-1',
quantity: '',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
const data = updates[0] as { data: { quantity?: string | null } }
expect(data.data).toEqual({ quantity: null })
expect(result.value.quantity).toBeNull()
})
it('marks the item back to pending, clears boughtAt and publishes item.updated', async () => {
const { db, updates } = createDb({
membership: { role: 'collaborator' },

View File

@@ -12,9 +12,19 @@ import type { Database } from '@/lib/prisma'
import { toListItem } from '../serialize'
type UpdateItemFields = {
listId: string
itemId: string
userId: string
/** New bought state; when omitted the state stays untouched. */
completed?: boolean
/** New quantity (`null` or an empty string clears it); when omitted it stays untouched. */
quantity?: string | null
}
/**
* Marks an item as bought (or back to pending). Only members can do it.
* `boughtAt` records the moment it was marked as bought, for future
* Updates an item's bought state and/or its quantity. Only members can do it.
* `boughtAt` records the moment an item was marked as bought, for future
* statistics, and is cleared when the item goes back to pending.
*/
export class UpdateItem {
@@ -23,12 +33,7 @@ export class UpdateItem {
private readonly events: ListEvents = listEvents,
) {}
async execute(input: {
listId: string
itemId: string
userId: string
completed: boolean
}): Promise<Result<ListItem, ProblemDetails>> {
async execute(input: UpdateItemFields): Promise<Result<ListItem, ProblemDetails>> {
const membership = await this.db.shoppingListMember.findUnique({
where: { listId_userId: { listId: input.listId, userId: input.userId } },
})
@@ -45,12 +50,20 @@ export class UpdateItem {
return Failure(problems.notFound('El artículo no existe en esta lista.'))
}
const data: { completed?: boolean; boughtAt?: Date | null; quantity?: string | null } = {}
if (input.completed !== undefined) {
data.completed = input.completed
data.boughtAt = input.completed ? new Date() : null
}
if (input.quantity !== undefined) {
data.quantity = input.quantity?.trim() || null
}
const updated = await this.db.listItem.update({
where: { id: item.id },
data: {
completed: input.completed,
boughtAt: input.completed ? new Date() : null,
},
data,
})
const dto = toListItem(updated)

View File

@@ -0,0 +1,101 @@
import { zodResolver } from '@hookform/resolvers/zod'
import type { ListItem } from '@superlist/shared'
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Field, FieldError } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import type { useUpdateItem } from '@/hooks/use-items'
const quantitySchema = z.object({
// Free text so "2 kg" works; the API trims it and an empty value clears it.
quantity: z.string().trim().max(40, 'Máximo 40 caracteres'),
})
type QuantityValues = z.infer<typeof quantitySchema>
type EditQuantityDialogProps = {
item: ListItem
open: boolean
onOpenChange: (open: boolean) => void
updateItem: ReturnType<typeof useUpdateItem>
}
/** Editor for an item's quantity: opened by swiping the row or right-clicking it. */
export function EditQuantityDialog({
item,
open,
onOpenChange,
updateItem,
}: EditQuantityDialogProps) {
const form = useForm<QuantityValues>({
resolver: zodResolver(quantitySchema),
defaultValues: { quantity: item.quantity ?? '' },
})
// The dialog always opens showing the current value, which may have changed
// while it was closed (another member's edit over SSE, or a failed optimistic
// update rolling back).
useEffect(() => {
if (open) form.reset({ quantity: item.quantity ?? '' })
}, [open, item.quantity, form])
const onSubmit = form.handleSubmit((values) => {
updateItem.mutate(
{ itemId: item.id, quantity: values.quantity || null },
{
// The row already shows the new value optimistically, so on success
// nothing else is left to do. On error the hook reports the problem
// details and this dialog stays open, keeping the typed text for a retry.
onSuccess: () => onOpenChange(false),
},
)
})
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-xs">
<form id="edit-quantity-form" onSubmit={onSubmit}>
<DialogHeader>
<DialogTitle>Editar cantidad</DialogTitle>
<DialogDescription>
Cantidad de «{item.name}». Déjala vacía para quitarla.
</DialogDescription>
</DialogHeader>
<Field data-invalid={!!form.formState.errors.quantity} className="mt-4">
<Input
aria-label="Cantidad"
placeholder="Ej. 2"
autoComplete="off"
autoFocus
data-invalid={!!form.formState.errors.quantity}
{...form.register('quantity')}
/>
<FieldError errors={[form.formState.errors.quantity]} />
</Field>
</form>
<DialogFooter>
<DialogClose asChild>
<Button type="button" variant="outline">
Cancelar
</Button>
</DialogClose>
<Button type="submit" form="edit-quantity-form" disabled={updateItem.isPending}>
Guardar
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View File

@@ -1,8 +1,11 @@
import type { ListItem } from '@superlist/shared'
import { CheckIcon } from 'lucide-react'
import { type PointerEvent, useRef, useState } from 'react'
import { refocusNewItemInput } from '@/components/items/create-item-form'
import { EditQuantityDialog } from '@/components/items/edit-quantity-dialog'
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
import { quantityLabel } from '@/lib/items'
import { cn } from '@/lib/utils'
type ItemRowProps = {
@@ -12,21 +15,75 @@ type ItemRowProps = {
isSaving: boolean
}
/** Horizontal drag (px) that turns a touch on the row into "edit quantity". */
const SWIPE_THRESHOLD = 48
/** A single item row inside a grouped card: tapping it toggles its bought state. */
export function ItemRow({ item, updateItem, isSaving }: ItemRowProps) {
const [editingQuantity, setEditingQuantity] = useState(false)
const swipeStart = useRef<{ x: number; y: number } | null>(null)
// Set when a swipe opened the editor, so the click that the touch may fire
// right after does not also toggle the bought state.
const swiped = useRef(false)
// A placeholder has no server id yet, so it cannot be toggled or edited.
const editable = !isSaving && !isOptimisticItem(item)
const quantity = quantityLabel(item.quantity)
const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => {
// Mice edit through right-click; only touch drags are tracked here.
if (!editable || event.pointerType === 'mouse') return
swipeStart.current = { x: event.clientX, y: event.clientY }
}
const handlePointerMove = (event: PointerEvent<HTMLButtonElement>) => {
const start = swipeStart.current
if (!start) return
const dx = event.clientX - start.x
const dy = event.clientY - start.y
// While the movement is mostly vertical the user is scrolling the list,
// so no gesture is decided yet (and `touch-pan-y` lets the page scroll).
if (Math.abs(dx) <= Math.abs(dy)) return
if (dx < -SWIPE_THRESHOLD) {
swipeStart.current = null
swiped.current = true
setEditingQuantity(true)
}
}
const handlePointerEnd = () => {
swipeStart.current = null
}
return (
<li>
<button
type="button"
aria-pressed={item.completed}
// A placeholder has no server id yet, so it cannot be toggled.
disabled={isSaving || isOptimisticItem(item)}
disabled={!editable}
onClick={() => {
if (swiped.current) {
swiped.current = false
return
}
updateItem.mutate({ itemId: item.id, completed: !item.completed })
// Back to the input, so the next item can be typed right away.
refocusNewItemInput()
}}
className="hover:bg-muted/50 focus-visible:bg-muted/50 flex w-full cursor-pointer items-center gap-4 px-4 py-3.5 text-left outline-none transition-colors disabled:cursor-default disabled:opacity-60"
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerEnd}
onPointerCancel={handlePointerEnd}
// Right-click is the desktop equivalent of the swipe: edit the quantity.
onContextMenu={(event) => {
if (!editable) return
event.preventDefault()
setEditingQuantity(true)
}}
className="hover:bg-muted/50 focus-visible:bg-muted/50 flex w-full cursor-pointer touch-pan-y items-center gap-4 px-4 py-3.5 text-left outline-none transition-colors disabled:cursor-default disabled:opacity-60"
>
<span
className={cn(
@@ -47,10 +104,14 @@ export function ItemRow({ item, updateItem, isSaving }: ItemRowProps) {
>
{item.name}
</span>
{item.quantity && (
<span className="text-muted-foreground shrink-0 text-sm">{item.quantity}</span>
)}
{quantity && <span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>}
</button>
<EditQuantityDialog
item={item}
open={editingQuantity}
onOpenChange={setEditingQuantity}
updateItem={updateItem}
/>
</li>
)
}

View File

@@ -0,0 +1,142 @@
import { cn } from 'cn'
import { XIcon } from 'lucide-react'
import { Dialog as DialogPrimitive } from 'radix-ui'
import * as React from 'react'
import { Button } from '@/components/ui/button'
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
'fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
className,
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
'fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm 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}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close data-slot="dialog-close" asChild>
<Button variant="ghost" className="absolute top-2 right-2" size="icon-sm">
<XIcon />
<span className="sr-only">Close</span>
</Button>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div data-slot="dialog-header" className={cn('flex flex-col gap-2', className)} {...props} />
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<'div'> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
'-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end',
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn('font-heading text-base leading-none font-medium', className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
'text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground',
className,
)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -77,7 +77,13 @@ export function useCreateItem(listId: string) {
})
}
type UpdateItemInput = { itemId: string; completed: boolean }
type UpdateItemInput = {
itemId: string
/** New bought state; omitted when only the quantity is being changed. */
completed?: boolean
/** New quantity (`null` clears it); omitted when only the bought state changes. */
quantity?: string | null
}
const updateItemMutationKey = (listId: string) => ['lists', listId, 'items', 'update']
@@ -88,23 +94,34 @@ export function useUpdateItem(listId: string) {
return useMutation({
mutationKey,
mutationFn: (input: UpdateItemInput) =>
apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
mutationFn: (input: UpdateItemInput) => {
const body: { completed?: boolean; quantity?: string | null } = {}
if (input.completed !== undefined) body.completed = input.completed
if (input.quantity !== undefined) body.quantity = input.quantity
return apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
method: 'PATCH',
body: JSON.stringify({ completed: input.completed }),
}),
onMutate: async ({ itemId, completed }) => {
body: JSON.stringify(body),
})
},
onMutate: async ({ itemId, completed, quantity }) => {
// 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) =>
item.id === itemId
? { ...item, completed, boughtAt: completed ? new Date().toISOString() : null }
: item,
),
items?.map((item) => {
if (item.id !== itemId) return item
return {
...item,
...(completed !== undefined
? { completed, boughtAt: completed ? new Date().toISOString() : null }
: {}),
...(quantity !== undefined ? { quantity: quantity?.trim() || null } : {}),
}
}),
)
return { previous }

View File

@@ -1,7 +1,7 @@
import type { ListItem } from '@superlist/shared'
import { describe, expect, it } from 'vitest'
import { splitItems } from './items'
import { quantityLabel, splitItems } from './items'
function item(overrides: Partial<ListItem>): ListItem {
return {
@@ -85,3 +85,25 @@ describe('splitItems', () => {
expect(boughtToday).toEqual([])
})
})
describe('quantityLabel', () => {
it('shows quantities above one, with their unit when present', () => {
expect(quantityLabel('2')).toBe('2')
expect(quantityLabel('2 kg')).toBe('2 kg')
expect(quantityLabel('1,5')).toBe('1,5')
expect(quantityLabel(' 3 ')).toBe('3')
})
it('hides empty, absent and exactly-one quantities', () => {
expect(quantityLabel(null)).toBeNull()
expect(quantityLabel('')).toBeNull()
expect(quantityLabel('1')).toBeNull()
expect(quantityLabel('1 kg')).toBeNull()
expect(quantityLabel('0,5')).toBeNull()
})
it('hides quantities whose text does not start with a number', () => {
expect(quantityLabel('un par')).toBeNull()
expect(quantityLabel('kg')).toBeNull()
})
})

View File

@@ -38,3 +38,19 @@ export function splitItems(items: ListItem[], now: Date): SplitItems {
return { pending, boughtToday }
}
/**
* The quantity to show at the right of an item's name, or `null` when it must
* stay hidden. Only quantities above one earn their place in the row, so a
* plain "1" does not add noise: the leading number of the string is parsed
* ("2" → 2, "2 kg" → 2, "0,5" → 0.5) and anything without one is hidden.
*/
export function quantityLabel(quantity: string | null): string | null {
if (!quantity) return null
const trimmed = quantity.trim()
const leadingNumber = /^(\d+(?:[.,]\d+)?)/.exec(trimmed)
if (!leadingNumber) return null
return Number.parseFloat(leadingNumber[1].replace(',', '.')) > 1 ? trimmed : null
}