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:
@@ -5,12 +5,14 @@ import { Card } from '@/components/ui/card'
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
|
||||
import type { useUpdateItem } from '@/hooks/use-items'
|
||||
|
||||
import { ItemRow } from './item-row'
|
||||
import { ItemRow, type ItemRowProps } from './item-row'
|
||||
|
||||
type BoughtItemListProps = {
|
||||
items: ListItem[]
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
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
|
||||
* 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 (
|
||||
<Collapsible defaultOpen asChild>
|
||||
<Card className="gap-0 py-0">
|
||||
@@ -34,6 +41,7 @@ export function BoughtItemList({ items, updateItem, savingIds }: BoughtItemListP
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
{...editingProps(item.id)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
106
apps/web/src/components/items/item-editor.tsx
Normal file
106
apps/web/src/components/items/item-editor.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ShoppingBasketIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
@@ -26,6 +27,14 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const savingIds = usePendingItemUpdates(listId)
|
||||
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.
|
||||
useListEvents(listId)
|
||||
@@ -84,6 +93,7 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
isSaving={savingIds.includes(item.id)}
|
||||
{...editingProps(item.id)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
@@ -91,7 +101,12 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
)}
|
||||
|
||||
{boughtToday.length > 0 && (
|
||||
<BoughtItemList items={boughtToday} updateItem={updateItem} savingIds={savingIds} />
|
||||
<BoughtItemList
|
||||
items={boughtToday}
|
||||
updateItem={updateItem}
|
||||
savingIds={savingIds}
|
||||
editingProps={editingProps}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,37 +1,68 @@
|
||||
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 { flushSync } from 'react-dom'
|
||||
|
||||
import { refocusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { EditQuantityDialog } from '@/components/items/edit-quantity-dialog'
|
||||
import { ItemEditor } from '@/components/items/item-editor'
|
||||
import { isOptimisticItem, type useUpdateItem } from '@/hooks/use-items'
|
||||
import { quantityLabel } from '@/lib/items'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
type ItemRowProps = {
|
||||
export type ItemRowProps = {
|
||||
item: ListItem
|
||||
updateItem: ReturnType<typeof useUpdateItem>
|
||||
/** This item's bought state is being saved; only this row waits for it. */
|
||||
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
|
||||
|
||||
/** 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. */
|
||||
export function ItemRow({ item, updateItem, isSaving }: ItemRowProps) {
|
||||
const [editingQuantity, setEditingQuantity] = useState(false)
|
||||
export function ItemRow({ item, updateItem, isSaving, editing, onEditingChange }: ItemRowProps) {
|
||||
const [dragX, setDragX] = useState(0)
|
||||
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.
|
||||
// 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)
|
||||
const quantityInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// A placeholder has no server id yet, so it cannot be toggled or edited.
|
||||
const editable = !isSaving && !isOptimisticItem(item)
|
||||
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>) => {
|
||||
// Mice edit through right-click; only touch drags are tracked here.
|
||||
swiped.current = false
|
||||
if (!editable || event.pointerType === 'mouse') return
|
||||
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
|
||||
// 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 (!swiped.current && Math.abs(dx) <= Math.abs(dy)) return
|
||||
|
||||
if (dx < -SWIPE_THRESHOLD) {
|
||||
swipeStart.current = null
|
||||
swiped.current = true
|
||||
setEditingQuantity(true)
|
||||
}
|
||||
setDragX(dragOffset(dx))
|
||||
swiped.current = dx < -SWIPE_THRESHOLD
|
||||
}
|
||||
|
||||
const handlePointerEnd = () => {
|
||||
const handlePointerUp = () => {
|
||||
const shouldOpen = swipeStart.current !== null && swiped.current
|
||||
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 (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={item.completed}
|
||||
disabled={!editable}
|
||||
onClick={() => {
|
||||
if (swiped.current) {
|
||||
swiped.current = false
|
||||
return
|
||||
}
|
||||
<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"
|
||||
style={{ width: -dragX }}
|
||||
aria-hidden
|
||||
>
|
||||
<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 })
|
||||
// Back to the input, so the next item can be typed right away.
|
||||
refocusNewItemInput()
|
||||
}}
|
||||
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
|
||||
updateItem.mutate({ itemId: item.id, completed: !item.completed })
|
||||
}}
|
||||
onPointerDown={handlePointerDown}
|
||||
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(
|
||||
'flex size-6 shrink-0 items-center justify-center rounded-full border-[1.5px] transition-colors',
|
||||
item.completed
|
||||
? 'bg-primary text-primary-foreground border-primary'
|
||||
: 'border-muted-foreground/45 text-transparent',
|
||||
)}
|
||||
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',
|
||||
'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',
|
||||
// Follows the finger while dragged, then snaps back on release.
|
||||
dragging
|
||||
? 'transition-colors'
|
||||
: 'transition-[background-color,transform] duration-200 motion-reduce:transition-colors',
|
||||
)}
|
||||
>
|
||||
{item.name}
|
||||
</span>
|
||||
{quantity && <span className="text-muted-foreground shrink-0 text-sm">{quantity}</span>}
|
||||
</button>
|
||||
<EditQuantityDialog
|
||||
item={item}
|
||||
open={editingQuantity}
|
||||
onOpenChange={setEditingQuantity}
|
||||
updateItem={updateItem}
|
||||
/>
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-6 shrink-0 items-center justify-center rounded-full border-[1.5px] transition-colors',
|
||||
item.completed
|
||||
? 'bg-primary text-primary-foreground border-primary'
|
||||
: 'border-muted-foreground/45 text-transparent',
|
||||
)}
|
||||
aria-hidden
|
||||
>
|
||||
<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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -79,10 +79,12 @@ export function useCreateItem(listId: string) {
|
||||
|
||||
type UpdateItemInput = {
|
||||
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
|
||||
/** 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
|
||||
/** New notes (`null` clears them); omitted to leave them untouched. */
|
||||
notes?: string | null
|
||||
}
|
||||
|
||||
const updateItemMutationKey = (listId: string) => ['lists', listId, 'items', 'update']
|
||||
@@ -95,16 +97,17 @@ export function useUpdateItem(listId: string) {
|
||||
return useMutation({
|
||||
mutationKey,
|
||||
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.quantity !== undefined) body.quantity = input.quantity
|
||||
if (input.notes !== undefined) body.notes = input.notes
|
||||
|
||||
return apiFetch<ListItem>(`/lists/${listId}/items/${input.itemId}`, {
|
||||
method: 'PATCH',
|
||||
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.
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
|
||||
@@ -120,6 +123,7 @@ export function useUpdateItem(listId: string) {
|
||||
? { completed, boughtAt: completed ? new Date().toISOString() : null }
|
||||
: {}),
|
||||
...(quantity !== undefined ? { quantity: quantity?.trim() || null } : {}),
|
||||
...(notes !== undefined ? { notes: notes?.trim() || null } : {}),
|
||||
}
|
||||
}),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user