Files
superlist/apps/web/src/components/items/create-item-form.tsx
Jose Selesan 5abdb08204 feat(items): read quantity, unit and notes from natural-language input
"400 de jamon" adds Jamón · 400, "Queso crema. Solo Tregar" adds a note,
"leche, pan y 2 pascualinas" adds three items and a pasted list adds one per
line. Units are normalized (½ kg, 1,5 l, 2 paquetes), common accents are
restored, and a pending duplicate gets its quantity summed instead of a new
row. A preview under the input shows the reading, with a way to add the text
as typed. quantityLabel now shows any quantity except a plain "1".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:10:23 -03:00

218 lines
8.2 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import type { ListItem } from '@superlist/shared'
import { PlusIcon, SearchIcon } from 'lucide-react'
import { type ClipboardEvent, useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod'
import { ItemInputPreview, type PreviewItem } from '@/components/items/item-input-preview'
import { Field, FieldError } from '@/components/ui/field'
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
} from '@/components/ui/input-group'
import { isOptimisticItem, useCreateItem, useItems, useUpdateItem } from '@/hooks/use-items'
import { ApiError } from '@/lib/api-client'
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
import { isPlainItem, literalItem, parseItemInput } from '@/lib/natural-input/parse-item'
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
// each one is checked against the API limits once the text is read.
const createItemSchema = z.object({
name: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'),
})
type CreateItemValues = z.infer<typeof createItemSchema>
type CreateItemFormProps = {
listId: string
/** Focus the input when the form mounts, so the user can type right away. */
autoFocus?: boolean
}
/** The input carries this id so it can be focused from outside the form (e.g. by the nav). */
const NEW_ITEM_INPUT_ID = 'new-item-input'
/**
* Puts the cursor in the "add an item" input when the home page is already the one on
* screen (the route does not remount, so nothing else would move the focus). When the
* user is navigating *to* the home page this is a no-op: the input takes the focus as
* soon as it mounts, through `autoFocus`. Either way, tapping "Inicio" always ends with
* the focus in the input — and never with the focus on another page's input.
*
* @param pathname the route the link was clicked from, so only the home input is focused.
*/
export function focusNewItemInput(pathname: string): void {
if (pathname !== '/') return
refocusNewItemInput()
}
/** Puts the cursor back in the "add an item" input of the page on screen, if it has one. */
export function refocusNewItemInput(): void {
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
}
/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */
function itemLimitError(item: PreviewItem): string | null {
if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres`
if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga`
if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga`
return null
}
/**
* Input to add items to a list. Submits with Enter or the button. The text is read
* as natural language ("400 de jamon", "Queso crema. Solo Tregar", "leche, pan y
* 2 pascualinas"), previewed while typing, and an item already pending is added to
* instead of repeated.
*/
export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) {
const createItem = useCreateItem(listId)
const updateItem = useUpdateItem(listId)
const { data: items } = useItems(listId)
// The text the user asked to add as typed; editing it brings the reading back.
const [literalText, setLiteralText] = useState<string | null>(null)
const form = useForm<CreateItemValues>({
resolver: zodResolver(createItemSchema),
defaultValues: { name: '' },
})
const text = useWatch({ control: form.control, name: 'name' })
const literal = literalText !== null && literalText === text
// Placeholders have no server id yet, so they cannot be added to.
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
const preview = readItems(text, literal, existing)
const showPreview =
text.trim() !== '' &&
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
const restoreText = (source: string, message: string) => {
const current = form.getValues('name').trim()
form.setValue('name', current ? `${current}; ${source}` : source)
form.setError('name', { message })
}
// The input clears at once (items are added optimistically) so several items can be
// typed in a row; if a request fails its text comes back with the error.
const onSubmit = form.handleSubmit((values) => {
const toAdd = readItems(values.name, literal, existing)
const limitError = toAdd.map(itemLimitError).find(Boolean)
if (limitError) {
form.setError('name', { message: limitError })
return
}
form.reset()
setLiteralText(null)
form.setFocus('name')
for (const item of toAdd) {
if (item.duplicate) {
const patch = mergeInto(item.duplicate, item)
if (patch.quantity !== undefined || patch.notes !== undefined) {
updateItem.mutate({ itemId: item.duplicate.id, ...patch })
}
toast(
patch.quantity
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
: `«${item.duplicate.name}» ya está en la lista`,
)
continue
}
createItem.mutate(
{ name: item.name, quantity: item.quantity ?? undefined, notes: item.notes ?? undefined },
{
onError: (error) =>
restoreText(
item.source,
error instanceof ApiError
? (error.problem.detail ?? error.problem.title)
: 'No pudimos añadir el artículo.',
),
},
)
}
})
// An <input> drops line breaks, so a pasted list keeps one item per line as "; ".
const onPaste = (event: ClipboardEvent<HTMLInputElement>) => {
const pasted = event.clipboardData.getData('text')
if (!/[\r\n]/.test(pasted)) return
event.preventDefault()
const input = event.currentTarget
const start = input.selectionStart ?? input.value.length
const end = input.selectionEnd ?? start
const lines = pasted
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
.join('; ')
form.setValue('name', input.value.slice(0, start) + lines + input.value.slice(end), {
shouldDirty: true,
})
}
return (
<form onSubmit={onSubmit}>
<Field data-invalid={!!form.formState.errors.name}>
<InputGroup className="bg-card h-14 rounded-full shadow-xs dark:bg-card">
<InputGroupAddon className="pl-5">
<SearchIcon className="size-5" />
</InputGroupAddon>
<InputGroupInput
id={NEW_ITEM_INPUT_ID}
aria-label="Nuevo artículo"
aria-invalid={!!form.formState.errors.name}
autoComplete="off"
placeholder="Ej: 400 g de jamón. Feteado fino"
autoFocus={autoFocus}
className="text-base"
onPaste={onPaste}
{...form.register('name')}
/>
<InputGroupAddon align="inline-end" className="pr-2">
<InputGroupButton
type="submit"
variant="default"
size="icon-sm"
aria-label="Agregar"
className="size-10 rounded-full"
// Tapping the button must not steal the focus from the input: on mobile that
// would close the keyboard between one item and the next.
onMouseDown={(event) => event.preventDefault()}
>
<PlusIcon className="size-5" strokeWidth={2.5} />
</InputGroupButton>
</InputGroupAddon>
</InputGroup>
<FieldError errors={[form.formState.errors.name]} className="px-5" />
{showPreview && (
<ItemInputPreview
items={preview}
literal={literal}
onLiteralChange={(value) => setLiteralText(value ? text : null)}
/>
)}
</Field>
</form>
)
}
/** The items `text` adds, each with the pending item it repeats, if any. */
function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] {
if (!text.trim()) return []
const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text))
return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) }))
}