feat: add dictation
This commit is contained in:
171
apps/web/src/hooks/use-add-items.ts
Normal file
171
apps/web/src/hooks/use-add-items.ts
Normal file
@@ -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<string[]>
|
||||
/** 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<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) => {
|
||||
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<number> => {
|
||||
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 }
|
||||
}
|
||||
@@ -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<SpeechRecognitionResultLike> }) => 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<string, string> = {
|
||||
* 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 = {
|
||||
|
||||
154
apps/web/src/hooks/use-microphone-dictation.ts
Normal file
154
apps/web/src/hooks/use-microphone-dictation.ts
Normal file
@@ -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<string, string | null> = {
|
||||
'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<DictationStatus>('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 }
|
||||
}
|
||||
Reference in New Issue
Block a user