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>
This commit is contained in:
@@ -1,8 +1,12 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import type { ListItem } from '@superlist/shared'
|
||||
import { PlusIcon, SearchIcon } from 'lucide-react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
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,
|
||||
@@ -10,11 +14,15 @@ import {
|
||||
InputGroupButton,
|
||||
InputGroupInput,
|
||||
} from '@/components/ui/input-group'
|
||||
import { useCreateItem } from '@/hooks/use-items'
|
||||
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(120, 'Máximo 120 caracteres'),
|
||||
name: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'),
|
||||
})
|
||||
|
||||
type CreateItemValues = z.infer<typeof createItemSchema>
|
||||
@@ -47,33 +55,112 @@ export function refocusNewItemInput(): void {
|
||||
document.getElementById(NEW_ITEM_INPUT_ID)?.focus()
|
||||
}
|
||||
|
||||
/** Input to add an item to a list. Submits with Enter or the button. */
|
||||
/** 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: '' },
|
||||
})
|
||||
|
||||
// The input clears at once (the item is added optimistically) so several items
|
||||
// can be typed in a row; if the request fails the text comes back with the error.
|
||||
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')
|
||||
createItem.mutate(values, {
|
||||
onError: (error) => {
|
||||
form.setValue('name', values.name)
|
||||
form.setError('name', {
|
||||
message:
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
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}>
|
||||
@@ -86,9 +173,10 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
aria-label="Nuevo artículo"
|
||||
aria-invalid={!!form.formState.errors.name}
|
||||
autoComplete="off"
|
||||
placeholder="Añadir un artículo…"
|
||||
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">
|
||||
@@ -107,7 +195,23 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
</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) }))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user