feat(items): voice dictation with Gemma 4 and a reworked list UI
Dictation: a mic button in the add field uses the Web Speech API (es-AR) and
shows the partial transcript in the input. POST /api/voice/split asks Gemma 4
(Gemini API, plain fetch) to split the sentence into one string per item,
written the way the existing parser reads typed text; each string then goes
through the usual add flow. The endpoint never fails because of the model:
missing key, timeout, 429 or invalid JSON fall back to splitting on commas,
semicolons, " y " and " e ". A toast offers "Deshacer" for the whole dictation;
if the request fails, the transcript is added as a single item.
UI: "+" instead of the search icon, quantity tags ("2 L", "×12", "1 kg"), the
list name with a list switcher and the pending/bought count in the header,
"Comprados (N)" folded by default, and a bottom sheet to edit name, quantity
(− / + and unit), note and delete. PATCH items now accepts a name.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
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 { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react'
|
||||
import { type ClipboardEvent, useEffect, useRef, useState } from 'react'
|
||||
import { useForm, useWatch } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
@@ -14,10 +14,19 @@ import {
|
||||
InputGroupButton,
|
||||
InputGroupInput,
|
||||
} from '@/components/ui/input-group'
|
||||
import { isOptimisticItem, useCreateItem, useItems, useUpdateItem } from '@/hooks/use-items'
|
||||
import { useDictation } from '@/hooks/use-dictation'
|
||||
import {
|
||||
isOptimisticItem,
|
||||
useCreateItem,
|
||||
useItems,
|
||||
useRemoveItems,
|
||||
useUpdateItem,
|
||||
} from '@/hooks/use-items'
|
||||
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
||||
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'
|
||||
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.
|
||||
@@ -33,6 +42,9 @@ type CreateItemFormProps = {
|
||||
autoFocus?: boolean
|
||||
}
|
||||
|
||||
/** How long the "Deshacer" of a dictation stays on screen. */
|
||||
const DICTATION_UNDO_MS = 8000
|
||||
|
||||
/** 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'
|
||||
|
||||
@@ -64,15 +76,28 @@ function itemLimitError(item: PreviewItem): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
/** What adding a batch of items did, so a dictation can be undone. */
|
||||
type AddedItems = {
|
||||
/** Ids of the items created (failed ones are left out). */
|
||||
created: Promise<string[]>
|
||||
/** The previous quantity/notes of the pending items that were added to. */
|
||||
merged: { itemId: string; quantity: string | null; notes: string | null }[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Input to add items to a list. Submits with Enter or the button. The text is read
|
||||
* 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) {
|
||||
const createItem = useCreateItem(listId)
|
||||
const updateItem = useUpdateItem(listId)
|
||||
const removeItems = useRemoveItems(listId)
|
||||
const voiceSplit = useVoiceSplit()
|
||||
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)
|
||||
@@ -86,8 +111,22 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
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))
|
||||
// A dictation finishes after a request: by then the list may have changed.
|
||||
const existingRef = useRef(existing)
|
||||
existingRef.current = existing
|
||||
|
||||
const dictation = useDictation({ onTranscript: (transcript) => void addDictation(transcript) })
|
||||
const processing = voiceSplit.isPending
|
||||
const dictating = dictation.listening || processing
|
||||
|
||||
// The partial transcript is shown in the input while the user talks.
|
||||
useEffect(() => {
|
||||
if (dictation.listening) form.setValue('name', 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))
|
||||
|
||||
@@ -97,6 +136,58 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
form.setError('name', { message })
|
||||
}
|
||||
|
||||
/** Adds the items, or adds to the pending ones they repeat. A failed one comes back to the input. */
|
||||
const addItems = (toAdd: PreviewItem[]): AddedItems => {
|
||||
const created: Promise<string | null>[] = []
|
||||
const merged: AddedItems['merged'] = []
|
||||
|
||||
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 })
|
||||
merged.push({
|
||||
itemId: item.duplicate.id,
|
||||
quantity: item.duplicate.quantity,
|
||||
notes: item.duplicate.notes,
|
||||
})
|
||||
}
|
||||
toast(
|
||||
patch.quantity
|
||||
? `Se sumó a «${item.duplicate.name}» (${patch.quantity})`
|
||||
: `«${item.duplicate.name}» ya está en la lista`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
created.push(
|
||||
createItem
|
||||
.mutateAsync({
|
||||
name: item.name,
|
||||
quantity: item.quantity ?? undefined,
|
||||
notes: item.notes ?? undefined,
|
||||
})
|
||||
.then(
|
||||
(createdItem) => createdItem.id,
|
||||
(error) => {
|
||||
restoreText(
|
||||
item.source,
|
||||
error instanceof ApiError
|
||||
? (error.problem.detail ?? error.problem.title)
|
||||
: 'No pudimos añadir el artículo.',
|
||||
)
|
||||
return null
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
created: Promise.all(created).then((ids) => ids.filter((id): id is string => id !== null)),
|
||||
merged,
|
||||
}
|
||||
}
|
||||
|
||||
// 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) => {
|
||||
@@ -112,35 +203,52 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
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.',
|
||||
),
|
||||
},
|
||||
)
|
||||
}
|
||||
addItems(toAdd)
|
||||
})
|
||||
|
||||
/**
|
||||
* The API splits the transcript into one string per item and each one is read by the
|
||||
* usual parser. If the request fails, the whole transcript is added as a single item.
|
||||
*/
|
||||
const addDictation = async (transcript: string) => {
|
||||
form.reset()
|
||||
setLiteralText(null)
|
||||
|
||||
let toAdd: PreviewItem[]
|
||||
try {
|
||||
const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript })
|
||||
toAdd = readItems(spoken.join('; '), false, existingRef.current)
|
||||
} catch {
|
||||
toAdd = readItems(transcript, true, existingRef.current)
|
||||
}
|
||||
|
||||
if (toAdd.length === 0) return
|
||||
|
||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||
if (limitError) {
|
||||
form.setValue('name', transcript)
|
||||
form.setError('name', { message: limitError })
|
||||
return
|
||||
}
|
||||
|
||||
const { created, merged } = addItems(toAdd)
|
||||
const createdIds = await created
|
||||
const count = createdIds.length + merged.length
|
||||
if (count === 0) return
|
||||
|
||||
toast(`Se ${count === 1 ? 'agregó 1 producto' : `agregaron ${count} productos`}`, {
|
||||
// Longer than a plain toast: the user has to check what was understood first.
|
||||
duration: DICTATION_UNDO_MS,
|
||||
action: {
|
||||
label: 'Deshacer',
|
||||
onClick: () => {
|
||||
void removeItems(createdIds)
|
||||
for (const previous of merged) updateItem.mutate(previous)
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// 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')
|
||||
@@ -161,31 +269,24 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
})
|
||||
}
|
||||
|
||||
const micLabel = processing
|
||||
? 'Procesando el dictado'
|
||||
: dictation.listening
|
||||
? 'Dejar de escuchar'
|
||||
: 'Dictar productos'
|
||||
|
||||
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">
|
||||
<InputGroupAddon className="pl-1.5">
|
||||
<InputGroupButton
|
||||
type="submit"
|
||||
variant="default"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Agregar"
|
||||
className="size-10 rounded-full"
|
||||
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()}
|
||||
@@ -193,8 +294,52 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
||||
<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.name}
|
||||
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}
|
||||
{...form.register('name', { 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={dictation.listening ? dictation.stop : dictation.start}
|
||||
>
|
||||
{processing ? (
|
||||
<Loader2Icon className="size-5 animate-spin" />
|
||||
) : (
|
||||
<MicIcon className="size-5" />
|
||||
)}
|
||||
</InputGroupButton>
|
||||
</InputGroupAddon>
|
||||
)}
|
||||
</InputGroup>
|
||||
<FieldError errors={[form.formState.errors.name]} 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}
|
||||
|
||||
Reference in New Issue
Block a user