feat(items): edit quantity and notes inline, with swipe feedback

The PATCH endpoint now also accepts notes. Swiping an item to the left (or
right-clicking it) opens an inline editor below the row for its quantity and
notes, focused on the quantity input, instead of the quantity dialog. The row
slides with the finger during the swipe and snaps back on release, and only
one row edits at a time. Toggling an item no longer moves the focus to the
add-item input, and notes show under the item's name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jose Selesan
2026-10-20 18:30:04 -03:00
parent db7cdd5585
commit d02ab28fc5
10 changed files with 332 additions and 181 deletions

View File

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

View File

@@ -13,9 +13,14 @@ export const UpdateItemSchema = z
.object({ .object({
completed: z.boolean().optional(), completed: z.boolean().optional(),
quantity: z.string().trim().max(40, 'Máximo 40 caracteres').nullable().optional(), quantity: z.string().trim().max(40, 'Máximo 40 caracteres').nullable().optional(),
notes: z.string().trim().max(280, 'Máximo 280 caracteres').nullable().optional(),
}) })
.refine((value) => value.completed !== undefined || value.quantity !== undefined, { .refine(
message: 'Indica al menos un campo para actualizar.', (value) =>
}) value.completed !== undefined || value.quantity !== undefined || value.notes !== undefined,
{
message: 'Indica al menos un campo para actualizar.',
},
)
export type UpdateItemInput = z.infer<typeof UpdateItemSchema> export type UpdateItemInput = z.infer<typeof UpdateItemSchema>

View File

