Files
superlist/apps/web/src/components/items/create-item-form.tsx
2026-10-29 10:29:57 -03:00

258 lines
9.8 KiB
TypeScript

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<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()
}
/**
* 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<string | null>(null)
const form = useForm<CreateItemValues>({
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 <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('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 (
<form
onSubmit={(event) => {
// Enter while dictating ends the dictation: what was heard goes through its flow.
if (!dictation.listening) return onSubmit(event)
event.preventDefault()
dictation.stop()
}}
>
<Field data-invalid={!!form.formState.errors.entry}>
<InputGroup className="bg-card h-14 rounded-full shadow-xs dark:bg-card">
<InputGroupAddon className="pl-1.5">
<InputGroupButton
type="submit"
variant="ghost"
size="icon-sm"
aria-label="Agregar"
disabled={dictating}
className="text-muted-foreground hover:text-foreground size-11 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>
<InputGroupInput
id={NEW_ITEM_INPUT_ID}
aria-label="Nuevo artículo"
aria-invalid={!!form.formState.errors.entry}
aria-describedby={dictation.error ? 'dictation-error' : undefined}
autoComplete="off"
placeholder={
dictation.listening ? 'Escuchando…' : 'Agregar… ej: 400 g de jamón. Feteado fino'
}
autoFocus={autoFocus}
readOnly={dictating}
className="text-base"
onPaste={onPaste}
onKeyDown={keyboardDictation.onKeyDown}
onInput={keyboardDictation.onInput}
{...form.register('entry', { onChange: dictation.clearError })}
/>
{dictation.supported && (
<InputGroupAddon align="inline-end" className="pr-1.5">
<InputGroupButton
type="button"
variant={dictation.listening ? 'default' : 'secondary'}
size="icon-sm"
aria-label={micLabel}
aria-pressed={dictation.listening}
disabled={processing}
className={cn(
'relative size-11 rounded-full',
dictation.listening &&
'after:bg-primary/30 after:absolute after:inset-0 after:-z-10 after:rounded-full motion-safe:after:animate-ping',
)}
onClick={() => {
keyboardDictation.cancel()
if (dictation.listening) dictation.stop()
else dictation.start()
}}
>
{processing ? (
<Loader2Icon className="size-5 animate-spin" />
) : (
<MicIcon className="size-5" />
)}
</InputGroupButton>
</InputGroupAddon>
)}
</InputGroup>
<FieldError errors={[form.formState.errors.entry]} className="px-5" />
{dictation.error && (
<p id="dictation-error" className="text-muted-foreground px-5 text-sm" aria-live="polite">
{dictation.error}
</p>
)}
{showPreview && (
<ItemInputPreview
items={preview}
literal={literal}
onLiteralChange={(value) => setLiteralText(value ? text : null)}
/>
)}
</Field>
</form>
)
}