import { zodResolver } from '@hookform/resolvers/zod' import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react' import { type ClipboardEvent, useEffect, useState } from 'react' import { useForm, useWatch } from 'react-hook-form' import { z } from 'zod' import { ItemInputPreview } from '@/components/items/item-input-preview' import { Field, FieldError } from '@/components/ui/field' import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, } from '@/components/ui/input-group' import { itemLimitError, readItems, useAddItems } from '@/hooks/use-add-items' import { useDictation } from '@/hooks/use-dictation' import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation' import { isPlainItem } from '@/lib/natural-input/parse-item' import { cn } from '@/lib/utils' // 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({ // Not called `name`: iOS offers to autofill a contact into an input named that way. entry: 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() } /** * 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. * * The microphone dictates instead: the transcript is split into items by the API (with * AI) and each one goes through this same flow. "Deshacer" removes the whole dictation. */ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProps) { // 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: { entry: '' }, }) const text = useWatch({ control: form.control, name: 'entry' }) const literal = literalText !== null && literalText === text const restoreText = (source: string, message: string) => { const current = form.getValues('entry').trim() form.setValue('entry', current ? `${current}; ${source}` : source) form.setError('entry', { message }) } // A failed item comes back to the input, and so does a dictation that breaks the limits. const { existing, addItems, addDictation, processing } = useAddItems(listId, { onItemFailed: restoreText, onDictationRejected: (transcript, message) => { form.setValue('entry', transcript) form.setError('entry', { message }) }, }) const dictation = useDictation({ onTranscript: (transcript) => onTranscript(transcript) }) // The keyboard's own microphone (the only one in the installed iOS app) just writes // text: once it has been quiet for a few seconds, that text is added as a dictation. const keyboardDictation = useKeyboardDictation({ onIdle: () => { const dictated = form.getValues('entry').trim() if (dictated && !dictation.listening && !processing) onTranscript(dictated) }, }) const dictating = dictation.listening || processing // The partial transcript is shown in the input while the user talks. useEffect(() => { if (dictation.listening) form.setValue('entry', dictation.interim) }, [dictation.listening, dictation.interim, form]) const preview = readItems(text, literal, existing) const showPreview = !dictating && text.trim() !== '' && (literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate)) // 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) => { keyboardDictation.cancel() const toAdd = readItems(values.entry, literal, existing) const limitError = toAdd.map(itemLimitError).find(Boolean) if (limitError) { form.setError('entry', { message: limitError }) return } form.reset() setLiteralText(null) form.setFocus('entry') addItems(toAdd) }) /** A dictation clears the input and goes through `addDictation`. */ const onTranscript = (transcript: string) => { keyboardDictation.cancel() form.reset() setLiteralText(null) void addDictation(transcript) } // 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('entry', input.value.slice(0, start) + lines + input.value.slice(end), { shouldDirty: true, }) } const micLabel = processing ? 'Procesando el dictado' : dictation.listening ? 'Dejar de escuchar' : 'Dictar productos' return (
{ // Enter while dictating ends the dictation: what was heard goes through its flow. if (!dictation.listening) return onSubmit(event) event.preventDefault() dictation.stop() }} > event.preventDefault()} > {dictation.supported && ( { keyboardDictation.cancel() if (dictation.listening) dictation.stop() else dictation.start() }} > {processing ? ( ) : ( )} )} {dictation.error && (

{dictation.error}

)} {showPreview && ( setLiteralText(value ? text : null)} /> )}
) }