feat: add dictation

This commit is contained in:
Jose Selesan
2026-10-29 10:29:57 -03:00
parent 2117188bf9
commit 1964d3e08b
10 changed files with 569 additions and 181 deletions

View File

@@ -0,0 +1,88 @@
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { useAddItems } from '@/hooks/use-add-items'
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
type DictateItemsButtonProps = {
listId: string
}
/**
* "Dictar ítems" for an empty list: listens until the user stops it and adds what was
* said through the same flow as the input's microphone (split by the API, undoable).
*/
export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
const [message, setMessage] = useState<string | null>(null)
const { addDictation, processing } = useAddItems(listId, {
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
onDictationRejected: (_, detail) => setMessage(detail),
})
const dictation = useMicrophoneDictation({
onPhrases: async (phrases) => {
const understood = await addDictation(phrases.join('\n'))
if (understood === 0) setMessage(DICTATION_MESSAGES.empty)
},
onError: setMessage,
})
const listening = dictation.status === 'listening'
const busy = dictation.status === 'requesting' || processing
const label = processing
? 'Procesando el dictado'
: dictation.status === 'requesting'
? 'Pidiendo acceso al micrófono'
: listening
? 'Detener dictado'
: 'Dictar ítems'
return (
<div className="flex flex-col items-center gap-2">
<Button
type="button"
variant={listening ? 'default' : 'secondary'}
aria-label={label}
aria-pressed={listening}
disabled={busy}
className="relative rounded-full"
onClick={() => {
setMessage(null)
if (listening) dictation.stop()
else dictation.start()
}}
>
{busy ? (
<Loader2Icon className="animate-spin" />
) : listening ? (
<SquareIcon className="fill-current" />
) : (
<MicIcon />
)}
{listening ? 'Detener dictado' : 'Dictar ítems'}
</Button>
<div aria-live="polite" className="flex flex-col items-center gap-1 text-sm">
{listening && (
<p className="text-primary flex items-center gap-2 font-medium">
<span className="relative flex size-2.5" aria-hidden="true">
<span className="bg-primary absolute inline-flex size-full rounded-full opacity-75 motion-safe:animate-ping" />
<span className="bg-primary relative inline-flex size-2.5 rounded-full" />
</span>
Micrófono activo, te escuchamos
</p>
)}
{listening && dictation.heard && (
<p className="text-muted-foreground max-w-xs">{dictation.heard}</p>
)}
{listening && !dictation.heard && (
<p className="text-muted-foreground">Di «nuevo ítem» o haz una pausa entre artículos.</p>
)}
{message && !listening && <p className="text-destructive max-w-xs">{message}</p>}
</div>
</div>
)
}