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 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(null) const form = useForm({ 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 drops line breaks, so a pasted list keeps one item per line as "; ". const onPaste = (event: ClipboardEvent) => { 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 (
event.preventDefault()} > {showPreview && ( setLiteralText(value ? text : null)} /> )}
) } /** 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) })) }