@@ -48,7 +48,7 @@ function createDb(options: { membership: unknown; item: ItemRow | null }) {
// The use case only sends the fields it changes, so the stored row is // 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. // simulated by merging those fields into the row the query returned.
update: async (args: { update: async (args: {
data: Partial<Pick<ItemRow, 'completed' | 'boughtAt' | 'quantity'>> data: Partial<Pick<ItemRow, 'completed' | 'boughtAt' | 'quantity' | 'notes'>>
}) => { }) => {
updates.push(args) updates.push(args)
return { ...options.item, ...args.data } as ItemRow return { ...options.item, ...args.data } as ItemRow
@@ -170,6 +170,45 @@ describe('UpdateItem', () => {
expect(result.value.quantity).toBeNull() expect(result.value.quantity).toBeNull()
}) })
it('updates only the notes, leaving the rest 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',
notes: ' sin lactosa ',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
const data = updates[0] as { data: { notes?: string | null } }
expect(data.data).toEqual({ notes: 'sin lactosa' })
expect(result.value.notes).toBe('sin lactosa')
expect(result.value.quantity).toBe('1 L')
expect(published).toEqual([{ type: 'item.updated', listId: 'list-1', item: result.value }])
})
it('clears the notes 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',
notes: '',
})
expect(result.ok).toBe(true)
if (!result.ok) throw new Error('expected the use case to succeed')
const data = updates[0] as { data: { notes?: string | null } }
expect(data.data).toEqual({ notes: null })
expect(result.value.notes).toBeNull()
})
it('marks the item back to pending, clears boughtAt and publishes item.updated', async () => { it('marks the item back to pending, clears boughtAt and publishes item.updated', async () => {
const { db, updates } = createDb({ const { db, updates } = createDb({
membership: { role: 'collaborator' }, membership: { role: 'collaborator' },

View File

@@ -20,10 +20,12 @@ type UpdateItemFields = {
completed?: boolean completed?: boolean
/** New quantity (`null` or an empty string clears it); when omitted it stays untouched. */ /** New quantity (`null` or an empty string clears it); when omitted it stays untouched. */
quantity?: string | null quantity?: string | null
/** New notes (`null` or an empty string clears them); when omitted they stay untouched. */
notes?: string | null
} }
/** /**
* Updates an item's bought state and/or its quantity. Only members can do it. * Updates an item's bought state, its quantity and/or its notes. Only members can do it.
* `boughtAt` records the moment an item was marked as bought, for future * `boughtAt` records the moment an item was marked as bought, for future
* statistics, and is cleared when the item goes back to pending. * statistics, and is cleared when the item goes back to pending.
*/ */
@@ -50,7 +52,12 @@ export class UpdateItem {
return Failure(problems.notFound('El artículo no existe en esta lista.')) return Failure(problems.notFound('El artículo no existe en esta lista.'))
} }
const data: { completed?: boolean; boughtAt?: Date | null; quantity?: string | null } = {} const data: {
completed?: boolean
boughtAt?: Date | null
quantity?: string | null
notes?: string | null
} = {}
if (input.completed !== undefined) { if (input.completed !== undefined) {
data.completed = input.completed data.completed = input.completed
@@ -61,6 +68,10 @@ export class UpdateItem {
data.quantity = input.quantity?.trim() || null data.quantity = input.quantity?.trim() || null
} }
if (input.notes !== undefined) {
data.notes = input.notes?.trim() || null
}
const updated = await this.db.listItem.update({ const updated = await this.db.listItem.update({
where: { id: item.id }, where: { id: item.id },
data, data,

View File

@@ -5,12 +5,14 @@ import { Card } from '@/components/ui/card'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible' import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import type { useUpdateItem } from '@/hooks/use-items' import type { useUpdateItem } from '@/hooks/use-items'
import { ItemRow } from './item-row' import { ItemRow, type ItemRowProps } from './item-row'
type BoughtItemListProps = { type BoughtItemListProps = {
items: ListItem[] items: ListItem[]
updateItem: ReturnType<typeof useUpdateItem> updateItem: ReturnType<typeof useUpdateItem>
savingIds: string[] 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'>
} }
/** /**
@@ -18,7 +20,12 @@ type BoughtItemListProps = {
* marking an item visibly moves it down; the user can fold it. Tapping an item * marking an item visibly moves it down; the user can fold it. Tapping an item
* here un-buys it and it returns to the pending list. * here un-buys it and it returns to the pending list.
*/ */
export function BoughtItemList({ items, updateItem, savingIds }: BoughtItemListProps) { export function BoughtItemList({
items,
updateItem,
savingIds,
editingProps,
}: BoughtItemListProps) {
return ( return (
<Collapsible defaultOpen asChild> <Collapsible defaultOpen asChild>
<Card className="gap-0 py-0"> <Card className="gap-0 py-0">
@@ -34,6 +41,7 @@ export function BoughtItemList({ items, updateItem, savingIds }: BoughtItemListP
item={item} item={item}
updateItem={updateItem} updateItem={updateItem}
isSaving={savingIds.includes(item.id)} isSaving={savingIds.includes(item.id)}
{...editingProps(item.id)}
/> />
))} ))}
</ul> </ul>

View File

@@ -1,101 +0,0 @@
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

@@ -0,0 +1,106 @@
import { zodResolver } from '@hookform/resolvers/zod'
import type { ListItem } from '@superlist/shared'
import type { Ref } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Field, FieldError } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import type { useUpdateItem } from '@/hooks/use-items'
const itemDetailsSchema = 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'),
notes: z.string().trim().max(280, 'Máximo 280 caracteres'),
})
type ItemDetailsValues = z.infer<typeof itemDetailsSchema>
type ItemEditorProps = {
item: ListItem
updateItem: ReturnType<typeof useUpdateItem>
onClose: () => void
/**
* Receives the quantity input, so the row can focus it synchronously from the
* gesture that opened the editor (iOS only shows the keyboard that way).
*/
quantityInputRef?: Ref<HTMLInputElement>
}
/**
* Inline editor for an item's quantity and notes, shown right below its row.
* Opened by swiping the row to the left or right-clicking it.
*/
export function ItemEditor({ item, updateItem, onClose, quantityInputRef }: ItemEditorProps) {
// The editor only exists while open, so it always starts from the current
// values (including another member's edit received over SSE).
const form = useForm<ItemDetailsValues>({
resolver: zodResolver(itemDetailsSchema),
defaultValues: { quantity: item.quantity ?? '', notes: item.notes ?? '' },
})
const { ref: registerQuantityRef, ...quantityField } = form.register('quantity')
const onSubmit = form.handleSubmit((values) => {
updateItem.mutate(
{ itemId: item.id, quantity: values.quantity || null, notes: values.notes || null },
{
// The row already shows the new values optimistically, so on success
// nothing else is left to do. On error the hook reports the problem
// details and the editor stays open, keeping the typed text for a retry.
onSuccess: onClose,
},
)
})
return (
<form
onSubmit={onSubmit}
onKeyDown={(event) => {
if (event.key !== 'Escape') return
event.preventDefault()
onClose()
}}
className="bg-muted/40 flex flex-col gap-3 border-t px-4 py-3"
>
<Field data-invalid={!!form.formState.errors.quantity}>
<Input
aria-label="Cantidad"
placeholder="Cantidad (ej. 2)"
autoComplete="off"
autoFocus
aria-invalid={!!form.formState.errors.quantity}
className="bg-card"
{...quantityField}
ref={(element) => {
registerQuantityRef(element)
if (typeof quantityInputRef === 'function') quantityInputRef(element)
else if (quantityInputRef) quantityInputRef.current = element
}}
/>
<FieldError errors={[form.formState.errors.quantity]} />
</Field>
<Field data-invalid={!!form.formState.errors.notes}>
<Textarea
aria-label="Notas"
placeholder="Notas (opcional)"
rows={2}
aria-invalid={!!form.formState.errors.notes}
className="bg-card min-h-12"
{...form.register('notes')}
/>
<FieldError errors={[form.formState.errors.notes]} />
</Field>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={onClose}>
Cancelar
</Button>
<Button type="submit" disabled={updateItem.isPending}>
Guardar
</Button>
</div>
</form>
)
}

View File

@@ -1,4 +1,5 @@
import { ShoppingBasketIcon } from 'lucide-react' import { ShoppingBasketIcon } from 'lucide-react'
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'
@@ -26,6 +27,14 @@ export function ItemList({ listId }: ItemListProps) {
const updateItem = useUpdateItem(listId) const updateItem = useUpdateItem(listId)
const savingIds = usePendingItemUpdates(listId) const savingIds = usePendingItemUpdates(listId)
const today = useToday() const today = useToday()
// Only one row shows its inline editor at a time: opening another closes it.
const [editingId, setEditingId] = useState<string | null>(null)
const editingProps = (itemId: string) => ({
editing: editingId === itemId,
onEditingChange: (editing: boolean) =>
setEditingId((current) => (editing ? itemId : current === itemId ? null : current)),
})
// Live updates: another member adds or buys an item and this list refreshes. // Live updates: another member adds or buys an item and this list refreshes.
useListEvents(listId) useListEvents(listId)
@@ -84,6 +93,7 @@ export function ItemList({ listId }: ItemListProps) {
item={item} item={item}
updateItem={updateItem} updateItem={updateItem}
isSaving={savingIds.includes(item.id)} isSaving={savingIds.includes(item.id)}
{...editingProps(item.id)}
/> />
))} ))}
</ul> </ul>
@@ -91,7 +101,12 @@ export function ItemList({ listId }: ItemListProps) {
)} )}
{boughtToday.length > 0 && ( {boughtToday.length > 0 && (
<BoughtItemList items={boughtToday} updateItem={updateItem} savingIds={savingIds} /> <BoughtItemList
items={boughtToday}
updateItem={updateItem}
savingIds={savingIds}
editingProps={editingProps}
/>
)} )}
</div> </div>
) )

