diff --git a/apps/web/src/components/items/dictate-fab.tsx b/apps/web/src/components/items/dictate-fab.tsx new file mode 100644 index 0000000..0161bbd --- /dev/null +++ b/apps/web/src/components/items/dictate-fab.tsx @@ -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 ( + <> + + + { + 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() + }} + > + { + if (!focusInput.current) return + focusInput.current = false + event.preventDefault() + refocusNewItemInput() + }} + > +
+
+ Dictar ítems + + + +
+ + Di los ítems con una pausa entre cada uno y los añadimos a la lista. + + +
+ {supported ? ( + <> + + + + + ) : ( + <> +

+ {DICTATION_MESSAGES.unsupported} +

+ + + )} +
+ + + + ) +} diff --git a/apps/web/src/components/items/dictate-items-button.tsx b/apps/web/src/components/items/dictate-items-button.tsx index 53b11a5..1c8e1d0 100644 --- a/apps/web/src/components/items/dictate-items-button.tsx +++ b/apps/web/src/components/items/dictate-items-button.tsx @@ -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(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 (
@@ -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'} -
- {listening && ( -

-

- )} - {listening && dictation.heard && ( -

{dictation.heard}

- )} - {listening && !dictation.heard && ( -

Di «nuevo ítem» o haz una pausa entre artículos.

- )} - {message && !listening &&

{message}

} -
+
) } diff --git a/apps/web/src/components/items/dictation-feedback.tsx b/apps/web/src/components/items/dictation-feedback.tsx new file mode 100644 index 0000000..3b7757f --- /dev/null +++ b/apps/web/src/components/items/dictation-feedback.tsx @@ -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 ( +
+ {listening && ( +

+

+ )} + {listening && heard &&

{heard}

} + {listening && !heard && ( +

+ Di «nuevo ítem» o haz una pausa entre artículos. +

+ )} + {message && !listening &&

{message}

} +
+ ) +} diff --git a/apps/web/src/components/items/item-list.tsx b/apps/web/src/components/items/item-list.tsx index c2ce684..8fbfab7 100644 --- a/apps/web/src/components/items/item-list.tsx +++ b/apps/web/src/components/items/item-list.tsx @@ -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 ( -
+
{pending.length > 0 && (
    @@ -146,6 +147,9 @@ export function ItemList({ listId }: ItemListProps) { onDelete={handleDelete} /> setMovingItem(null)} /> + + {/* An empty list dictates from its central card; with items, from this button. */} +
) } diff --git a/apps/web/src/hooks/use-dictate-items.ts b/apps/web/src/hooks/use-dictate-items.ts new file mode 100644 index 0000000..6d5e1fe --- /dev/null +++ b/apps/web/src/hooks/use-dictate-items.ts @@ -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(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, + } +} diff --git a/apps/web/src/hooks/use-dictation.ts b/apps/web/src/hooks/use-dictation.ts index 6e74039..1e022c5 100644 --- a/apps/web/src/hooks/use-dictation.ts +++ b/apps/web/src/hooks/use-dictation.ts @@ -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 = { * 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 = { diff --git a/apps/web/src/hooks/use-microphone-dictation.ts b/apps/web/src/hooks/use-microphone-dictation.ts index 37a36ed..04e7fcf 100644 --- a/apps/web/src/hooks/use-microphone-dictation.ts +++ b/apps/web/src/hooks/use-microphone-dictation.ts @@ -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('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 } } diff --git a/apps/web/src/lib/speech-recognition.ts b/apps/web/src/lib/speech-recognition.ts index 0d798f6..b60ee15 100644 --- a/apps/web/src/lib/speech-recognition.ts +++ b/apps/web/src/lib/speech-recognition.ts @@ -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 +}