From db7cdd5585bebbf8021bdbe5547455e1a98ca9ec Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Tue, 20 Oct 2026 15:02:41 -0300 Subject: [PATCH] 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. --- .../src/modules/lists/items/update/route.ts | 5 +- .../src/modules/lists/items/update/schema.ts | 13 +- .../lists/items/update/use-case.test.ts | 52 ++++++- .../modules/lists/items/update/use-case.ts | 37 +++-- .../components/items/edit-quantity-dialog.tsx | 101 +++++++++++++ apps/web/src/components/items/item-row.tsx | 73 ++++++++- apps/web/src/components/ui/dialog.tsx | 142 ++++++++++++++++++ apps/web/src/hooks/use-items.ts | 39 +++-- apps/web/src/lib/items.test.ts | 24 ++- apps/web/src/lib/items.ts | 16 ++ 10 files changed, 464 insertions(+), 38 deletions(-) create mode 100644 apps/web/src/components/items/edit-quantity-dialog.tsx create mode 100644 apps/web/src/components/ui/dialog.tsx diff --git a/apps/api/src/modules/lists/items/update/route.ts b/apps/api/src/modules/lists/items/update/route.ts index 52290d3..b16466a 100644 --- a/apps/api/src/modules/lists/items/update/route.ts +++ b/apps/api/src/modules/lists/items/update/route.ts @@ -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().patch( '/:itemId', requireSession, @@ -17,12 +17,13 @@ export const updateItemRoute = new Hono().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) diff --git a/apps/api/src/modules/lists/items/update/schema.ts b/apps/api/src/modules/lists/items/update/schema.ts index a2ef76c..e38c200 100644 --- a/apps/api/src/modules/lists/items/update/schema.ts +++ b/apps/api/src/modules/lists/items/update/schema.ts @@ -8,9 +8,14 @@ export const ItemParamsSchema = z.object({ export type ItemParams = z.infer -/** 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 diff --git a/apps/api/src/modules/lists/items/update/use-case.test.ts b/apps/api/src/modules/lists/items/update/use-case.test.ts index f36a361..f394fa3 100644 --- a/apps/api/src/modules/lists/items/update/use-case.test.ts +++ b/apps/api/src/modules/lists/items/update/use-case.test.ts @@ -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> + }) => { 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' }, diff --git a/apps/api/src/modules/lists/items/update/use-case.ts b/apps/api/src/modules/lists/items/update/use-case.ts index e33f39d..3ff4d5f 100644 --- a/apps/api/src/modules/lists/items/update/use-case.ts +++ b/apps/api/src/modules/lists/items/update/use-case.ts @@ -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> { + async execute(input: UpdateItemFields): Promise> { 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) diff --git a/apps/web/src/components/items/edit-quantity-dialog.tsx b/apps/web/src/components/items/edit-quantity-dialog.tsx new file mode 100644 index 0000000..95372a0 --- /dev/null +++ b/apps/web/src/components/items/edit-quantity-dialog.tsx @@ -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 + +type EditQuantityDialogProps = { + item: ListItem + open: boolean + onOpenChange: (open: boolean) => void + updateItem: ReturnType +} + +/** 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({ + 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 ( + + +
+ + Editar cantidad + + Cantidad de «{item.name}». Déjala vacía para quitarla. + + + + + + +
+ + + + + + +
+
+ ) +} diff --git a/apps/web/src/components/items/item-row.tsx b/apps/web/src/components/items/item-row.tsx index 187c428..8188b4e 100644 --- a/apps/web/src/components/items/item-row.tsx +++ b/apps/web/src/components/items/item-row.tsx @@ -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) => { + // 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) => { + 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 (
  • +
  • ) } diff --git a/apps/web/src/components/ui/dialog.tsx b/apps/web/src/components/ui/dialog.tsx new file mode 100644 index 0000000..8c05762 --- /dev/null +++ b/apps/web/src/components/ui/dialog.tsx @@ -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) { + return +} + +function DialogTrigger({ ...props }: React.ComponentProps) { + return +} + +function DialogPortal({ ...props }: React.ComponentProps) { + return +} + +function DialogClose({ ...props }: React.ComponentProps) { + return +} + +function DialogOverlay({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DialogContent({ + className, + children, + showCloseButton = true, + ...props +}: React.ComponentProps & { + showCloseButton?: boolean +}) { + return ( + + + + {children} + {showCloseButton && ( + + + + )} + + + ) +} + +function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
    + ) +} + +function DialogFooter({ + className, + showCloseButton = false, + children, + ...props +}: React.ComponentProps<'div'> & { + showCloseButton?: boolean +}) { + return ( +
    + {children} + {showCloseButton && ( + + + + )} +
    + ) +} + +function DialogTitle({ className, ...props }: React.ComponentProps) { + return ( + + ) +} + +function DialogDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogOverlay, + DialogPortal, + DialogTitle, + DialogTrigger, +} diff --git a/apps/web/src/hooks/use-items.ts b/apps/web/src/hooks/use-items.ts index d42bbe0..b2f8c1f 100644 --- a/apps/web/src/hooks/use-items.ts +++ b/apps/web/src/hooks/use-items.ts @@ -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(`/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(`/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 } diff --git a/apps/web/src/lib/items.test.ts b/apps/web/src/lib/items.test.ts index 3c56e01..6e48f30 100644 --- a/apps/web/src/lib/items.test.ts +++ b/apps/web/src/lib/items.test.ts @@ -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 { 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() + }) +}) diff --git a/apps/web/src/lib/items.ts b/apps/web/src/lib/items.ts index 25829a6..5729770 100644 --- a/apps/web/src/lib/items.ts +++ b/apps/web/src/lib/items.ts @@ -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 +}