View File

@@ -1,37 +1,68 @@
import type { ListItem } from '@superlist/shared' import type { ListItem } from '@superlist/shared'
import { CheckIcon } from 'lucide-react' import { CheckIcon, PencilIcon } from 'lucide-react'
import { type PointerEvent, useRef, useState } from 'react' import { type PointerEvent, useRef, useState } from 'react'
import { flushSync } from 'react-dom'
import { refocusNewItemInput } from '@/components/items/create-item-form' import { ItemEditor } from '@/components/items/item-editor'
import { EditQuantityDialog } from '@/components/items/edit-quantity-dialog'
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items' import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
import { quantityLabel } from '@/lib/items' import { quantityLabel } from '@/lib/items'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
type ItemRowProps = { export type ItemRowProps = {
item: ListItem item: ListItem
updateItem: ReturnType<typeof useUpdateItem> updateItem: ReturnType<typeof useUpdateItem>
/** This item's bought state is being saved; only this row waits for it. */ /** This item's bought state is being saved; only this row waits for it. */
isSaving: boolean isSaving: boolean
/** The inline editor of this row is open (only one row edits at a time). */
editing: boolean
onEditingChange: (editing: boolean) => void
} }
/** Horizontal drag (px) that turns a touch on the row into "edit quantity". */ /** Horizontal drag (px) that turns a touch on the row into "edit the item". */
const SWIPE_THRESHOLD = 48 const SWIPE_THRESHOLD = 48
/** Furthest the row slides while dragged, so it never leaves the card. */
const MAX_DRAG = SWIPE_THRESHOLD * 1.5
/**
* 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`.
*/
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
return -Math.min(resisted, MAX_DRAG)
}
/** A single item row inside a grouped card: tapping it toggles its bought state. */ /** A single item row inside a grouped card: tapping it toggles its bought state. */
export function ItemRow({ item, updateItem, isSaving }: ItemRowProps) { export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }: ItemRowProps) {
const [editingQuantity, setEditingQuantity] = useState(false) const [dragX, setDragX] = useState(0)
const swipeStart = useRef<{ x: number; y: number } | null>(null) const swipeStart = useRef<{ x: number; y: number } | null>(null)
// Set when a swipe opened the editor, so the click that the touch may fire // Set once a drag passes the threshold: releasing the finger then opens the
// right after does not also toggle the bought state. // editor, and the click that the touch may fire right after is ignored.
const swiped = useRef(false) const swiped = useRef(false)
const quantityInputRef = useRef<HTMLInputElement>(null)
// A placeholder has no server id yet, so it cannot be toggled or edited. // A placeholder has no server id yet, so it cannot be toggled or edited.
const editable = !isSaving && !isOptimisticItem(item) const editable = !isSaving && !isOptimisticItem(item)
const quantity = quantityLabel(item.quantity) const quantity = quantityLabel(item.quantity)
/**
* Opens the editor and focuses its first input in the same event handler:
* iOS only shows the keyboard for a focus made synchronously inside a user
* gesture, so the editor is rendered with `flushSync` first.
*/
const openEditor = () => {
flushSync(() => onEditingChange(true))
quantityInputRef.current?.focus()
}
const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => { const handlePointerDown = (event: PointerEvent<HTMLButtonElement>) => {
// Mice edit through right-click; only touch drags are tracked here. // Mice edit through right-click; only touch drags are tracked here.
swiped.current = false
if (!editable || event.pointerType === 'mouse') return if (!editable || event.pointerType === 'mouse') return
swipeStart.current = { x: event.clientX, y: event.clientY } swipeStart.current = { x: event.clientX, y: event.clientY }
} }
@@ -44,74 +75,106 @@ export function ItemRow({ item, updateItem, isSaving }: ItemRowProps) {
const dy = event.clientY - start.y const dy = event.clientY - start.y
// While the movement is mostly vertical the user is scrolling the list, // 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). // so no gesture is decided yet (and `touch-pan-y` lets the page scroll).
if (Math.abs(dx) <= Math.abs(dy)) return if (!swiped.current && Math.abs(dx) <= Math.abs(dy)) return
if (dx < -SWIPE_THRESHOLD) { setDragX(dragOffset(dx))
swipeStart.current = null swiped.current = dx < -SWIPE_THRESHOLD
swiped.current = true
setEditingQuantity(true)
}
} }
const handlePointerEnd = () => { const handlePointerUp = () => {
const shouldOpen = swipeStart.current !== null && swiped.current
swipeStart.current = null swipeStart.current = null
setDragX(0)
if (shouldOpen) openEditor()
} }
const handlePointerCancel = () => {
swipeStart.current = null
swiped.current = false
setDragX(0)
}
const dragging = swipeStart.current !== null && dragX !== 0
return ( return (
<li> <li>
<button <div className="relative overflow-hidden">
type="button" {dragX !== 0 && (
aria-pressed={item.completed} <div
disabled={!editable} className="bg-primary/15 text-primary absolute inset-y-0 right-0 flex items-center justify-center"
onClick={() => { style={{ width: -dragX }}
if (swiped.current) { aria-hidden
swiped.current = false >
return <PencilIcon className="size-5" />
} </div>
)}
<button
type="button"
aria-pressed={item.completed}
aria-expanded={editing}
disabled={!editable}
onClick={() => {
if (swiped.current) {
swiped.current = false
return
}
updateItem.mutate({ itemId: item.id, completed: !item.completed }) updateItem.mutate({ itemId: item.id, completed: !item.completed })
// Back to the input, so the next item can be typed right away. }}
refocusNewItemInput() onPointerDown={handlePointerDown}
}} onPointerMove={handlePointerMove}
onPointerDown={handlePointerDown} onPointerUp={handlePointerUp}
onPointerMove={handlePointerMove} onPointerCancel={handlePointerCancel}
onPointerUp={handlePointerEnd} // Right-click is the desktop equivalent of the swipe: edit the item.
onPointerCancel={handlePointerEnd} onContextMenu={(event) => {
// Right-click is the desktop equivalent of the swipe: edit the quantity. if (!editable) return
onContextMenu={(event) => { event.preventDefault()
if (!editable) return openEditor()
event.preventDefault() }}
setEditingQuantity(true) style={dragX !== 0 ? { transform: `translateX(${dragX}px)` } : undefined}
}}
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( className={cn(
'flex size-6 shrink-0 items-center justify-center rounded-full border-[1.5px] transition-colors', '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',
item.completed // Follows the finger while dragged, then snaps back on release.
? 'bg-primary text-primary-foreground border-primary' dragging
: 'border-muted-foreground/45 text-transparent', ? 'transition-colors'
)} : 'transition-[background-color,transform] duration-200 motion-reduce:transition-colors',
aria-hidden
>
<CheckIcon className="size-3.5" strokeWidth={3} />
</span>
<span
className={cn(
'min-w-0 flex-1 truncate text-base',
item.completed && 'text-muted-foreground line-through',
)} )}
> >
{item.name} <span
</span> className={cn(
{quantity && <span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>} 'flex size-6 shrink-0 items-center justify-center rounded-full border-[1.5px] transition-colors',
</button> item.completed
<EditQuantityDialog ? 'bg-primary text-primary-foreground border-primary'
item={item} : 'border-muted-foreground/45 text-transparent',
open={editingQuantity} )}
onOpenChange={setEditingQuantity} aria-hidden
updateItem={updateItem} >
/> <CheckIcon className="size-3.5" strokeWidth={3} />
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span
className={cn(
'truncate text-base',
item.completed && 'text-muted-foreground line-through',
)}
>
{item.name}
</span>
{item.notes && (
<span className="text-muted-foreground truncate text-sm">{item.notes}</span>
)}
</span>
{quantity && <span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>}
</button>
</div>
{editing && (
<ItemEditor
item={item}
updateItem={updateItem}
onClose={() => onEditingChange(false)}
quantityInputRef={quantityInputRef}
/>
)}
</li> </li>
) )
} }

