feat(web): add text dictated with the iOS keyboard after 3 seconds
The installed iOS app has no speech recognition, so people dictate with the keyboard's microphone, which only writes text into the input and never ended it. Text that arrives without key presses (words or phrases at once, or replacements) is now treated as a dictation: 3 seconds after the last change it goes through the voice flow (AI split, "Deshacer"). Typing a key cancels it; pastes and deletions never trigger it. The form field is no longer called `name`, which made iOS offer to autofill a contact into the add field. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,7 @@ import {
|
|||||||
useRemoveItems,
|
useRemoveItems,
|
||||||
useUpdateItem,
|
useUpdateItem,
|
||||||
} from '@/hooks/use-items'
|
} from '@/hooks/use-items'
|
||||||
|
import { useKeyboardDictation } from '@/hooks/use-keyboard-dictation'
|
||||||
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
import { useVoiceSplit } from '@/hooks/use-voice-split'
|
||||||
import { ApiError } from '@/lib/api-client'
|
import { ApiError } from '@/lib/api-client'
|
||||||
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
import { findDuplicate, mergeBatch, mergeInto } from '@/lib/natural-input/merge'
|
||||||
@@ -31,7 +32,8 @@ import { cn } from '@/lib/utils'
|
|||||||
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
|
// The input may hold several items ("leche, pan y 2 pascualinas" or a pasted list);
|
||||||
// each one is checked against the API limits once the text is read.
|
// each one is checked against the API limits once the text is read.
|
||||||
const createItemSchema = z.object({
|
const createItemSchema = z.object({
|
||||||
name: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'),
|
// Not called `name`: iOS offers to autofill a contact into an input named that way.
|
||||||
|
entry: z.string().trim().min(1, 'Escribe un artículo').max(2000, 'Máximo 2000 caracteres'),
|
||||||
})
|
})
|
||||||
|
|
||||||
type CreateItemValues = z.infer<typeof createItemSchema>
|
type CreateItemValues = z.infer<typeof createItemSchema>
|
||||||
@@ -104,10 +106,10 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
|
|
||||||
const form = useForm<CreateItemValues>({
|
const form = useForm<CreateItemValues>({
|
||||||
resolver: zodResolver(createItemSchema),
|
resolver: zodResolver(createItemSchema),
|
||||||
defaultValues: { name: '' },
|
defaultValues: { entry: '' },
|
||||||
})
|
})
|
||||||
|
|
||||||
const text = useWatch({ control: form.control, name: 'name' })
|
const text = useWatch({ control: form.control, name: 'entry' })
|
||||||
const literal = literalText !== null && literalText === text
|
const literal = literalText !== null && literalText === text
|
||||||
// Placeholders have no server id yet, so they cannot be added to.
|
// Placeholders have no server id yet, so they cannot be added to.
|
||||||
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
const existing = (items ?? []).filter((item) => !isOptimisticItem(item))
|
||||||
@@ -116,12 +118,20 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
existingRef.current = existing
|
existingRef.current = existing
|
||||||
|
|
||||||
const dictation = useDictation({ onTranscript: (transcript) => void addDictation(transcript) })
|
const dictation = useDictation({ onTranscript: (transcript) => void addDictation(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)
|
||||||
|
},
|
||||||
|
})
|
||||||
const processing = voiceSplit.isPending
|
const processing = voiceSplit.isPending
|
||||||
const dictating = dictation.listening || processing
|
const dictating = dictation.listening || processing
|
||||||
|
|
||||||
// The partial transcript is shown in the input while the user talks.
|
// The partial transcript is shown in the input while the user talks.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (dictation.listening) form.setValue('name', dictation.interim)
|
if (dictation.listening) form.setValue('entry', dictation.interim)
|
||||||
}, [dictation.listening, dictation.interim, form])
|
}, [dictation.listening, dictation.interim, form])
|
||||||
|
|
||||||
const preview = readItems(text, literal, existing)
|
const preview = readItems(text, literal, existing)
|
||||||
@@ -131,9 +141,9 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
(literal || !isPlainItem(preview, text) || preview.some((item) => item.duplicate))
|
||||||
|
|
||||||
const restoreText = (source: string, message: string) => {
|
const restoreText = (source: string, message: string) => {
|
||||||
const current = form.getValues('name').trim()
|
const current = form.getValues('entry').trim()
|
||||||
form.setValue('name', current ? `${current}; ${source}` : source)
|
form.setValue('entry', current ? `${current}; ${source}` : source)
|
||||||
form.setError('name', { message })
|
form.setError('entry', { message })
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Adds the items, or adds to the pending ones they repeat. A failed one comes back to the input. */
|
/** Adds the items, or adds to the pending ones they repeat. A failed one comes back to the input. */
|
||||||
@@ -191,17 +201,18 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
// The input clears at once (items are added optimistically) so several items can be
|
// 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.
|
// typed in a row; if a request fails its text comes back with the error.
|
||||||
const onSubmit = form.handleSubmit((values) => {
|
const onSubmit = form.handleSubmit((values) => {
|
||||||
const toAdd = readItems(values.name, literal, existing)
|
keyboardDictation.cancel()
|
||||||
|
const toAdd = readItems(values.entry, literal, existing)
|
||||||
|
|
||||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||||
if (limitError) {
|
if (limitError) {
|
||||||
form.setError('name', { message: limitError })
|
form.setError('entry', { message: limitError })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
form.reset()
|
form.reset()
|
||||||
setLiteralText(null)
|
setLiteralText(null)
|
||||||
form.setFocus('name')
|
form.setFocus('entry')
|
||||||
|
|
||||||
addItems(toAdd)
|
addItems(toAdd)
|
||||||
})
|
})
|
||||||
@@ -211,6 +222,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
* usual parser. If the request fails, the whole transcript is added as a single item.
|
* usual parser. If the request fails, the whole transcript is added as a single item.
|
||||||
*/
|
*/
|
||||||
const addDictation = async (transcript: string) => {
|
const addDictation = async (transcript: string) => {
|
||||||
|
keyboardDictation.cancel()
|
||||||
form.reset()
|
form.reset()
|
||||||
setLiteralText(null)
|
setLiteralText(null)
|
||||||
|
|
||||||
@@ -226,8 +238,8 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
|
|
||||||
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
const limitError = toAdd.map(itemLimitError).find(Boolean)
|
||||||
if (limitError) {
|
if (limitError) {
|
||||||
form.setValue('name', transcript)
|
form.setValue('entry', transcript)
|
||||||
form.setError('name', { message: limitError })
|
form.setError('entry', { message: limitError })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,7 +276,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join('; ')
|
.join('; ')
|
||||||
|
|
||||||
form.setValue('name', input.value.slice(0, start) + lines + input.value.slice(end), {
|
form.setValue('entry', input.value.slice(0, start) + lines + input.value.slice(end), {
|
||||||
shouldDirty: true,
|
shouldDirty: true,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -284,7 +296,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
dictation.stop()
|
dictation.stop()
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Field data-invalid={!!form.formState.errors.name}>
|
<Field data-invalid={!!form.formState.errors.entry}>
|
||||||
<InputGroup className="bg-card h-14 rounded-full shadow-xs dark:bg-card">
|
<InputGroup className="bg-card h-14 rounded-full shadow-xs dark:bg-card">
|
||||||
<InputGroupAddon className="pl-1.5">
|
<InputGroupAddon className="pl-1.5">
|
||||||
<InputGroupButton
|
<InputGroupButton
|
||||||
@@ -304,7 +316,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
<InputGroupInput
|
<InputGroupInput
|
||||||
id={NEW_ITEM_INPUT_ID}
|
id={NEW_ITEM_INPUT_ID}
|
||||||
aria-label="Nuevo artículo"
|
aria-label="Nuevo artículo"
|
||||||
aria-invalid={!!form.formState.errors.name}
|
aria-invalid={!!form.formState.errors.entry}
|
||||||
aria-describedby={dictation.error ? 'dictation-error' : undefined}
|
aria-describedby={dictation.error ? 'dictation-error' : undefined}
|
||||||
autoComplete="off"
|
autoComplete="off"
|
||||||
placeholder={
|
placeholder={
|
||||||
@@ -314,7 +326,9 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
readOnly={dictating}
|
readOnly={dictating}
|
||||||
className="text-base"
|
className="text-base"
|
||||||
onPaste={onPaste}
|
onPaste={onPaste}
|
||||||
{...form.register('name', { onChange: dictation.clearError })}
|
onKeyDown={keyboardDictation.onKeyDown}
|
||||||
|
onInput={keyboardDictation.onInput}
|
||||||
|
{...form.register('entry', { onChange: dictation.clearError })}
|
||||||
/>
|
/>
|
||||||
{dictation.supported && (
|
{dictation.supported && (
|
||||||
<InputGroupAddon align="inline-end" className="pr-1.5">
|
<InputGroupAddon align="inline-end" className="pr-1.5">
|
||||||
@@ -330,7 +344,11 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
dictation.listening &&
|
dictation.listening &&
|
||||||
'after:bg-primary/30 after:absolute after:inset-0 after:-z-10 after:rounded-full motion-safe:after:animate-ping',
|
'after:bg-primary/30 after:absolute after:inset-0 after:-z-10 after:rounded-full motion-safe:after:animate-ping',
|
||||||
)}
|
)}
|
||||||
onClick={dictation.listening ? dictation.stop : dictation.start}
|
onClick={() => {
|
||||||
|
keyboardDictation.cancel()
|
||||||
|
if (dictation.listening) dictation.stop()
|
||||||
|
else dictation.start()
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{processing ? (
|
{processing ? (
|
||||||
<Loader2Icon className="size-5 animate-spin" />
|
<Loader2Icon className="size-5 animate-spin" />
|
||||||
@@ -341,7 +359,7 @@ export function CreateItemForm({ listId, autoFocus = false }: CreateItemFormProp
|
|||||||
</InputGroupAddon>
|
</InputGroupAddon>
|
||||||
)}
|
)}
|
||||||
</InputGroup>
|
</InputGroup>
|
||||||
<FieldError errors={[form.formState.errors.name]} className="px-5" />
|
<FieldError errors={[form.formState.errors.entry]} className="px-5" />
|
||||||
{dictation.error && (
|
{dictation.error && (
|
||||||
<p id="dictation-error" className="text-muted-foreground px-5 text-sm" aria-live="polite">
|
<p id="dictation-error" className="text-muted-foreground px-5 text-sm" aria-live="polite">
|
||||||
{dictation.error}
|
{dictation.error}
|
||||||
|
|||||||
29
apps/web/src/hooks/use-keyboard-dictation.test.ts
Normal file
29
apps/web/src/hooks/use-keyboard-dictation.test.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
|
import { isDictatedInput } from './use-keyboard-dictation'
|
||||||
|
|
||||||
|
describe('isDictatedInput', () => {
|
||||||
|
it('takes words or phrases written without a key press as dictation', () => {
|
||||||
|
expect(isDictatedInput({ inputType: 'insertText', data: 'Yogur', msSinceKeydown: 5000 })).toBe(
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
expect(
|
||||||
|
isDictatedInput({ inputType: 'insertReplacementText', data: null, msSinceKeydown: 5000 }),
|
||||||
|
).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not take typing as dictation', () => {
|
||||||
|
expect(isDictatedInput({ inputType: 'insertText', data: 'Yogur', msSinceKeydown: 10 })).toBe(
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
expect(isDictatedInput({ inputType: 'insertText', data: 'y', msSinceKeydown: 5000 })).toBe(
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('never takes pastes, drops or deletions as dictation', () => {
|
||||||
|
for (const inputType of ['insertFromPaste', 'insertFromDrop', 'deleteContentBackward']) {
|
||||||
|
expect(isDictatedInput({ inputType, data: 'leche y pan', msSinceKeydown: 5000 })).toBe(false)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
92
apps/web/src/hooks/use-keyboard-dictation.ts
Normal file
92
apps/web/src/hooks/use-keyboard-dictation.ts
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
import { type FormEvent, type KeyboardEvent, useCallback, useEffect, useRef } from 'react'
|
||||||
|
|
||||||
|
/** Quiet time after the keyboard's dictation last wrote into the input before it is added. */
|
||||||
|
export const KEYBOARD_DICTATION_IDLE_MS = 3000
|
||||||
|
|
||||||
|
/** How close to a key press an input event must be to count as typed. */
|
||||||
|
const KEYDOWN_WINDOW_MS = 100
|
||||||
|
|
||||||
|
/** Insertions that are never dictation (pasting or dropping text, deleting). */
|
||||||
|
const NOT_DICTATION = /^(insertFromPaste|insertFromDrop|delete)/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether an input event looks like the system keyboard's dictation writing into the
|
||||||
|
* field: text that arrives without a key press, several characters at once (dictation
|
||||||
|
* writes word by word or a whole phrase) or as a replacement of what it wrote before.
|
||||||
|
* Tapping a keyboard suggestion looks the same, which is the price of the guess.
|
||||||
|
*/
|
||||||
|
export function isDictatedInput(event: {
|
||||||
|
inputType: string
|
||||||
|
data: string | null
|
||||||
|
msSinceKeydown: number
|
||||||
|
}): boolean {
|
||||||
|
if (NOT_DICTATION.test(event.inputType)) return false
|
||||||
|
if (event.msSinceKeydown < KEYDOWN_WINDOW_MS) return false
|
||||||
|
if (event.inputType === 'insertReplacementText') return true
|
||||||
|
|
||||||
|
return event.inputType === 'insertText' && (event.data?.trim().length ?? 0) > 1
|
||||||
|
}
|
||||||
|
|
||||||
|
type UseKeyboardDictationOptions = {
|
||||||
|
/** Called with the input's text once the dictation has been quiet for a while. */
|
||||||
|
onIdle: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The installed iOS app has no speech recognition, so people dictate with the
|
||||||
|
* keyboard's microphone, which only writes text into the input. This notices text that
|
||||||
|
* arrives that way and calls `onIdle` once nothing new has arrived for
|
||||||
|
* `KEYBOARD_DICTATION_IDLE_MS`, so it is added without pressing Enter. Typing a key
|
||||||
|
* cancels it: from then on the text is the user's to submit.
|
||||||
|
*/
|
||||||
|
export function useKeyboardDictation({ onIdle }: UseKeyboardDictationOptions) {
|
||||||
|
const lastKeydown = useRef(0)
|
||||||
|
const dictated = useRef(false)
|
||||||
|
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
|
||||||
|
const onIdleRef = useRef(onIdle)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onIdleRef.current = onIdle
|
||||||
|
})
|
||||||
|
|
||||||
|
const cancel = useCallback(() => {
|
||||||
|
clearTimeout(timer.current)
|
||||||
|
dictated.current = false
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => cancel, [cancel])
|
||||||
|
|
||||||
|
const onKeyDown = useCallback(
|
||||||
|
(_event: KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
lastKeydown.current = performance.now()
|
||||||
|
cancel()
|
||||||
|
},
|
||||||
|
[cancel],
|
||||||
|
)
|
||||||
|
|
||||||
|
const onInput = useCallback((event: FormEvent<HTMLInputElement>) => {
|
||||||
|
const native = event.nativeEvent as InputEvent
|
||||||
|
const inputType = native.inputType ?? ''
|
||||||
|
|
||||||
|
const looksDictated = isDictatedInput({
|
||||||
|
inputType,
|
||||||
|
data: native.data ?? null,
|
||||||
|
msSinceKeydown: performance.now() - lastKeydown.current,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Once dictation started, any later update without a key press (corrections,
|
||||||
|
// composition) keeps it going; a paste or a deletion stops it.
|
||||||
|
if (looksDictated) dictated.current = true
|
||||||
|
else if (NOT_DICTATION.test(inputType)) dictated.current = false
|
||||||
|
|
||||||
|
clearTimeout(timer.current)
|
||||||
|
if (!dictated.current) return
|
||||||
|
|
||||||
|
timer.current = setTimeout(() => {
|
||||||
|
dictated.current = false
|
||||||
|
onIdleRef.current()
|
||||||
|
}, KEYBOARD_DICTATION_IDLE_MS)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return { onKeyDown, onInput, cancel }
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user