feat(web): dictate items from a floating button on lists with items
An empty list dictates from its central card; once it has items that card is gone, so the same flow now has a floating microphone in the bottom-right corner that opens a bottom sheet and starts listening in the same tap. - use-dictate-items extracts the dictation wiring shared by the card and the sheet (split by the API, merged with pending items, undoable toast). - DictationFeedback keeps the live state (listening, phrases heard, errors) the same in both surfaces. - Closing the sheet ends the dictation like "Detener": what was heard is added. - canDictate() centralises the "an iOS home-screen app cannot dictate" rule; the sheet offers "Escribir a mano" there and focuses the composer input.
This commit is contained in:
161
apps/web/src/components/items/dictate-fab.tsx
Normal file
161
apps/web/src/components/items/dictate-fab.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
import { Loader2Icon, MicIcon, SquareIcon, XIcon } from 'lucide-react'
|
||||
import { useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { refocusNewItemInput } from '@/components/items/create-item-form'
|
||||
import { DictationFeedback } from '@/components/items/dictation-feedback'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Sheet,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetTitle,
|
||||
} from '@/components/ui/sheet'
|
||||
import { useDictateItems } from '@/hooks/use-dictate-items'
|
||||
import { DICTATION_MESSAGES } from '@/hooks/use-microphone-dictation'
|
||||
|
||||
type DictateFabProps = {
|
||||
listId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating microphone for a list that already has items. An empty list dictates from
|
||||
* its central card; this repeats that experience on a bottom sheet so the rows stay
|
||||
* on screen. The tap opens the sheet and starts listening in the same gesture, which
|
||||
* is what Safari needs to grant the microphone.
|
||||
*/
|
||||
export function DictateFab({ listId }: DictateFabProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
// "Escribir a mano" moves the focus to the composer once the sheet is gone.
|
||||
const focusInput = useRef(false)
|
||||
|
||||
const { listening, busy, processing, supported, heard, message, start, stop } = useDictateItems(
|
||||
listId,
|
||||
{
|
||||
onFinish: (added) => added && setOpen(false),
|
||||
// Closing the sheet while it listened can still end in a rejection: show it.
|
||||
onMessage: (detail) => {
|
||||
if (!open) toast.error(detail)
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const label = processing
|
||||
? 'Procesando el dictado'
|
||||
: busy
|
||||
? 'Pidiendo acceso al micrófono'
|
||||
: listening
|
||||
? 'Detener dictado'
|
||||
: 'Dictar ítems'
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
aria-label="Dictar ítems"
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
className="fixed right-4 bottom-[calc(4.5rem+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6"
|
||||
onClick={() => {
|
||||
setOpen(true)
|
||||
// Called right in the click, before any state update, so the browser still
|
||||
// treats the microphone request as the user's.
|
||||
start()
|
||||
}}
|
||||
>
|
||||
<MicIcon className="size-6" />
|
||||
</Button>
|
||||
|
||||
<Sheet
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
setOpen(next)
|
||||
// Leaving the sheet ends the dictation: what was heard is delivered, like
|
||||
// "Detener". While the permission is still being asked it just cancels, and
|
||||
// with a request in flight it is a no-op.
|
||||
if (!next) stop()
|
||||
}}
|
||||
>
|
||||
<SheetContent
|
||||
side="bottom"
|
||||
showCloseButton={false}
|
||||
className="max-h-[90dvh] gap-0 overflow-y-auto rounded-t-3xl px-5 pt-3 pb-[calc(1.25rem+env(safe-area-inset-bottom))] sm:mx-auto sm:max-w-lg"
|
||||
onCloseAutoFocus={(event) => {
|
||||
if (!focusInput.current) return
|
||||
focusInput.current = false
|
||||
event.preventDefault()
|
||||
refocusNewItemInput()
|
||||
}}
|
||||
>
|
||||
<div className="bg-muted-foreground/30 mx-auto mb-3 h-1 w-10 rounded-full" aria-hidden />
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<SheetTitle className="text-lg font-semibold">Dictar ítems</SheetTitle>
|
||||
<SheetClose asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
className="size-11 rounded-full"
|
||||
aria-label="Cerrar"
|
||||
>
|
||||
<XIcon className="size-5" />
|
||||
</Button>
|
||||
</SheetClose>
|
||||
</div>
|
||||
<SheetDescription className="text-muted-foreground mt-1">
|
||||
Di los ítems con una pausa entre cada uno y los añadimos a la lista.
|
||||
</SheetDescription>
|
||||
|
||||
<div className="flex flex-col items-center gap-3 pt-6 pb-2">
|
||||
{supported ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant={listening ? 'default' : 'secondary'}
|
||||
aria-label={label}
|
||||
aria-pressed={listening}
|
||||
disabled={busy}
|
||||
className="relative h-12 rounded-full px-6 text-base"
|
||||
onClick={() => {
|
||||
if (listening) stop()
|
||||
else start()
|
||||
}}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2Icon className="size-5 animate-spin" />
|
||||
) : listening ? (
|
||||
<SquareIcon className="size-5 fill-current" />
|
||||
) : (
|
||||
<MicIcon className="size-5" />
|
||||
)}
|
||||
{processing ? 'Procesando…' : listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||
</Button>
|
||||
|
||||
<DictationFeedback listening={listening} heard={heard} message={message} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-muted-foreground max-w-xs text-center text-sm">
|
||||
{DICTATION_MESSAGES.unsupported}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="h-11 rounded-full px-5"
|
||||
onClick={() => {
|
||||
focusInput.current = true
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
Escribir a mano
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { DictationFeedback } from '@/components/items/dictation-feedback'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useAddItems } from '@/hooks/use-add-items'
|
||||
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
||||
import { useDictateItems } from '@/hooks/use-dictate-items'
|
||||
|
||||
type DictateItemsButtonProps = {
|
||||
listId: string
|
||||
@@ -15,30 +13,13 @@ type DictateItemsButtonProps = {
|
||||
* 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 { listening, busy, processing, heard, message, start, stop } = useDictateItems(listId)
|
||||
|
||||
const label = processing
|
||||
? 'Procesando el dictado'
|
||||
: dictation.status === 'requesting'
|
||||
? 'Pidiendo acceso al micrófono'
|
||||
: listening
|
||||
? 'Detener dictado'
|
||||
: 'Dictar ítems'
|
||||
: listening
|
||||
? 'Detener dictado'
|
||||
: 'Dictar ítems'
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
@@ -50,9 +31,8 @@ export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||
disabled={busy}
|
||||
className="relative rounded-full"
|
||||
onClick={() => {
|
||||
setMessage(null)
|
||||
if (listening) dictation.stop()
|
||||
else dictation.start()
|
||||
if (listening) stop()
|
||||
else start()
|
||||
}}
|
||||
>
|
||||
{busy ? (
|
||||
@@ -65,24 +45,7 @@ export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||
{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>
|
||||
<DictationFeedback listening={listening} heard={heard} message={message} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
44
apps/web/src/components/items/dictation-feedback.tsx
Normal file
44
apps/web/src/components/items/dictation-feedback.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
type DictationFeedbackProps = {
|
||||
/** Whether the microphone is listening right now. */
|
||||
listening: boolean
|
||||
/** What has been heard so far, one phrase per item. */
|
||||
heard: string
|
||||
/** Why the last dictation did not deliver anything, in Spanish. */
|
||||
message: string | null
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Live state of a dictation: that we are listening, the phrases heard so far and the
|
||||
* last error. Shared by the empty list's card and the floating button's sheet so both
|
||||
* tell the same thing.
|
||||
*/
|
||||
export function DictationFeedback({
|
||||
listening,
|
||||
heard,
|
||||
message,
|
||||
className,
|
||||
}: DictationFeedbackProps) {
|
||||
return (
|
||||
<div aria-live="polite" className={cn('flex flex-col items-center gap-1 text-sm', className)}>
|
||||
{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 && heard && <p className="text-muted-foreground max-w-xs text-center">{heard}</p>}
|
||||
{listening && !heard && (
|
||||
<p className="text-muted-foreground text-center">
|
||||
Di «nuevo ítem» o haz una pausa entre artículos.
|
||||
</p>
|
||||
)}
|
||||
{message && !listening && <p className="text-destructive max-w-xs text-center">{message}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { ApiError } from '@/lib/api-client'
|
||||
import { splitItems } from '@/lib/items'
|
||||
|
||||
import { BoughtItemList } from './bought-item-list'
|
||||
import { DictateFab } from './dictate-fab'
|
||||
import { DictateItemsButton } from './dictate-items-button'
|
||||
import { ItemRow } from './item-row'
|
||||
import { ItemSheet } from './item-sheet'
|
||||
@@ -109,7 +110,7 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-4 pb-16">
|
||||
{pending.length > 0 && (
|
||||
<Card className="py-0">
|
||||
<ul className="divide-y">
|
||||
@@ -146,6 +147,9 @@ export function ItemList({ listId }: ItemListProps) {
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
|
||||
|
||||
{/* An empty list dictates from its central card; with items, from this button. */}
|
||||
<DictateFab listId={listId} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
78
apps/web/src/hooks/use-dictate-items.ts
Normal file
78
apps/web/src/hooks/use-dictate-items.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { useAddItems } from '@/hooks/use-add-items'
|
||||
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
||||
|
||||
type UseDictateItemsOptions = {
|
||||
/**
|
||||
* The dictation finished: `added` says whether anything made it to the list, so a
|
||||
* sheet can close on success and stay open to show why nothing was added.
|
||||
*/
|
||||
onFinish?: (added: boolean) => void
|
||||
/**
|
||||
* A message was set (an error, or a dictation the API limits rejected). A surface that
|
||||
* may already be closed uses this to show it somewhere else, e.g. as a toast.
|
||||
*/
|
||||
onMessage?: (message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Dictation of items into a list, shared by the empty list's card and the floating
|
||||
* button: the microphone listens until the user stops it and the transcript goes
|
||||
* through `addDictation` (split by the API, undoable). Errors and limits stay in
|
||||
* `message` so each surface can show them where it fits.
|
||||
*/
|
||||
export function useDictateItems(
|
||||
listId: string,
|
||||
{ onFinish, onMessage }: UseDictateItemsOptions = {},
|
||||
) {
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
// A rejected dictation is reported from a callback, so the outcome of `addDictation`
|
||||
// is read from here once it resolves.
|
||||
const rejected = useRef(false)
|
||||
|
||||
const showMessage = (detail: string) => {
|
||||
setMessage(detail)
|
||||
onMessage?.(detail)
|
||||
}
|
||||
|
||||
const { addDictation, processing } = useAddItems(listId, {
|
||||
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
|
||||
onDictationRejected: (_, detail) => {
|
||||
rejected.current = true
|
||||
showMessage(detail)
|
||||
},
|
||||
})
|
||||
|
||||
const dictation = useMicrophoneDictation({
|
||||
onPhrases: async (phrases) => {
|
||||
rejected.current = false
|
||||
const understood = await addDictation(phrases.join('\n'))
|
||||
if (!rejected.current && understood === 0) showMessage(DICTATION_MESSAGES.empty)
|
||||
onFinish?.(understood > 0 && !rejected.current)
|
||||
},
|
||||
onError: (detail) => {
|
||||
showMessage(detail)
|
||||
onFinish?.(false)
|
||||
},
|
||||
})
|
||||
|
||||
const listening = dictation.status === 'listening'
|
||||
|
||||
return {
|
||||
listening,
|
||||
/** Asking for the microphone or splitting the transcript: no new dictation yet. */
|
||||
busy: dictation.status === 'requesting' || processing,
|
||||
processing,
|
||||
supported: dictation.supported,
|
||||
/** What has been heard so far, shown while listening. */
|
||||
heard: dictation.heard,
|
||||
message,
|
||||
start: () => {
|
||||
setMessage(null)
|
||||
dictation.start()
|
||||
},
|
||||
stop: dictation.stop,
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import {
|
||||
canDictate,
|
||||
getSpeechRecognition as getBrowserSpeechRecognition,
|
||||
isIosStandalone,
|
||||
type SpeechRecognitionConstructor,
|
||||
} from '@/lib/speech-recognition'
|
||||
|
||||
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
|
||||
@@ -21,10 +20,8 @@ const ERROR_MESSAGES: Record<string, string> = {
|
||||
* app exposes `webkitSpeechRecognition` but it does not work there, so it counts as
|
||||
* unsupported (the keyboard's own dictation still works).
|
||||
*/
|
||||
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||
if (typeof window === 'undefined' || isIosStandalone()) return null
|
||||
|
||||
return getBrowserSpeechRecognition()
|
||||
function getSpeechRecognition() {
|
||||
return canDictate() ? getBrowserSpeechRecognition() : null
|
||||
}
|
||||
|
||||
type UseDictationOptions = {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
|
||||
import { splitDictation } from '@/lib/natural-input/dictation'
|
||||
import { getSpeechRecognition, type SpeechRecognitionLike } from '@/lib/speech-recognition'
|
||||
import {
|
||||
canDictate,
|
||||
getSpeechRecognition,
|
||||
type SpeechRecognitionLike,
|
||||
} from '@/lib/speech-recognition'
|
||||
|
||||
export const DICTATION_MESSAGES = {
|
||||
denied: 'No tenemos permiso para usar el micrófono. Habilítalo en los ajustes del navegador.',
|
||||
@@ -51,6 +55,7 @@ type UseMicrophoneDictationOptions = {
|
||||
* capture. Unmounting aborts the recognition.
|
||||
*/
|
||||
export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDictationOptions) {
|
||||
const [supported] = useState(() => canDictate())
|
||||
const [status, setStatus] = useState<DictationStatus>('idle')
|
||||
// What has been heard so far, shown while listening.
|
||||
const [heard, setHeard] = useState('')
|
||||
@@ -67,7 +72,7 @@ export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDict
|
||||
const start = useCallback(() => {
|
||||
if (endRef.current) return
|
||||
|
||||
const SpeechRecognition = getSpeechRecognition()
|
||||
const SpeechRecognition = canDictate() ? getSpeechRecognition() : null
|
||||
if (!SpeechRecognition) {
|
||||
callbacksRef.current.onError(DICTATION_MESSAGES.unsupported)
|
||||
return
|
||||
@@ -150,5 +155,5 @@ export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDict
|
||||
/** Stops listening; what was heard so far is delivered. */
|
||||
const stop = useCallback(() => endRef.current?.(true), [])
|
||||
|
||||
return { status, heard, start, stop }
|
||||
return { status, heard, supported, start, stop }
|
||||
}
|
||||
|
||||
@@ -32,3 +32,14 @@ export function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
||||
export function isIosStandalone(): boolean {
|
||||
return (navigator as Navigator & { standalone?: boolean }).standalone === true
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this browser can dictate on its own. An iOS home-screen app exposes
|
||||
* `webkitSpeechRecognition` but it does not work there, so it counts as unsupported
|
||||
* (the keyboard's own dictation still works).
|
||||
*/
|
||||
export function canDictate(): boolean {
|
||||
if (typeof window === 'undefined' || isIosStandalone()) return false
|
||||
|
||||
return getSpeechRecognition() !== null
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user