From 1964d3e08b601fa019df22f05f7c141f3c6d13ee Mon Sep 17 00:00:00 2001 From: Jose Selesan Date: Thu, 29 Oct 2026 10:29:57 -0300 Subject: [PATCH] feat: add dictation --- .claude/launch.json | 17 ++ .../src/components/items/create-item-form.tsx | 178 +++--------------- .../components/items/dictate-items-button.tsx | 88 +++++++++ apps/web/src/components/items/item-list.tsx | 2 + apps/web/src/hooks/use-add-items.ts | 171 +++++++++++++++++ apps/web/src/hooks/use-dictation.ts | 34 +--- .../web/src/hooks/use-microphone-dictation.ts | 154 +++++++++++++++ .../src/lib/natural-input/dictation.test.ts | 37 ++++ apps/web/src/lib/natural-input/dictation.ts | 35 ++++ apps/web/src/lib/speech-recognition.ts | 34 ++++ 10 files changed, 569 insertions(+), 181 deletions(-) create mode 100644 .claude/launch.json create mode 100644 apps/web/src/components/items/dictate-items-button.tsx create mode 100644 apps/web/src/hooks/use-add-items.ts create mode 100644 apps/web/src/hooks/use-microphone-dictation.ts create mode 100644 apps/web/src/lib/natural-input/dictation.test.ts create mode 100644 apps/web/src/lib/natural-input/dictation.ts create mode 100644 apps/web/src/lib/speech-recognition.ts diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..e57c4a6 --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,17 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "web", + "runtimeExecutable": "bun", + "runtimeArgs": ["run", "dev", "--filter=@superlist/web"], + "port": 7153 + }, + { + "name": "api", + "runtimeExecutable": "bun", + "runtimeArgs": ["run", "dev", "--filter=@superlist/api"], + "port": 4100 + } + ] +} diff --git a/apps/web/src/components/items/create-item-form.tsx b/apps/web/src/components/items/create-item-form.tsx index b734fc8..90c91db 100644 --- a/apps/web/src/components/items/create-item-form.tsx +++ b/apps/web/src/components/items/create-item-form.tsx @@ -1,12 +1,10 @@ import { zodResolver } from '@hookform/resolvers/zod' -import type { ListItem } from '@superlist/shared' import { Loader2Icon, MicIcon, PlusIcon } from 'lucide-react' -import { type ClipboardEvent, useEffect, useRef, useState } from 'react' +import { type ClipboardEvent, useEffect, useState } from 'react' import { useForm, useWatch } from 'react-hook-form' -import { toast } from 'sonner' import { z } from 'zod' -import { ItemInputPreview, type PreviewItem } from '@/components/items/item-input-preview' +import { ItemInputPreview } from '@/components/items/item-input-preview' import { Field, FieldError } from '@/components/ui/field' import { InputGroup, @@ -14,19 +12,10 @@ import { InputGroupButton, InputGroupInput, } from '@/components/ui/input-group' +import { itemLimitError, readItems, useAddItems } from '@/hooks/use-add-items' import { useDictation } from '@/hooks/use-dictation' -import { - isOptimisticItem, - useCreateItem, - useItems, - useRemoveItems, - useUpdateItem, -} from '@/hooks/use-items' import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation' -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 { 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); @@ -44,9 +33,6 @@ 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' @@ -69,23 +55,6 @@ export function refocusNewItemInput(): void { document.getElementById(NEW_ITEM_INPUT_ID)?.focus() } -/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */ -function itemLimitError(item: PreviewItem): string | null { - if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres` - if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga` - if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga` - - 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 - /** 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 * as natural language ("400 de jamon", "Queso crema. Solo Tregar", "leche, pan y @@ -96,11 +65,6 @@ type AddedItems = { * 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(null) @@ -111,22 +75,31 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp const text = useWatch({ control: form.control, name: 'entry' }) 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 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 && !voiceSplit.isPending) void addDictation(dictated) + if (dictated && !dictation.listening && !processing) onTranscript(dictated) }, }) - const processing = voiceSplit.isPending const dictating = dictation.listening || processing // The partial transcript is shown in the input while the user talks. @@ -140,64 +113,6 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp text.trim() !== '' && (literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate)) - const restoreText = (source: string, message: string) => { - const current = form.getValues('entry').trim() - form.setValue('entry', current ? `${current}; ${source}` : source) - form.setError('entry', { 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[] = [] - 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) => { @@ -217,48 +132,12 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp 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) => { + /** A dictation clears the input and goes through `addDictation`. */ + const onTranscript = (transcript: string) => { keyboardDictation.cancel() 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('entry', transcript) - form.setError('entry', { 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) - }, - }, - }) + void addDictation(transcript) } // An drops line breaks, so a pasted list keeps one item per line as "; ". @@ -376,12 +255,3 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp ) } - -/** The items `text` adds, each with the pending item it repeats, if any. */ -function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] { - if (!text.trim()) return [] - - const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text)) - - return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) })) -} diff --git a/apps/web/src/components/items/dictate-items-button.tsx b/apps/web/src/components/items/dictate-items-button.tsx new file mode 100644 index 0000000..53b11a5 --- /dev/null +++ b/apps/web/src/components/items/dictate-items-button.tsx @@ -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(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 ( +
+ + +
+ {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/item-list.tsx b/apps/web/src/components/items/item-list.tsx index c993944..c2ce684 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 { DictateItemsButton } from './dictate-items-button' import { ItemRow } from './item-row' import { ItemSheet } from './item-sheet' import { MoveItemDialog } from './move-item-dialog' @@ -101,6 +102,7 @@ export function ItemList({ listId }: ItemListProps) { Usa el campo de arriba para añadir tu primer artículo.

+ ) diff --git a/apps/web/src/hooks/use-add-items.ts b/apps/web/src/hooks/use-add-items.ts new file mode 100644 index 0000000..72c9351 --- /dev/null +++ b/apps/web/src/hooks/use-add-items.ts @@ -0,0 +1,171 @@ +import type { ListItem } from '@superlist/shared' +import { useRef } from 'react' +import { toast } from 'sonner' + +import type { PreviewItem } from '@/components/items/item-input-preview' +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 { literalItem, parseItemInput } from '@/lib/natural-input/parse-item' + +/** How long the "Deshacer" of a dictation stays on screen. */ +const DICTATION_UNDO_MS = 8000 + +/** Why a read item cannot be sent as is, mirroring the API limits, or `null`. */ +export function itemLimitError(item: PreviewItem): string | null { + if (item.name.length > 120) return `«${item.name.slice(0, 20)}…»: máximo 120 caracteres` + if ((item.quantity?.length ?? 0) > 40) return `«${item.name}»: la cantidad es demasiado larga` + if ((item.notes?.length ?? 0) > 280) return `«${item.name}»: la nota es demasiado larga` + + return null +} + +/** The items `text` adds, each with the pending item it repeats, if any. */ +export function readItems(text: string, literal: boolean, existing: ListItem[]): PreviewItem[] { + if (!text.trim()) return [] + + const items = literal ? [literalItem(text)] : mergeBatch(parseItemInput(text)) + + return items.map((item) => ({ ...item, duplicate: findDuplicate(existing, item.name) })) +} + +/** 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 + /** The previous quantity/notes of the pending items that were added to. */ + merged: { itemId: string; quantity: string | null; notes: string | null }[] +} + +type UseAddItemsOptions = { + /** An item could not be created: `source` is the text it was read from. */ + onItemFailed: (source: string, message: string) => void + /** A dictation was not added because an item breaks the API limits. */ + onDictationRejected: (transcript: string, message: string) => void +} + +/** + * Adds items to a list the way the "add an item" input does: an item already pending is + * added to instead of repeated, and a dictation is split into items by the API (with AI) + * and can be undone as a whole. + */ +export function useAddItems( + listId: string, + { onItemFailed, onDictationRejected }: UseAddItemsOptions, +) { + const createItem = useCreateItem(listId) + const updateItem = useUpdateItem(listId) + const removeItems = useRemoveItems(listId) + const voiceSplit = useVoiceSplit() + const { data: items } = useItems(listId) + // 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 + + /** Adds the items, or adds to the pending ones they repeat. */ + const addItems = (toAdd: PreviewItem[]): AddedItems => { + const created: Promise[] = [] + 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) => { + onItemFailed( + 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 API splits the transcript into one string per item and each one is read by the + * usual parser. If the request fails, the transcript is read as typed text when it is + * already split into lines, and added as a single item otherwise. + * + * @returns how many items were understood (0 when the dictation had none). + */ + const addDictation = async (transcript: string): Promise => { + let toAdd: PreviewItem[] + try { + const { items: spoken } = await voiceSplit.mutateAsync({ text: transcript }) + toAdd = readItems(spoken.join('; '), false, existingRef.current) + } catch { + toAdd = readItems(transcript, !/[;\n]/.test(transcript), existingRef.current) + } + + if (toAdd.length === 0) return 0 + + const limitError = toAdd.map(itemLimitError).find(Boolean) + if (limitError) { + onDictationRejected(transcript, limitError) + return toAdd.length + } + + const { created, merged } = addItems(toAdd) + const createdIds = await created + const count = createdIds.length + merged.length + if (count === 0) return toAdd.length + + 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) + }, + }, + }) + + return toAdd.length + } + + return { existing, addItems, addDictation, processing: voiceSplit.isPending } +} diff --git a/apps/web/src/hooks/use-dictation.ts b/apps/web/src/hooks/use-dictation.ts index e5cb597..6e74039 100644 --- a/apps/web/src/hooks/use-dictation.ts +++ b/apps/web/src/hooks/use-dictation.ts @@ -1,22 +1,10 @@ import { useCallback, useEffect, useRef, useState } from 'react' -/** The slice of the Web Speech API this hook uses (TypeScript's DOM lib does not ship it). */ -type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } } - -type SpeechRecognitionLike = { - lang: string - interimResults: boolean - continuous: boolean - maxAlternatives: number - onresult: ((event: { results: ArrayLike }) => void) | null - onerror: ((event: { error: string }) => void) | null - onend: (() => void) | null - start: () => void - stop: () => void - abort: () => void -} - -type SpeechRecognitionConstructor = new () => SpeechRecognitionLike +import { + getSpeechRecognition as getBrowserSpeechRecognition, + isIosStandalone, + type SpeechRecognitionConstructor, +} from '@/lib/speech-recognition' /** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */ const IGNORED_ERRORS = new Set(['no-speech', 'aborted']) @@ -34,17 +22,9 @@ const ERROR_MESSAGES: Record = { * unsupported (the keyboard's own dictation still works). */ function getSpeechRecognition(): SpeechRecognitionConstructor | null { - if (typeof window === 'undefined') return null + if (typeof window === 'undefined' || isIosStandalone()) return null - const iosStandalone = (navigator as Navigator & { standalone?: boolean }).standalone === true - if (iosStandalone) return null - - const speechWindow = window as Window & { - SpeechRecognition?: SpeechRecognitionConstructor - webkitSpeechRecognition?: SpeechRecognitionConstructor - } - - return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null + return getBrowserSpeechRecognition() } type UseDictationOptions = { diff --git a/apps/web/src/hooks/use-microphone-dictation.ts b/apps/web/src/hooks/use-microphone-dictation.ts new file mode 100644 index 0000000..37a36ed --- /dev/null +++ b/apps/web/src/hooks/use-microphone-dictation.ts @@ -0,0 +1,154 @@ +import { useCallback, useEffect, useRef, useState } from 'react' + +import { splitDictation } from '@/lib/natural-input/dictation' +import { 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.', + unavailable: 'No encontramos un micrófono disponible.', + unsupported: + 'Este navegador no permite dictar. Puedes usar el micrófono del teclado en el campo de arriba.', + empty: 'No escuchamos ningún artículo. Inténtalo de nuevo.', + failed: 'Ocurrió un error al reconocer la voz. Inténtalo de nuevo.', +} as const + +/** Recognition errors with a message of their own; any other one is `failed`. */ +const RECOGNITION_ERRORS: Record = { + 'not-allowed': DICTATION_MESSAGES.denied, + 'service-not-allowed': DICTATION_MESSAGES.unsupported, + 'audio-capture': DICTATION_MESSAGES.unavailable, + // Silence just ends with no phrases; a stop of ours is not an error. + 'no-speech': null, + aborted: null, +} + +/** What `getUserMedia` rejects with, as one of the messages. */ +function microphoneError(error: unknown): string { + const name = error instanceof DOMException ? error.name : '' + if (name === 'NotAllowedError' || name === 'SecurityError') return DICTATION_MESSAGES.denied + + return DICTATION_MESSAGES.unavailable +} + +type DictationStatus = 'idle' | 'requesting' | 'listening' + +type UseMicrophoneDictationOptions = { + /** The phrases dictated, one per item said, when the dictation ends with some. */ + onPhrases: (phrases: string[]) => void + /** Why the dictation did not deliver anything, in Spanish. */ + onError: (message: string) => void +} + +/** + * Dictation of several items in a row with the Web Speech API (`webkitSpeechRecognition` + * in Safari), in Argentine Spanish. `start()` must run inside a click handler: it asks + * for the microphone right there, then listens until the user calls `stop()` or the + * browser ends the recognition. Pauses, line breaks and "nuevo ítem" separate phrases + * (`splitDictation`). + * + * The microphone stream is only used to ask for the permission: its tracks are stopped + * as soon as it arrives (even after an unmount), before the recognition opens its own + * capture. Unmounting aborts the recognition. + */ +export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDictationOptions) { + const [status, setStatus] = useState('idle') + // What has been heard so far, shown while listening. + const [heard, setHeard] = useState('') + const callbacksRef = useRef({ onPhrases, onError }) + // Ends the dictation in progress: `true` delivers what was heard, `false` drops it. + const endRef = useRef<((deliver: boolean) => void) | null>(null) + + useEffect(() => { + callbacksRef.current = { onPhrases, onError } + }) + + useEffect(() => () => endRef.current?.(false), []) + + const start = useCallback(() => { + if (endRef.current) return + + const SpeechRecognition = getSpeechRecognition() + if (!SpeechRecognition) { + callbacksRef.current.onError(DICTATION_MESSAGES.unsupported) + return + } + + let recognition: SpeechRecognitionLike | null = null + let segments: string[] = [] + let failure: string | null = null + let done = false + + const end = (deliver: boolean) => { + if (done) return + done = true + endRef.current = null + // Aborting afterwards only fires an ignored `aborted` and an `onend` that finds it done. + recognition?.abort() + setStatus('idle') + setHeard('') + // Stopped while the permission was being asked: there is nothing to tell. + if (!deliver || (!recognition && !failure)) return + + const phrases = splitDictation(segments) + if (failure) callbacksRef.current.onError(failure) + else if (phrases.length === 0) callbacksRef.current.onError(DICTATION_MESSAGES.empty) + else callbacksRef.current.onPhrases(phrases) + } + + const listen = () => { + recognition = new SpeechRecognition() + recognition.lang = 'es-AR' + recognition.interimResults = true + recognition.continuous = true + recognition.maxAlternatives = 1 + + // Each result is a stretch of speech between pauses; the last one may still change. + recognition.onresult = (event) => { + segments = Array.from(event.results, (result) => result[0].transcript) + setHeard(splitDictation(segments).join(' · ')) + } + + recognition.onerror = (event) => { + const message = RECOGNITION_ERRORS[event.error] + if (message === null) return + failure = message ?? DICTATION_MESSAGES.failed + } + + recognition.onend = () => end(true) + + try { + recognition.start() + setStatus('listening') + } catch { + failure = DICTATION_MESSAGES.failed + end(true) + } + } + + endRef.current = end + setStatus('requesting') + + // Without `getUserMedia` (e.g. outside HTTPS) the recognition asks for the microphone itself. + if (!navigator.mediaDevices?.getUserMedia) { + listen() + return + } + + // Called right in the click, before any `await`, so Safari treats it as the user's. + navigator.mediaDevices.getUserMedia({ audio: true }).then( + (stream) => { + for (const track of stream.getTracks()) track.stop() + if (!done) listen() + }, + (error: unknown) => { + failure = microphoneError(error) + end(true) + }, + ) + }, []) + + /** Stops listening; what was heard so far is delivered. */ + const stop = useCallback(() => endRef.current?.(true), []) + + return { status, heard, start, stop } +} diff --git a/apps/web/src/lib/natural-input/dictation.test.ts b/apps/web/src/lib/natural-input/dictation.test.ts new file mode 100644 index 0000000..e7e0cc2 --- /dev/null +++ b/apps/web/src/lib/natural-input/dictation.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' + +import { splitDictation } from './dictation' + +describe('splitDictation', () => { + it('splits on "nuevo ítem" and its variants', () => { + expect( + splitDictation([ + 'leche descremada nuevo ítem pan Nuevo item 2 kilos de papa, otro artículo yerba', + ]), + ).toEqual(['leche descremada', 'pan', '2 kilos de papa', 'yerba']) + }) + + it('takes every segment and line as a separate phrase', () => { + expect(splitDictation(['Leche.', ' pan\nqueso rallado '])).toEqual([ + 'Leche', + 'pan', + 'queso rallado', + ]) + }) + + it('collapses spaces and drops empty phrases', () => { + expect(splitDictation([' dulce de leche ', '', 'nuevo ítem', '...'])).toEqual([ + 'dulce de leche', + ]) + }) + + it('keeps a repeated phrase once, ignoring case and accents', () => { + expect(splitDictation(['jamón', 'Jamon nuevo ítem pan', 'pan'])).toEqual(['jamón', 'pan']) + }) + + it('does not split words that only contain the keywords', () => { + expect(splitDictation(['productos nuevos de limpieza'])).toEqual([ + 'productos nuevos de limpieza', + ]) + }) +}) diff --git a/apps/web/src/lib/natural-input/dictation.ts b/apps/web/src/lib/natural-input/dictation.ts new file mode 100644 index 0000000..0f024e4 --- /dev/null +++ b/apps/web/src/lib/natural-input/dictation.ts @@ -0,0 +1,35 @@ +import { normalizeWord } from './text' + +/** + * What the user says to start another item: "nuevo ítem", "otro artículo", "nuevo + * producto". The punctuation the recognizer puts around it goes with it. + */ +const NEXT_ITEM = + /[\s,.;:]*(?() + + for (const segment of segments) { + for (const part of segment.split(/\r?\n/).flatMap((line) => line.split(NEXT_ITEM))) { + const phrase = part.replace(/\s+/g, ' ').replace(EDGE_PUNCTUATION, '') + const key = normalizeWord(phrase) + if (!phrase || seen.has(key)) continue + + seen.add(key) + phrases.push(phrase) + } + } + + return phrases +} diff --git a/apps/web/src/lib/speech-recognition.ts b/apps/web/src/lib/speech-recognition.ts new file mode 100644 index 0000000..0d798f6 --- /dev/null +++ b/apps/web/src/lib/speech-recognition.ts @@ -0,0 +1,34 @@ +/** The slice of the Web Speech API the app uses (TypeScript's DOM lib does not ship it). */ +export type SpeechRecognitionResultLike = { isFinal: boolean; 0: { transcript: string } } + +export type SpeechRecognitionLike = { + lang: string + interimResults: boolean + continuous: boolean + maxAlternatives: number + onresult: ((event: { results: ArrayLike }) => void) | null + onerror: ((event: { error: string }) => void) | null + onend: (() => void) | null + start: () => void + stop: () => void + abort: () => void +} + +export type SpeechRecognitionConstructor = new () => SpeechRecognitionLike + +/** `SpeechRecognition`, or Safari's `webkitSpeechRecognition`, or `null` when there is none. */ +export function getSpeechRecognition(): SpeechRecognitionConstructor | null { + if (typeof window === 'undefined') return null + + const speechWindow = window as Window & { + SpeechRecognition?: SpeechRecognitionConstructor + webkitSpeechRecognition?: SpeechRecognitionConstructor + } + + return speechWindow.SpeechRecognition ?? speechWindow.webkitSpeechRecognition ?? null +} + +/** Whether the page runs as an app installed on the iOS home screen. */ +export function isIosStandalone(): boolean { + return (navigator as Navigator & { standalone?: boolean }).standalone === true +}