View File

@@ -79,10 +79,12 @@ export function useCreateItem(listId: string) {
type UpdateItemInput = { type UpdateItemInput = {
itemId: string itemId: string
/** New bought state; omitted when only the quantity is being changed. */ /** New bought state; omitted when only the details are being changed. */
completed?: boolean completed?: boolean
/** New quantity (`null` clears it); omitted when only the bought state changes. */ /** New quantity (`null` clears it); omitted to leave it untouched. */
quantity?: string | null quantity?: string | null
/** New notes (`null` clears them); omitted to leave them untouched. */
notes?: string | null
} }
const updateItemMutationKey = (listId: string) => ['lists', listId, 'items', 'update'] const updateItemMutationKey = (listId: string) => ['lists', listId, 'items', 'update']
@@ -95,16 +97,17 @@ export function useUpdateItem(listId: string) {
return useMutation({ return useMutation({
mutationKey, mutationKey,
mutationFn: (input: UpdateItemInput) => { mutationFn: (input: UpdateItemInput) => {
const body: { completed?: boolean; quantity?: string | null } = {} const body: { completed?: boolean; quantity?: string | null; notes?: string | null } = {}
if (input.completed !== undefined) body.completed = input.completed if (input.completed !== undefined) body.completed = input.completed
if (input.quantity !== undefined) body.quantity = input.quantity if (input.quantity !== undefined) body.quantity = input.quantity
if (input.notes !== undefined) body.notes = input.notes
return apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, { return apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
method: 'PATCH', method: 'PATCH',
body: JSON.stringify(body), body: JSON.stringify(body),
}) })
}, },
onMutate: async ({ itemId, completed, quantity }) => { onMutate: async ({ itemId, completed, quantity, notes }) => {
// Cancel the outgoing refetch so it cannot overwrite our optimistic one. // Cancel the outgoing refetch so it cannot overwrite our optimistic one.
await queryClient.cancelQueries({ queryKey }) await queryClient.cancelQueries({ queryKey })
@@ -120,6 +123,7 @@ export function useUpdateItem(listId: string) {
? { completed, boughtAt: completed ? new Date().toISOString() : null } ? { completed, boughtAt: completed ? new Date().toISOString() : null }
: {}), : {}),
...(quantity !== undefined ? { quantity: quantity?.trim() || null } : {}), ...(quantity !== undefined ? { quantity: quantity?.trim() || null } : {}),
...(notes !== undefined ? { notes: notes?.trim() || null } : {}),
} }
}), }),
) )