@umodeapporg/ui 0.32.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,7 +29,7 @@ const ControlledVoiceTextarea = ({
29
29
  lastEmittedValueRef.current = next;
30
30
  onChange(next);
31
31
  };
32
- const { isSupported, isListening, error, toggle } = useVoiceTranscription({
32
+ const { isSupported, isListening, isTranscribing, engine, error, toggle } = useVoiceTranscription({
33
33
  lang,
34
34
  onCommit: (update) => {
35
35
  const next = applyVoiceUpdate(committedRef.current, update);
@@ -90,6 +90,10 @@ const ControlledVoiceTextarea = ({
90
90
  isSupported && error && /* @__PURE__ */ jsxs("span", { role: "alert", className: "mt-1 flex items-center gap-1 text-xs text-danger-emphasis", children: [
91
91
  /* @__PURE__ */ jsx(MaterialSymbol, { icon: "mic_off", size: 14 }),
92
92
  errorMessageByCode[error]
93
+ ] }),
94
+ isSupported && !error && (isTranscribing || isListening && engine === "recorder") && /* @__PURE__ */ jsxs("span", { role: "status", className: "mt-1 flex items-center gap-1 text-xs text-foreground-muted", children: [
95
+ /* @__PURE__ */ jsx(MaterialSymbol, { icon: "graphic_eq", size: 14, className: isTranscribing ? "animate-pulse" : "" }),
96
+ isTranscribing ? t("voiceInput.transcribing") : t("voiceInput.listeningInPauses")
93
97
  ] })
94
98
  ] });
95
99
  };
@@ -1 +1 @@
1
- {"version":3,"file":"ControlledVoiceTextarea.js","sources":["../../../src/components/Form/ControlledVoiceTextarea.tsx"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport {\n appendInterimTranscript,\n applyVoiceUpdate,\n TVoiceTranscriptionError,\n useVoiceTranscription,\n VOICE_COMMANDS,\n} from '@/hooks/useVoiceTranscription';\n\nimport { MaterialSymbol } from '../UI/MaterialSymbol';\n\nimport ControlledButton from './ControlledButton';\nimport ControlledTextarea from './ControlledTextarea';\n\ninterface IControlledVoiceTextareaProps {\n /** Reaches the field itself, so a `FieldLabel` can point at it. */\n id?: string;\n value: string;\n onChange: (value: string) => void;\n placeholder?: string;\n rows?: number;\n lang?: string;\n className?: string;\n disabled?: boolean;\n}\n\nconst ControlledVoiceTextarea: React.FC<IControlledVoiceTextareaProps> = ({\n id,\n value,\n onChange,\n placeholder,\n rows = 4,\n lang = 'pt-BR',\n className,\n disabled,\n}) => {\n const { t } = useTranslation('ui');\n\n const committedRef = useRef(value);\n const lastEmittedValueRef = useRef(value);\n\n useEffect(() => {\n if (value === lastEmittedValueRef.current) return;\n committedRef.current = value;\n lastEmittedValueRef.current = value;\n }, [value]);\n\n const emitValue = (next: string) => {\n lastEmittedValueRef.current = next;\n onChange(next);\n };\n\n const { isSupported, isListening, error, toggle } = useVoiceTranscription({\n lang,\n onCommit: (update) => {\n const next = applyVoiceUpdate(committedRef.current, update);\n committedRef.current = next;\n emitValue(next);\n },\n onInterim: (text) => emitValue(appendInterimTranscript(committedRef.current, text)),\n });\n\n const handleManualChange = (next: string) => {\n committedRef.current = next;\n emitValue(next);\n };\n\n const errorMessageByCode: Record<TVoiceTranscriptionError, string> = {\n permission: t('voiceInput.errors.permission'),\n microphone: t('voiceInput.errors.microphone'),\n network: t('voiceInput.errors.network'),\n unavailable: t('voiceInput.errors.unavailable'),\n };\n\n const commandHint = VOICE_COMMANDS.map((command) => command.phrases[0]).join(', ');\n\n return (\n <div className={classNames('relative w-full', className)}>\n <ControlledTextarea\n id={id}\n value={value}\n rows={rows}\n resize=\"none\"\n disabled={disabled}\n placeholder={placeholder}\n onChange={(e) => handleManualChange(e.target.value)}\n className=\"pr-12\"\n />\n\n {isSupported && (\n <div className=\"absolute right-2 top-2 flex items-center gap-1\">\n <ControlledTooltip content={t('voiceInput.commandsHint', { commands: commandHint })} className=\"w-56\">\n <span className=\"flex size-7 items-center justify-center rounded-full text-foreground-faint\">\n <MaterialSymbol icon=\"help\" size={16} />\n </span>\n </ControlledTooltip>\n <ControlledTooltip content={isListening ? t('voiceInput.stop') : t('voiceInput.start')}>\n <ControlledButton\n aria-label={isListening ? t('voiceInput.stop') : t('voiceInput.start')}\n defaultHtmlButton\n disabled={disabled}\n onClick={toggle}\n className={classNames(\n 'flex size-8 items-center justify-center rounded-full transition-colors',\n isListening\n ? 'bg-danger-soft text-danger-emphasis hover:bg-danger-soft'\n : 'text-foreground-faint hover:bg-muted-hover hover:text-brand-emphasis',\n )}\n >\n <MaterialSymbol\n icon={isListening ? 'stop' : 'mic'}\n size={18}\n className={isListening ? 'animate-pulse' : ''}\n />\n </ControlledButton>\n </ControlledTooltip>\n </div>\n )}\n\n {isSupported && error && (\n <span role=\"alert\" className=\"mt-1 flex items-center gap-1 text-xs text-danger-emphasis\">\n <MaterialSymbol icon=\"mic_off\" size={14} />\n {errorMessageByCode[error]}\n </span>\n )}\n </div>\n );\n};\n\nexport default ControlledVoiceTextarea;\n"],"names":[],"mappings":";;;;;;;;;AA8BA,MAAM,0BAAmE,CAAC;AAAA,EACxE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAO;AAAA,EACP,OAAO;AAAA,EACP;AAAA,EACA;AACF,MAAM;AACJ,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AAEjC,QAAM,eAAe,OAAO,KAAK;AACjC,QAAM,sBAAsB,OAAO,KAAK;AAExC,YAAU,MAAM;AACd,QAAI,UAAU,oBAAoB,QAAS;AAC3C,iBAAa,UAAU;AACvB,wBAAoB,UAAU;AAAA,EAChC,GAAG,CAAC,KAAK,CAAC;AAEV,QAAM,YAAY,CAAC,SAAiB;AAClC,wBAAoB,UAAU;AAC9B,aAAS,IAAI;AAAA,EACf;AAEA,QAAM,EAAE,aAAa,aAAa,OAAO,OAAA,IAAW,sBAAsB;AAAA,IACxE;AAAA,IACA,UAAU,CAAC,WAAW;AACpB,YAAM,OAAO,iBAAiB,aAAa,SAAS,MAAM;AAC1D,mBAAa,UAAU;AACvB,gBA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;AAAA,UAAA;AAAA,UAGN,UAAA;AAAA,YAAC;AAAA,YAAA;AAAA,cACC,MAAM,cAAc,SAAS;AAAA,cAC7B,MAAM;AAAA,cACN,WAAW,cAAc,kBAAkB;AAAA,YAAA;AAAA,UAAA;AAAA,QAC7C;AAAA,MAAA,EACF,CACF;AAAA,IAAA,GACF;AAAA,IAGD,eAAe,SACd,qBAAC,UAAK,MAAK,SAAQ,WAAU,6DAC3B,UAAA;AAAA,MAAA,oBAAC,gBAAA,EAAe,MAAK,WAAU,MAAM,IAAI;AAAA,MACxC,mBAAmB,KAAK;AAAA,IAAA,EAAA,CAC3B;AAAA,EAAA,GAEJ;AAEJ;"}
1
+ {"version":3,"file":"ControlledVoiceTextarea.js","sources":["../../../src/components/Form/ControlledVoiceTextarea.tsx"],"sourcesContent":["import { useEffect, useRef } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport {\n appendInterimTranscript,\n applyVoiceUpdate,\n TVoiceTranscriptionError,\n useVoiceTranscription,\n VOICE_COMMANDS,\n} from '@/hooks/useVoiceTranscription';\n\nimport { MaterialSymbol } from '../UI/MaterialSymbol';\n\nimport ControlledButton from './ControlledButton';\nimport ControlledTextarea from './ControlledTextarea';\n\ninterface IControlledVoiceTextareaProps {\n /** Reaches the field itself, so a `FieldLabel` can point at it. */\n id?: string;\n value: string;\n onChange: (value: string) => void;\n placeholder?: string;\n rows?: number;\n lang?: string;\n className?: string;\n disabled?: boolean;\n}\n\nconst ControlledVoiceTextarea: React.FC<IControlledVoiceTextareaProps> = ({\n id,\n value,\n onChange,\n placeholder,\n rows = 4,\n lang = 'pt-BR',\n className,\n disabled,\n}) => {\n const { t } = useTranslation('ui');\n\n const committedRef = useRef(value);\n const lastEmittedValueRef = useRef(value);\n\n useEffect(() => {\n if (value === lastEmittedValueRef.current) return;\n committedRef.current = value;\n lastEmittedValueRef.current = value;\n }, [value]);\n\n const emitValue = (next: string) => {\n lastEmittedValueRef.current = next;\n onChange(next);\n };\n\n const { isSupported, isListening, isTranscribing, engine, error, toggle } = useVoiceTranscription({\n lang,\n onCommit: (update) => {\n const next = applyVoiceUpdate(committedRef.current, update);\n committedRef.current = next;\n emitValue(next);\n },\n onInterim: (text) => emitValue(appendInterimTranscript(committedRef.current, text)),\n });\n\n const handleManualChange = (next: string) => {\n committedRef.current = next;\n emitValue(next);\n };\n\n const errorMessageByCode: Record<TVoiceTranscriptionError, string> = {\n permission: t('voiceInput.errors.permission'),\n microphone: t('voiceInput.errors.microphone'),\n network: t('voiceInput.errors.network'),\n unavailable: t('voiceInput.errors.unavailable'),\n };\n\n const commandHint = VOICE_COMMANDS.map((command) => command.phrases[0]).join(', ');\n\n return (\n <div className={classNames('relative w-full', className)}>\n <ControlledTextarea\n id={id}\n value={value}\n rows={rows}\n resize=\"none\"\n disabled={disabled}\n placeholder={placeholder}\n onChange={(e) => handleManualChange(e.target.value)}\n className=\"pr-12\"\n />\n\n {isSupported && (\n <div className=\"absolute right-2 top-2 flex items-center gap-1\">\n <ControlledTooltip content={t('voiceInput.commandsHint', { commands: commandHint })} className=\"w-56\">\n <span className=\"flex size-7 items-center justify-center rounded-full text-foreground-faint\">\n <MaterialSymbol icon=\"help\" size={16} />\n </span>\n </ControlledTooltip>\n <ControlledTooltip content={isListening ? t('voiceInput.stop') : t('voiceInput.start')}>\n <ControlledButton\n aria-label={isListening ? t('voiceInput.stop') : t('voiceInput.start')}\n defaultHtmlButton\n disabled={disabled}\n onClick={toggle}\n className={classNames(\n 'flex size-8 items-center justify-center rounded-full transition-colors',\n isListening\n ? 'bg-danger-soft text-danger-emphasis hover:bg-danger-soft'\n : 'text-foreground-faint hover:bg-muted-hover hover:text-brand-emphasis',\n )}\n >\n <MaterialSymbol\n icon={isListening ? 'stop' : 'mic'}\n size={18}\n className={isListening ? 'animate-pulse' : ''}\n />\n </ControlledButton>\n </ControlledTooltip>\n </div>\n )}\n\n {isSupported && error && (\n <span role=\"alert\" className=\"mt-1 flex items-center gap-1 text-xs text-danger-emphasis\">\n <MaterialSymbol icon=\"mic_off\" size={14} />\n {errorMessageByCode[error]}\n </span>\n )}\n\n {isSupported && !error && (isTranscribing || (isListening && engine === 'recorder')) && (\n <span role=\"status\" className=\"mt-1 flex items-center gap-1 text-xs text-foreground-muted\">\n <MaterialSymbol icon=\"graphic_eq\" size={14} className={isTranscribing ? 'animate-pulse' : ''} />\n {isTranscribing ? t('voiceInput.transcribing') : t('voiceInput.listeningInPauses')}\n </span>\n )}\n </div>\n );\n};\n\nexport default ControlledVoiceTextarea;\n"],"names":[],"mappings":";;;;;;;;;AA8BA,MAAM,0BAAmE,CAAC;AAAA,EACxE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAO;AAAA,EACP,OAAO;AAAA,EACP;AAAA,EACA;AACF,MAAM;AACJ,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AAEjC,QAAM,eAAe,OAAO,KAAK;AACjC,QAAM,sBAAsB,OAAO,KAAK;AAExC,YAAU,MAAM;AACd,QAAI,UAAU,oBAAoB,QAAS;AAC3C,iBAAa,UAAU;AACvB,wBAAoB,UAAU;AAAA,EAChC,GAAG,CAAC,KAAK,CAAC;AAEV,QAAM,YAAY,CAAC,SAAiB;AAClC,wBAAoB,UAAU;AAC9B,aAAS,IAAI;AAAA,EACf;AAEA,QAAM,EAAE,aAAa,aAAa,gBAAgB,QAAQ,OAAO,OAAA,IAAW,sBAAsB;AAAA,IAChG;AAAA,IACA,UAAU,CAAC,WAAW;AACpB,YAAM,OAAO,iBAAiB,aAAa,SAAS,MAAM;AAC1D,mBAAa,UAAU;AACvB,gBAAU,IAAI;AAAA,IAChB;AAAA,IACA,WAAW,CAAC,SAAS,UAAU,wBAAwB,aAAa,SAAS,IAAI,CAAC;AAAA,EAAA,CACnF;AAED,QAAM,qBAAqB,CAAC,SAAiB;AAC3C,iBAAa,UAAU;AACvB,cAAU,IAAI;AAAA,EAChB;A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F;AAAA,IAAA,GACF;AAAA,IAGD,eAAe,SACd,qBAAC,UAAK,MAAK,SAAQ,WAAU,6DAC3B,UAAA;AAAA,MAAA,oBAAC,gBAAA,EAAe,MAAK,WAAU,MAAM,IAAI;AAAA,MACxC,mBAAmB,KAAK;AAAA,IAAA,GAC3B;AAAA,IAGD,eAAe,CAAC,UAAU,kBAAmB,eAAe,WAAW,eACtE,qBAAC,QAAA,EAAK,MAAK,UAAS,WAAU,8DAC5B,UAAA;AAAA,MAAA,oBAAC,gBAAA,EAAe,MAAK,cAAa,MAAM,IAAI,WAAW,iBAAiB,kBAAkB,GAAA,CAAI;AAAA,MAC7F,iBAAiB,EAAE,yBAAyB,IAAI,EAAE,8BAA8B;AAAA,IAAA,EAAA,CACnF;AAAA,EAAA,GAEJ;AAEJ;"}
@@ -53,7 +53,7 @@ const AppHeader = ({
53
53
  }
54
54
  ) })
55
55
  ] }),
56
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
56
+ /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 items-center gap-x-2", children: [
57
57
  toolsSlot && /* @__PURE__ */ jsx("div", { className: HEADER_CONTROL_SHELL_CLASS, children: toolsSlot }),
58
58
  controlsSlot,
59
59
  userMenuSlot && /* @__PURE__ */ jsxs(Fragment, { children: [
@@ -1 +1 @@
1
- {"version":3,"file":"AppHeader.js","sources":["../../../src/components/Shell/AppHeader.tsx"],"sourcesContent":["import { ReactNode, Ref } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport { useUiNavigation } from '@/components/Navigation/UiNavigationContext';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport UmodeLogo from '@/components/UI/UmodeLogo';\n\nimport { HEADER_CONTROL_SHELL_CLASS } from './headerControlStyles';\n\ninterface IAppHeaderProps {\n toggleSidebar: () => void;\n isSidebarOpen: boolean;\n toggleLabelKey: string;\n toggleRef?: Ref<HTMLElement>;\n /** Mobile drawer only: drives `aria-expanded` / `aria-controls` on the toggle. */\n mobileSidebar?: { id: string; open: boolean };\n homePath: string;\n /** Replaces the uMode logo; the header stays the same. */\n logo?: ReactNode;\n /** App tools rendered inside the pill shell (workspace, notifications...). */\n toolsSlot?: ReactNode;\n /** Theme/language knobs (usually the lib's ThemeToggle + LanguageToggle wired by the host). */\n controlsSlot?: ReactNode;\n /** The account surface (usually the lib's UserMenu wired by the host). */\n userMenuSlot?: ReactNode;\n onHoverEnter: () => void;\n onHoverLeave: () => void;\n}\n\nconst AppHeader: React.FC<IAppHeaderProps> = ({\n toggleSidebar,\n isSidebarOpen,\n toggleLabelKey,\n toggleRef,\n mobileSidebar,\n homePath,\n logo,\n toolsSlot,\n controlsSlot,\n userMenuSlot,\n onHoverEnter,\n onHoverLeave,\n}) => {\n const { t } = useTranslation('ui');\n const { Link: NavigationLink } = useUiNavigation();\n\n return (\n <header className=\"fixed top-0 z-50 flex h-16 w-full select-none items-center justify-between border-x-0 border-t-0 py-2 pr-4 glass-subtle\">\n <div className=\"flex cursor-pointer items-center gap-x-2\">\n <div className=\"sidebar-rail-slot flex shrink-0 items-center justify-center\">\n <MaterialSymbol\n icon={isSidebarOpen ? 'menu_open' : 'menu'}\n size={22}\n weight={400}\n ref={toggleRef}\n onClick={toggleSidebar}\n aria-controls={mobileSidebar?.id}\n aria-expanded={mobileSidebar?.open}\n onMouseEnter={onHoverEnter}\n onMouseLeave={onHoverLeave}\n aria-label={t(toggleLabelKey)}\n className={classNames(\n 'rounded-lg p-1 transition-colors duration-base',\n isSidebarOpen\n ? 'text-brand-emphasis hover:bg-brand-soft'\n : 'text-foreground-muted hover:bg-muted-hover hover:text-foreground',\n )}\n />\n </div>\n\n <ControlledTooltip content={t('sidebar.home')}>\n <NavigationLink\n to={homePath}\n aria-label={t('sidebar.home')}\n className=\"interactive hidden shrink-0 rounded-lg px-1 text-foreground hover:opacity-70 tablet:block\"\n >\n {logo ?? <UmodeLogo className=\"h-5 w-auto\" />}\n </NavigationLink>\n </ControlledTooltip>\n </div>\n\n <div className=\"flex items-center gap-x-2\">\n {toolsSlot && <div className={HEADER_CONTROL_SHELL_CLASS}>{toolsSlot}</div>}\n {controlsSlot}\n\n {userMenuSlot && (\n <>\n <div className=\"mx-1 h-6 w-px shrink-0 bg-border\" aria-hidden />\n {userMenuSlot}\n </>\n )}\n </div>\n </header>\n );\n};\n\nexport default AppHeader;\n"],"names":[],"mappings":";;;;;;;;AA+BA,MAAM,YAAuC,CAAC;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAAM;AACJ,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AACjC,QAAM,EAAE,MAAM,eAAA,IAAmB,gBAAA;AAEjC,SACE,qBAAC,UAAA,EAAO,WAAU,2HAChB,UAAA;AAAA,IAAA,qBAAC,OAAA,EAAI,WAAU,4CACb,UAAA;AAAA,MAAA,oBAAC,OAAA,EAAI,WAAU,+DACb,UAAA;AAAA,QAAC;AAAA,QAAA;AAAA,UACC,MAAM,gBAAgB,cAAc;AAAA,UACpC,MAAM;AAAA,UACN,QAAQ;AAAA,UACR,KAAK;AAAA,UACL,SAAS;AAAA,UACT,iBAAe,eAAe;AAAA,UAC9B,iBAAe,eAAe;AAAA,UAC9B,cAAc;AAAA,UACd,cAAc;AAAA,UACd,cAAY,EAAE,cAAc;AAAA,UAC5B,WAAW;AAAA,YACT;AAAA,YACA,gBACI,4CACA;AAAA,UAAA;AAAA,QACN;AAAA,MAAA,GAEJ;AAAA,MAEA,oBAAC,mBAAA,EAAkB,SAAS,EAAE,cAAc,GAC1C,UAAA;AAAA,QAAC;AAAA,QAAA;AAAA,UACC,IAAI;AAAA,UACJ,cAAY,EAAE,cAAc;AAAA,UAC5B,WAAU;AAAA,UAET,UAAA,QAAQ,oBAAC,WAAA,EAAU,WAAU,aAAA,CAAa;AAAA,QAAA;AAAA,MAAA,EAC7C,CACF;AAAA,IAAA,GACF;AAAA,IAEA,qBAAC,OAAA,EAAI,WAAU,6BACZ,UAAA;AAAA,MAAA,aAAa,oBAAC,OAAA,EAAI,WAAW,4BAA6B,UAAA,WAAU;AAAA,MACpE;AAAA,MAEA,gBACC,qBAAA,UAAA,EACE,UAAA;AAAA,QAAA,oBAAC,OAAA,EAAI,WAAU,oCAAmC,eAAW,MAAC;AAAA,QAC7D;AAAA,MAAA,EAAA,CACH;AAAA,IAAA,EAAA,CAEJ;AAAA,EAAA,GACF;AAEJ;"}
1
+ {"version":3,"file":"AppHeader.js","sources":["../../../src/components/Shell/AppHeader.tsx"],"sourcesContent":["import { ReactNode, Ref } from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport { useUiNavigation } from '@/components/Navigation/UiNavigationContext';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport { MaterialSymbol } from '@/components/UI/MaterialSymbol';\nimport UmodeLogo from '@/components/UI/UmodeLogo';\n\nimport { HEADER_CONTROL_SHELL_CLASS } from './headerControlStyles';\n\ninterface IAppHeaderProps {\n toggleSidebar: () => void;\n isSidebarOpen: boolean;\n toggleLabelKey: string;\n toggleRef?: Ref<HTMLElement>;\n /** Mobile drawer only: drives `aria-expanded` / `aria-controls` on the toggle. */\n mobileSidebar?: { id: string; open: boolean };\n homePath: string;\n /** Replaces the uMode logo; the header stays the same. */\n logo?: ReactNode;\n /** App tools rendered inside the pill shell (workspace, notifications...). */\n toolsSlot?: ReactNode;\n /** Theme/language knobs (usually the lib's ThemeToggle + LanguageToggle wired by the host). */\n controlsSlot?: ReactNode;\n /** The account surface (usually the lib's UserMenu wired by the host). */\n userMenuSlot?: ReactNode;\n onHoverEnter: () => void;\n onHoverLeave: () => void;\n}\n\nconst AppHeader: React.FC<IAppHeaderProps> = ({\n toggleSidebar,\n isSidebarOpen,\n toggleLabelKey,\n toggleRef,\n mobileSidebar,\n homePath,\n logo,\n toolsSlot,\n controlsSlot,\n userMenuSlot,\n onHoverEnter,\n onHoverLeave,\n}) => {\n const { t } = useTranslation('ui');\n const { Link: NavigationLink } = useUiNavigation();\n\n return (\n <header className=\"fixed top-0 z-50 flex h-16 w-full select-none items-center justify-between border-x-0 border-t-0 py-2 pr-4 glass-subtle\">\n <div className=\"flex cursor-pointer items-center gap-x-2\">\n <div className=\"sidebar-rail-slot flex shrink-0 items-center justify-center\">\n <MaterialSymbol\n icon={isSidebarOpen ? 'menu_open' : 'menu'}\n size={22}\n weight={400}\n ref={toggleRef}\n onClick={toggleSidebar}\n aria-controls={mobileSidebar?.id}\n aria-expanded={mobileSidebar?.open}\n onMouseEnter={onHoverEnter}\n onMouseLeave={onHoverLeave}\n aria-label={t(toggleLabelKey)}\n className={classNames(\n 'rounded-lg p-1 transition-colors duration-base',\n isSidebarOpen\n ? 'text-brand-emphasis hover:bg-brand-soft'\n : 'text-foreground-muted hover:bg-muted-hover hover:text-foreground',\n )}\n />\n </div>\n\n <ControlledTooltip content={t('sidebar.home')}>\n <NavigationLink\n to={homePath}\n aria-label={t('sidebar.home')}\n className=\"interactive hidden shrink-0 rounded-lg px-1 text-foreground hover:opacity-70 tablet:block\"\n >\n {logo ?? <UmodeLogo className=\"h-5 w-auto\" />}\n </NavigationLink>\n </ControlledTooltip>\n </div>\n\n {/* min-w-0: when the header runs out of room this side gives way, so a user menu that truncates can truncate. */}\n <div className=\"flex min-w-0 items-center gap-x-2\">\n {toolsSlot && <div className={HEADER_CONTROL_SHELL_CLASS}>{toolsSlot}</div>}\n {controlsSlot}\n\n {userMenuSlot && (\n <>\n <div className=\"mx-1 h-6 w-px shrink-0 bg-border\" aria-hidden />\n {userMenuSlot}\n </>\n )}\n </div>\n </header>\n );\n};\n\nexport default AppHeader;\n"],"names":[],"mappings":";;;;;;;;AA+BA,MAAM,YAAuC,CAAC;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,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AAA,EAAA,GACF;AAEJ;"}
@@ -0,0 +1,25 @@
1
+ export type TSpeechRecorderFailure = 'permission' | 'microphone' | 'unavailable';
2
+ export declare class SpeechRecorderError extends Error {
3
+ readonly failure: TSpeechRecorderFailure;
4
+ constructor(failure: TSpeechRecorderFailure);
5
+ }
6
+ export interface ISpeechSegmentRecorderCallbacks {
7
+ onSegment: (segment: Blob) => void;
8
+ /** Nothing was said for a while; the recorder already stopped. */
9
+ onIdle: () => void;
10
+ /** The microphone went away (unplugged, permission revoked); the recorder already stopped. */
11
+ onInterrupted: () => void;
12
+ }
13
+ export interface ISpeechSegmentRecorder {
14
+ /** Stops listening and still delivers the phrase in progress; resolves once it was handed over. */
15
+ stop: () => Promise<void>;
16
+ /** Stops listening and drops the phrase in progress. */
17
+ abort: () => void;
18
+ }
19
+ export declare const canRecordSpeech: () => boolean;
20
+ /**
21
+ * Records dictation for browsers whose speech engine is missing or unreachable. The microphone is
22
+ * watched for pauses and every phrase becomes its own recording, handed over as soon as it ends.
23
+ * Only phrases with speech are handed over: silence is never sent anywhere.
24
+ */
25
+ export declare const startSpeechSegmentRecorder: (callbacks: ISpeechSegmentRecorderCallbacks) => Promise<ISpeechSegmentRecorder>;
@@ -0,0 +1,171 @@
1
+ import { createSpeechSegmenter } from "./speechSegmenter.js";
2
+ import { uiLogger } from "./uiLogger.js";
3
+ class SpeechRecorderError extends Error {
4
+ constructor(failure) {
5
+ super(`Speech recorder could not start: ${failure}`);
6
+ this.failure = failure;
7
+ this.name = "SpeechRecorderError";
8
+ }
9
+ }
10
+ const RECORDING_MIME_CANDIDATES = ["audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/mp4", "audio/webm"];
11
+ const RECORDING_BITS_PER_SECOND = 32e3;
12
+ const LEVEL_SAMPLE_INTERVAL_MS = 50;
13
+ const SEGMENT_CLOSE_TIMEOUT_MS = 3e3;
14
+ const resolveAudioContextCtor = () => {
15
+ if (typeof window === "undefined") return null;
16
+ const audioWindow = window;
17
+ return audioWindow.AudioContext ?? audioWindow.webkitAudioContext ?? null;
18
+ };
19
+ const canRecordSpeech = () => typeof window !== "undefined" && typeof window.MediaRecorder !== "undefined" && typeof navigator !== "undefined" && typeof navigator.mediaDevices?.getUserMedia === "function" && resolveAudioContextCtor() !== null;
20
+ const pickRecordingMime = () => RECORDING_MIME_CANDIDATES.find((candidate) => MediaRecorder.isTypeSupported?.(candidate)) ?? "";
21
+ const toContainerMime = (mimeType) => mimeType.split(";")[0]?.trim() || "audio/webm";
22
+ const classifyMicrophoneError = (error) => {
23
+ const errorName = error instanceof Error || error instanceof DOMException ? error.name : "";
24
+ if (errorName === "NotAllowedError" || errorName === "SecurityError") return "permission";
25
+ if (errorName === "NotFoundError" || errorName === "NotReadableError" || errorName === "OverconstrainedError") {
26
+ return "microphone";
27
+ }
28
+ return "unavailable";
29
+ };
30
+ const readLevel = (analyser, samples) => {
31
+ analyser.getFloatTimeDomainData(samples);
32
+ let sumOfSquares = 0;
33
+ for (let sampleIndex = 0; sampleIndex < samples.length; sampleIndex += 1) {
34
+ const sample = samples[sampleIndex] ?? 0;
35
+ sumOfSquares += sample * sample;
36
+ }
37
+ return Math.sqrt(sumOfSquares / samples.length);
38
+ };
39
+ const closeAudioContext = async (audioContext) => {
40
+ try {
41
+ await audioContext.close();
42
+ } catch (error) {
43
+ uiLogger.debug("[speechSegmentRecorder] audio context close failed", error);
44
+ }
45
+ };
46
+ const resumeAudioContext = async (audioContext) => {
47
+ try {
48
+ await audioContext.resume();
49
+ } catch (error) {
50
+ uiLogger.debug("[speechSegmentRecorder] audio context resume failed", error);
51
+ }
52
+ };
53
+ const startSpeechSegmentRecorder = async (callbacks) => {
54
+ const AudioContextCtor = resolveAudioContextCtor();
55
+ if (!AudioContextCtor || !canRecordSpeech()) throw new SpeechRecorderError("unavailable");
56
+ const audioContext = new AudioContextCtor();
57
+ const audioContextResumed = resumeAudioContext(audioContext);
58
+ let stream;
59
+ try {
60
+ stream = await navigator.mediaDevices.getUserMedia({
61
+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }
62
+ });
63
+ } catch (error) {
64
+ uiLogger.warn("[speechSegmentRecorder] microphone unavailable", error);
65
+ void closeAudioContext(audioContext);
66
+ throw new SpeechRecorderError(classifyMicrophoneError(error));
67
+ }
68
+ await audioContextResumed;
69
+ const source = audioContext.createMediaStreamSource(stream);
70
+ const analyser = audioContext.createAnalyser();
71
+ analyser.fftSize = 1024;
72
+ const silentOutput = audioContext.createGain();
73
+ silentOutput.gain.value = 0;
74
+ source.connect(analyser);
75
+ analyser.connect(silentOutput);
76
+ silentOutput.connect(audioContext.destination);
77
+ const samples = new Float32Array(analyser.fftSize);
78
+ const recordingMime = pickRecordingMime();
79
+ const recorderOptions = {
80
+ audioBitsPerSecond: RECORDING_BITS_PER_SECOND,
81
+ ...recordingMime ? { mimeType: recordingMime } : {}
82
+ };
83
+ let finished = false;
84
+ let closing = null;
85
+ let levelTimer = null;
86
+ const segmenter = createSpeechSegmenter(performance.now());
87
+ const releaseMicrophone = () => {
88
+ stream.getTracks().forEach((track) => track.stop());
89
+ source.disconnect();
90
+ void closeAudioContext(audioContext);
91
+ };
92
+ const openSegment = () => {
93
+ const recorder = new MediaRecorder(stream, recorderOptions);
94
+ const segment = { recorder, keepsSpeech: false, onClosed: null };
95
+ const chunks = [];
96
+ recorder.ondataavailable = (event) => {
97
+ if (event.data.size > 0) chunks.push(event.data);
98
+ };
99
+ recorder.onstop = () => {
100
+ if (segment.keepsSpeech && chunks.length > 0) {
101
+ callbacks.onSegment(new Blob(chunks, { type: toContainerMime(recorder.mimeType || recordingMime) }));
102
+ }
103
+ segment.onClosed?.();
104
+ };
105
+ recorder.start();
106
+ return segment;
107
+ };
108
+ const closeSegment = (segment, keepsSpeech, onClosed = null) => {
109
+ segment.keepsSpeech = keepsSpeech;
110
+ segment.onClosed = onClosed;
111
+ if (segment.recorder.state === "inactive") {
112
+ onClosed?.();
113
+ return;
114
+ }
115
+ segment.recorder.stop();
116
+ };
117
+ let currentSegment = openSegment();
118
+ const finish = (keepsSpeech) => {
119
+ if (closing) return closing;
120
+ finished = true;
121
+ if (levelTimer !== null) clearInterval(levelTimer);
122
+ stream.getAudioTracks().forEach((track) => track.removeEventListener("ended", handleTrackEnded));
123
+ const lastSegment = currentSegment;
124
+ const keepsLastPhrase = keepsSpeech && segmenter.segmentSpeechMs() > 0;
125
+ closing = new Promise((resolve) => {
126
+ let released = false;
127
+ const release = () => {
128
+ if (released) return;
129
+ released = true;
130
+ clearTimeout(closeTimeout);
131
+ releaseMicrophone();
132
+ resolve();
133
+ };
134
+ const closeTimeout = setTimeout(release, SEGMENT_CLOSE_TIMEOUT_MS);
135
+ closeSegment(lastSegment, keepsLastPhrase, release);
136
+ });
137
+ return closing;
138
+ };
139
+ function handleTrackEnded() {
140
+ void finish(true);
141
+ callbacks.onInterrupted();
142
+ }
143
+ stream.getAudioTracks().forEach((track) => track.addEventListener("ended", handleTrackEnded));
144
+ levelTimer = setInterval(() => {
145
+ if (finished) return;
146
+ const decision = segmenter.observe(readLevel(analyser, samples), performance.now());
147
+ if (decision === "idle") {
148
+ void finish(true);
149
+ callbacks.onIdle();
150
+ return;
151
+ }
152
+ if (decision === "close-with-speech" || decision === "close-silent") {
153
+ const closingSegment = currentSegment;
154
+ currentSegment = openSegment();
155
+ segmenter.openSegment(performance.now());
156
+ closeSegment(closingSegment, decision === "close-with-speech");
157
+ }
158
+ }, LEVEL_SAMPLE_INTERVAL_MS);
159
+ return {
160
+ stop: () => finish(true),
161
+ abort: () => {
162
+ void finish(false);
163
+ }
164
+ };
165
+ };
166
+ export {
167
+ SpeechRecorderError,
168
+ canRecordSpeech,
169
+ startSpeechSegmentRecorder
170
+ };
171
+ //# sourceMappingURL=speechSegmentRecorder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"speechSegmentRecorder.js","sources":["../../src/helpers/speechSegmentRecorder.ts"],"sourcesContent":["import { createSpeechSegmenter } from './speechSegmenter';\nimport { uiLogger } from './uiLogger';\n\nexport type TSpeechRecorderFailure = 'permission' | 'microphone' | 'unavailable';\n\nexport class SpeechRecorderError extends Error {\n constructor(readonly failure: TSpeechRecorderFailure) {\n super(`Speech recorder could not start: ${failure}`);\n this.name = 'SpeechRecorderError';\n }\n}\n\nexport interface ISpeechSegmentRecorderCallbacks {\n onSegment: (segment: Blob) => void;\n /** Nothing was said for a while; the recorder already stopped. */\n onIdle: () => void;\n /** The microphone went away (unplugged, permission revoked); the recorder already stopped. */\n onInterrupted: () => void;\n}\n\nexport interface ISpeechSegmentRecorder {\n /** Stops listening and still delivers the phrase in progress; resolves once it was handed over. */\n stop: () => Promise<void>;\n /** Stops listening and drops the phrase in progress. */\n abort: () => void;\n}\n\ntype TAudioContextCtor = new () => AudioContext;\n\n/** Opus first: a phrase stays in a few dozen kilobytes. Safari only records MP4. */\nconst RECORDING_MIME_CANDIDATES = ['audio/webm;codecs=opus', 'audio/ogg;codecs=opus', 'audio/mp4', 'audio/webm'];\nconst RECORDING_BITS_PER_SECOND = 32_000;\nconst LEVEL_SAMPLE_INTERVAL_MS = 50;\n/** A recorder that never reports its end must not hold the host waiting for a phrase forever. */\nconst SEGMENT_CLOSE_TIMEOUT_MS = 3_000;\n\nconst resolveAudioContextCtor = (): TAudioContextCtor | null => {\n if (typeof window === 'undefined') return null;\n const audioWindow = window as unknown as { AudioContext?: TAudioContextCtor; webkitAudioContext?: TAudioContextCtor };\n return audioWindow.AudioContext ?? audioWindow.webkitAudioContext ?? null;\n};\n\nexport const canRecordSpeech = (): boolean =>\n typeof window !== 'undefined' &&\n typeof window.MediaRecorder !== 'undefined' &&\n typeof navigator !== 'undefined' &&\n typeof navigator.mediaDevices?.getUserMedia === 'function' &&\n resolveAudioContextCtor() !== null;\n\nconst pickRecordingMime = (): string =>\n RECORDING_MIME_CANDIDATES.find((candidate) => MediaRecorder.isTypeSupported?.(candidate)) ?? '';\n\n/**\n * The container alone: a type with codec parameters (`audio/webm;codecs=opus`) is read as\n * `text/plain` by some multipart parsers, and the upload is refused as not audio.\n */\nconst toContainerMime = (mimeType: string): string => mimeType.split(';')[0]?.trim() || 'audio/webm';\n\nconst classifyMicrophoneError = (error: unknown): TSpeechRecorderFailure => {\n const errorName = error instanceof Error || error instanceof DOMException ? error.name : '';\n if (errorName === 'NotAllowedError' || errorName === 'SecurityError') return 'permission';\n if (errorName === 'NotFoundError' || errorName === 'NotReadableError' || errorName === 'OverconstrainedError') {\n return 'microphone';\n }\n return 'unavailable';\n};\n\nconst readLevel = (analyser: AnalyserNode, samples: Float32Array<ArrayBuffer>): number => {\n analyser.getFloatTimeDomainData(samples);\n let sumOfSquares = 0;\n for (let sampleIndex = 0; sampleIndex < samples.length; sampleIndex += 1) {\n const sample = samples[sampleIndex] ?? 0;\n sumOfSquares += sample * sample;\n }\n return Math.sqrt(sumOfSquares / samples.length);\n};\n\nconst closeAudioContext = async (audioContext: AudioContext): Promise<void> => {\n try {\n await audioContext.close();\n } catch (error) {\n uiLogger.debug('[speechSegmentRecorder] audio context close failed', error);\n }\n};\n\nconst resumeAudioContext = async (audioContext: AudioContext): Promise<void> => {\n try {\n await audioContext.resume();\n } catch (error) {\n uiLogger.debug('[speechSegmentRecorder] audio context resume failed', error);\n }\n};\n\ninterface IRecordingSegment {\n recorder: MediaRecorder;\n keepsSpeech: boolean;\n onClosed: (() => void) | null;\n}\n\n/**\n * Records dictation for browsers whose speech engine is missing or unreachable. The microphone is\n * watched for pauses and every phrase becomes its own recording, handed over as soon as it ends.\n * Only phrases with speech are handed over: silence is never sent anywhere.\n */\nexport const startSpeechSegmentRecorder = async (\n callbacks: ISpeechSegmentRecorderCallbacks,\n): Promise<ISpeechSegmentRecorder> => {\n const AudioContextCtor = resolveAudioContextCtor();\n if (!AudioContextCtor || !canRecordSpeech()) throw new SpeechRecorderError('unavailable');\n\n /* Created and resumed before the permission prompt, while the click that started dictation still\n counts as a user gesture: a context born after it can stay suspended and hear only silence. */\n const audioContext = new AudioContextCtor();\n const audioContextResumed = resumeAudioContext(audioContext);\n\n let stream: MediaStream;\n try {\n stream = await navigator.mediaDevices.getUserMedia({\n audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },\n });\n } catch (error) {\n uiLogger.warn('[speechSegmentRecorder] microphone unavailable', error);\n void closeAudioContext(audioContext);\n throw new SpeechRecorderError(classifyMicrophoneError(error));\n }\n\n await audioContextResumed;\n const source = audioContext.createMediaStreamSource(stream);\n const analyser = audioContext.createAnalyser();\n analyser.fftSize = 1024;\n const silentOutput = audioContext.createGain();\n silentOutput.gain.value = 0;\n // Some engines only process a graph that reaches the output; the gain keeps it inaudible.\n source.connect(analyser);\n analyser.connect(silentOutput);\n silentOutput.connect(audioContext.destination);\n const samples = new Float32Array(analyser.fftSize);\n\n const recordingMime = pickRecordingMime();\n const recorderOptions: MediaRecorderOptions = {\n audioBitsPerSecond: RECORDING_BITS_PER_SECOND,\n ...(recordingMime ? { mimeType: recordingMime } : {}),\n };\n\n let finished = false;\n let closing: Promise<void> | null = null;\n let levelTimer: ReturnType<typeof setInterval> | null = null;\n const segmenter = createSpeechSegmenter(performance.now());\n\n const releaseMicrophone = () => {\n stream.getTracks().forEach((track) => track.stop());\n source.disconnect();\n void closeAudioContext(audioContext);\n };\n\n const openSegment = (): IRecordingSegment => {\n const recorder = new MediaRecorder(stream, recorderOptions);\n const segment: IRecordingSegment = { recorder, keepsSpeech: false, onClosed: null };\n const chunks: Array<Blob> = [];\n\n recorder.ondataavailable = (event) => {\n if (event.data.size > 0) chunks.push(event.data);\n };\n recorder.onstop = () => {\n if (segment.keepsSpeech && chunks.length > 0) {\n callbacks.onSegment(new Blob(chunks, { type: toContainerMime(recorder.mimeType || recordingMime) }));\n }\n segment.onClosed?.();\n };\n recorder.start();\n return segment;\n };\n\n const closeSegment = (segment: IRecordingSegment, keepsSpeech: boolean, onClosed: (() => void) | null = null) => {\n segment.keepsSpeech = keepsSpeech;\n segment.onClosed = onClosed;\n if (segment.recorder.state === 'inactive') {\n onClosed?.();\n return;\n }\n segment.recorder.stop();\n };\n\n let currentSegment = openSegment();\n\n const finish = (keepsSpeech: boolean): Promise<void> => {\n if (closing) return closing;\n finished = true;\n if (levelTimer !== null) clearInterval(levelTimer);\n stream.getAudioTracks().forEach((track) => track.removeEventListener('ended', handleTrackEnded));\n\n const lastSegment = currentSegment;\n const keepsLastPhrase = keepsSpeech && segmenter.segmentSpeechMs() > 0;\n closing = new Promise<void>((resolve) => {\n let released = false;\n const release = () => {\n if (released) return;\n released = true;\n clearTimeout(closeTimeout);\n releaseMicrophone();\n resolve();\n };\n const closeTimeout = setTimeout(release, SEGMENT_CLOSE_TIMEOUT_MS);\n closeSegment(lastSegment, keepsLastPhrase, release);\n });\n return closing;\n };\n\n function handleTrackEnded() {\n void finish(true);\n callbacks.onInterrupted();\n }\n\n stream.getAudioTracks().forEach((track) => track.addEventListener('ended', handleTrackEnded));\n\n levelTimer = setInterval(() => {\n if (finished) return;\n const decision = segmenter.observe(readLevel(analyser, samples), performance.now());\n\n if (decision === 'idle') {\n void finish(true);\n callbacks.onIdle();\n return;\n }\n\n if (decision === 'close-with-speech' || decision === 'close-silent') {\n const closingSegment = currentSegment;\n currentSegment = openSegment();\n segmenter.openSegment(performance.now());\n closeSegment(closingSegment, decision === 'close-with-speech');\n }\n }, LEVEL_SAMPLE_INTERVAL_MS);\n\n return {\n stop: () => finish(true),\n abort: () => {\n void finish(false);\n },\n };\n};\n"],"names":[],"mappings":";;AAKO,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAqB,SAAiC;AACpD,UAAM,oCAAoC,OAAO,EAAE;AADhC,SAAA,UAAA;AAEnB,SAAK,OAAO;AAAA,EACd;AACF;AAoBA,MAAM,4BAA4B,CAAC,0BAA0B,yBAAyB,aAAa,YAAY;AAC/G,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AAEjC,MAAM,2BAA2B;AAEjC,MAAM,0BAA0B,MAAgC;AAC9D,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,QAAM,cAAc;AACp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SAAU;AACd,UAAM,WAAW,UAAU,QAAQ,UAAU,UAAU,OAAO,GAAG,YAAY,KAAK;AAElF,QAAI,aAAa,QAAQ;AACvB,WAAK,OAAO,IAAI;AAChB,gBAAU,OAAA;AACV;AAAA,IACF;AAEA,QAAI,aAAa,uBAAuB,aAAa,gBAAgB;AACnE,YAAM,iBAAiB;AACvB,uBAAiB,YAAA;AACjB,gBAAU,YAAY,YAAY,KAAK;AACvC,mBAAa,gBAAgB,aAAa,mBAAmB;AAAA,IAC/D;AAAA,EACF,GAAG,wBAAwB;AAE3B,SAAO;AAAA,IACL,MAAM,MAAM,OAAO,IAAI;AAAA,IACvB,OAAO,MAAM;AACX,WAAK,OAAO,KAAK;AAAA,IACnB;AAAA,EAAA;AAEJ;"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Decides, from the microphone level, where dictated speech breaks into segments that are sent to
3
+ * be transcribed. A segment closes on a pause, so each one is a whole phrase and the text arrives
4
+ * while the person keeps talking. Pure: the clock and the level come from outside.
5
+ */
6
+ /** Voiced time a segment needs before it is worth sending: shorter is a click or a breath. */
7
+ export declare const MIN_SEGMENT_SPEECH_MS = 200;
8
+ /** Nothing said for this long ends the dictation, like the browser engine does. */
9
+ export declare const IDLE_STOP_MS = 20000;
10
+ export type TSpeechSegmenterDecision = 'listen' | 'close-with-speech' | 'close-silent' | 'idle';
11
+ export interface ISpeechSegmenter {
12
+ observe: (level: number, now: number) => TSpeechSegmenterDecision;
13
+ openSegment: (now: number) => void;
14
+ segmentSpeechMs: () => number;
15
+ }
16
+ export declare const createSpeechSegmenter: (startedAt: number) => ISpeechSegmenter;
@@ -0,0 +1,53 @@
1
+ const MIN_SPEECH_LEVEL = 0.012;
2
+ const NOISE_FLOOR_MULTIPLIER = 3;
3
+ const INITIAL_NOISE_FLOOR = MIN_SPEECH_LEVEL / NOISE_FLOOR_MULTIPLIER;
4
+ const NOISE_WINDOW_MS = 2500;
5
+ const MIN_SEGMENT_SPEECH_MS = 200;
6
+ const PAUSE_TO_CLOSE_SEGMENT_MS = 900;
7
+ const LONG_SEGMENT_MS = 15e3;
8
+ const SHORT_PAUSE_TO_CLOSE_LONG_SEGMENT_MS = 300;
9
+ const MAX_SEGMENT_MS = 3e4;
10
+ const SILENT_SEGMENT_MS = 5e3;
11
+ const IDLE_STOP_MS = 2e4;
12
+ const createSpeechSegmenter = (startedAt) => {
13
+ const recentLevels = [];
14
+ let segmentStartedAt = startedAt;
15
+ let segmentVoicedMs = 0;
16
+ let lastVoiceAt = startedAt;
17
+ let lastObservedAt = startedAt;
18
+ const measureNoiseFloor = (now) => {
19
+ const quietestLevel = recentLevels.reduce((quietest, entry) => Math.min(quietest, entry.level), Infinity);
20
+ return now - startedAt < NOISE_WINDOW_MS ? Math.min(INITIAL_NOISE_FLOOR, quietestLevel) : quietestLevel;
21
+ };
22
+ const observe = (level, now) => {
23
+ const elapsedMs = Math.max(0, now - lastObservedAt);
24
+ lastObservedAt = now;
25
+ recentLevels.push({ at: now, level });
26
+ while (recentLevels.length > 0 && (recentLevels[0]?.at ?? now) < now - NOISE_WINDOW_MS) recentLevels.shift();
27
+ const isVoiced = level >= Math.max(MIN_SPEECH_LEVEL, measureNoiseFloor(now) * NOISE_FLOOR_MULTIPLIER);
28
+ if (isVoiced) {
29
+ segmentVoicedMs += elapsedMs;
30
+ lastVoiceAt = now;
31
+ }
32
+ const pauseMs = now - lastVoiceAt;
33
+ if (pauseMs >= IDLE_STOP_MS) return "idle";
34
+ const segmentAgeMs = now - segmentStartedAt;
35
+ if (segmentVoicedMs >= MIN_SEGMENT_SPEECH_MS) {
36
+ const isPhraseOver = pauseMs >= PAUSE_TO_CLOSE_SEGMENT_MS;
37
+ const isLongPhraseBreathing = segmentAgeMs >= LONG_SEGMENT_MS && pauseMs >= SHORT_PAUSE_TO_CLOSE_LONG_SEGMENT_MS;
38
+ return isPhraseOver || isLongPhraseBreathing || segmentAgeMs >= MAX_SEGMENT_MS ? "close-with-speech" : "listen";
39
+ }
40
+ return !isVoiced && segmentAgeMs >= SILENT_SEGMENT_MS ? "close-silent" : "listen";
41
+ };
42
+ const openSegment = (now) => {
43
+ segmentStartedAt = now;
44
+ segmentVoicedMs = 0;
45
+ };
46
+ return { observe, openSegment, segmentSpeechMs: () => segmentVoicedMs };
47
+ };
48
+ export {
49
+ IDLE_STOP_MS,
50
+ MIN_SEGMENT_SPEECH_MS,
51
+ createSpeechSegmenter
52
+ };
53
+ //# sourceMappingURL=speechSegmenter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"speechSegmenter.js","sources":["../../src/helpers/speechSegmenter.ts"],"sourcesContent":["/**\n * Decides, from the microphone level, where dictated speech breaks into segments that are sent to\n * be transcribed. A segment closes on a pause, so each one is a whole phrase and the text arrives\n * while the person keeps talking. Pure: the clock and the level come from outside.\n */\n\n/** RMS below this is never speech, however quiet the room is. */\nconst MIN_SPEECH_LEVEL = 0.012;\n/** Speech has to stand this many times above the background noise. */\nconst NOISE_FLOOR_MULTIPLIER = 3;\nconst INITIAL_NOISE_FLOOR = MIN_SPEECH_LEVEL / NOISE_FLOOR_MULTIPLIER;\n/**\n * The background is the quietest level of the last moments. Speech always dips between syllables,\n * a fan or a street does not, so a steady noise becomes the floor and stops counting as speech.\n */\nconst NOISE_WINDOW_MS = 2_500;\n\n/** Voiced time a segment needs before it is worth sending: shorter is a click or a breath. */\nexport const MIN_SEGMENT_SPEECH_MS = 200;\nconst PAUSE_TO_CLOSE_SEGMENT_MS = 900;\nconst LONG_SEGMENT_MS = 15_000;\nconst SHORT_PAUSE_TO_CLOSE_LONG_SEGMENT_MS = 300;\nconst MAX_SEGMENT_MS = 30_000;\n/** A segment with no speech is restarted so silence never piles up in one recording. */\nconst SILENT_SEGMENT_MS = 5_000;\n/** Nothing said for this long ends the dictation, like the browser engine does. */\nexport const IDLE_STOP_MS = 20_000;\n\nexport type TSpeechSegmenterDecision = 'listen' | 'close-with-speech' | 'close-silent' | 'idle';\n\nexport interface ISpeechSegmenter {\n observe: (level: number, now: number) => TSpeechSegmenterDecision;\n openSegment: (now: number) => void;\n segmentSpeechMs: () => number;\n}\n\nexport const createSpeechSegmenter = (startedAt: number): ISpeechSegmenter => {\n const recentLevels: Array<{ at: number; level: number }> = [];\n let segmentStartedAt = startedAt;\n let segmentVoicedMs = 0;\n let lastVoiceAt = startedAt;\n let lastObservedAt = startedAt;\n\n /* Until a whole window was heard, someone who starts talking at once would become the floor. */\n const measureNoiseFloor = (now: number): number => {\n const quietestLevel = recentLevels.reduce((quietest, entry) => Math.min(quietest, entry.level), Infinity);\n return now - startedAt < NOISE_WINDOW_MS ? Math.min(INITIAL_NOISE_FLOOR, quietestLevel) : quietestLevel;\n };\n\n const observe = (level: number, now: number): TSpeechSegmenterDecision => {\n const elapsedMs = Math.max(0, now - lastObservedAt);\n lastObservedAt = now;\n\n recentLevels.push({ at: now, level });\n while (recentLevels.length > 0 && (recentLevels[0]?.at ?? now) < now - NOISE_WINDOW_MS) recentLevels.shift();\n\n const isVoiced = level >= Math.max(MIN_SPEECH_LEVEL, measureNoiseFloor(now) * NOISE_FLOOR_MULTIPLIER);\n if (isVoiced) {\n segmentVoicedMs += elapsedMs;\n lastVoiceAt = now;\n }\n\n const pauseMs = now - lastVoiceAt;\n if (pauseMs >= IDLE_STOP_MS) return 'idle';\n\n const segmentAgeMs = now - segmentStartedAt;\n if (segmentVoicedMs >= MIN_SEGMENT_SPEECH_MS) {\n const isPhraseOver = pauseMs >= PAUSE_TO_CLOSE_SEGMENT_MS;\n const isLongPhraseBreathing = segmentAgeMs >= LONG_SEGMENT_MS && pauseMs >= SHORT_PAUSE_TO_CLOSE_LONG_SEGMENT_MS;\n return isPhraseOver || isLongPhraseBreathing || segmentAgeMs >= MAX_SEGMENT_MS ? 'close-with-speech' : 'listen';\n }\n\n return !isVoiced && segmentAgeMs >= SILENT_SEGMENT_MS ? 'close-silent' : 'listen';\n };\n\n const openSegment = (now: number) => {\n segmentStartedAt = now;\n segmentVoicedMs = 0;\n };\n\n return { observe, open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AsB;AAAA,IACzG;AAEA,WAAO,CAAC,YAAY,gBAAgB,oBAAoB,iBAAiB;AAAA,EAC3E;AAEA,QAAM,cAAc,CAAC,QAAgB;AACnC,uBAAmB;AACnB,sBAAkB;AAAA,EACpB;AAEA,SAAO,EAAE,SAAS,aAAa,iBAAiB,MAAM,gBAAA;AACxD;"}
@@ -1,3 +1,16 @@
1
+ export interface IVoiceTranscriberRequest {
2
+ /** BCP 47 tag of the language being spoken. */
3
+ lang: string;
4
+ signal: AbortSignal;
5
+ }
6
+ /** Turns one recorded phrase into text. Resolves with an empty string when nothing was said. */
7
+ export type TVoiceTranscriber = (audio: Blob, request: IVoiceTranscriberRequest) => Promise<string>;
8
+ /**
9
+ * The host registers how recorded speech becomes text. It backs the browsers that ship no speech
10
+ * engine (Firefox) or one that cannot reach its service (Arc, Brave, Opera): without it, those
11
+ * browsers cannot dictate at all.
12
+ */
13
+ export declare const configureVoiceTranscriber: (transcriber: TVoiceTranscriber | null) => void;
1
14
  export type TVoiceCommandKey = 'comma' | 'period' | 'newline' | 'space' | 'question' | 'exclamation' | 'deleteWord';
2
15
  interface IVoiceCommand {
3
16
  key: TVoiceCommandKey;
@@ -13,6 +26,8 @@ export interface IVoiceTranscriptionUpdate {
13
26
  export declare const applyVoiceUpdate: (current: string, update: IVoiceTranscriptionUpdate) => string;
14
27
  export declare const appendInterimTranscript: (committed: string, interim: string) => string;
15
28
  export type TVoiceTranscriptionError = 'permission' | 'microphone' | 'network' | 'unavailable';
29
+ /** `browser`: the browser's own engine, live text. `recorder`: recorded phrases sent to the host. */
30
+ export type TVoiceTranscriptionEngine = 'browser' | 'recorder';
16
31
  interface IUseVoiceTranscriptionParams {
17
32
  lang?: string;
18
33
  onCommit: (update: IVoiceTranscriptionUpdate) => void;
@@ -21,6 +36,10 @@ interface IUseVoiceTranscriptionParams {
21
36
  interface IUseVoiceTranscriptionResult {
22
37
  isSupported: boolean;
23
38
  isListening: boolean;
39
+ /** Recorded speech whose text has not arrived yet. Only the recorder engine waits for text. */
40
+ isTranscribing: boolean;
41
+ /** The engine of the current (or last) dictation. */
42
+ engine: TVoiceTranscriptionEngine | null;
24
43
  error: TVoiceTranscriptionError | null;
25
44
  toggle: () => void;
26
45
  stop: () => void;
@@ -1,12 +1,44 @@
1
1
  import { useState, useRef, useSyncExternalStore, useCallback, useEffect } from "react";
2
+ import { startSpeechSegmentRecorder, SpeechRecorderError, canRecordSpeech } from "../helpers/speechSegmentRecorder.js";
2
3
  import { uiLogger } from "../helpers/uiLogger.js";
4
+ import { writeUiPreference, readUiPreference } from "../helpers/uiPreferences.js";
3
5
  const getRecognitionCtor = () => {
4
6
  const w = window;
5
7
  return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;
6
8
  };
7
- const subscribeToNothing = () => () => void 0;
8
- const isRecognitionAvailable = () => getRecognitionCtor() !== null;
9
+ let configuredTranscriber = null;
10
+ const transcriberListeners = /* @__PURE__ */ new Set();
11
+ const configureVoiceTranscriber = (transcriber) => {
12
+ configuredTranscriber = transcriber;
13
+ transcriberListeners.forEach((listener) => listener());
14
+ };
15
+ const canTranscribeRecordedSpeech = () => configuredTranscriber !== null && canRecordSpeech();
16
+ const subscribeToTranscriber = (listener) => {
17
+ transcriberListeners.add(listener);
18
+ return () => {
19
+ transcriberListeners.delete(listener);
20
+ };
21
+ };
22
+ const isVoiceInputAvailable = () => getRecognitionCtor() !== null || canTranscribeRecordedSpeech();
9
23
  const isUnavailableOnServer = () => false;
24
+ const BROWSER_ENGINE_UNREACHABLE_PREFERENCE_KEY = "umode-ui.voiceInput.browserEngineUnreachableAt";
25
+ const BROWSER_ENGINE_RETRY_AFTER_MS = 7 * 24 * 60 * 60 * 1e3;
26
+ const BROWSER_ENGINE_FAILURES_TO_RECORD_INSTEAD = /* @__PURE__ */ new Set([
27
+ "network",
28
+ "service-not-allowed",
29
+ "language-not-supported"
30
+ ]);
31
+ const BROWSER_CAPTURE_FAILURES_TO_RECORD_INSTEAD = /* @__PURE__ */ new Set(["audio-capture"]);
32
+ let browserEngineUnreachableThisPage = false;
33
+ const isBrowserEngineUnreachable = () => {
34
+ if (browserEngineUnreachableThisPage) return true;
35
+ const unreachableAt = readUiPreference(BROWSER_ENGINE_UNREACHABLE_PREFERENCE_KEY);
36
+ return typeof unreachableAt === "number" && Date.now() - unreachableAt < BROWSER_ENGINE_RETRY_AFTER_MS;
37
+ };
38
+ const rememberBrowserEngineUnreachable = () => {
39
+ browserEngineUnreachableThisPage = true;
40
+ writeUiPreference(BROWSER_ENGINE_UNREACHABLE_PREFERENCE_KEY, Date.now());
41
+ };
10
42
  const listensOneUtterancePerSession = () => {
11
43
  const { userAgent, maxTouchPoints } = navigator;
12
44
  return /Android|iPhone|iPad|iPod/i.test(userAgent) || /Macintosh/i.test(userAgent) && maxTouchPoints > 1;
@@ -85,6 +117,13 @@ const RECOGNITION_ERROR_TO_VOICE_ERROR = {
85
117
  "bad-grammar": "unavailable"
86
118
  };
87
119
  const MAX_SILENT_RESTARTS = 2;
120
+ const settleTranscript = async (transcriber, segment, request) => {
121
+ try {
122
+ return { ok: true, text: await transcriber(segment, request) };
123
+ } catch (error) {
124
+ return { ok: false, error };
125
+ }
126
+ };
88
127
  const detachRecognition = (recognition) => {
89
128
  recognition.onresult = null;
90
129
  recognition.onerror = null;
@@ -96,19 +135,121 @@ const useVoiceTranscription = ({
96
135
  onInterim
97
136
  }) => {
98
137
  const [isListening, setIsListening] = useState(false);
138
+ const [pendingSegmentCount, setPendingSegmentCount] = useState(0);
139
+ const [engine, setEngine] = useState(null);
99
140
  const [error, setError] = useState(null);
100
141
  const recognitionRef = useRef(null);
142
+ const segmentRecorderRef = useRef(null);
143
+ const activeEngineRef = useRef(null);
144
+ const recorderStartIdRef = useRef(0);
145
+ const commitQueueRef = useRef(Promise.resolve());
146
+ const unmountControllerRef = useRef(null);
147
+ const isMountedRef = useRef(true);
101
148
  const wantsListeningRef = useRef(false);
102
149
  const silentRestartCountRef = useRef(0);
103
150
  const onCommitRef = useRef(onCommit);
104
151
  const onInterimRef = useRef(onInterim);
105
152
  onCommitRef.current = onCommit;
106
153
  onInterimRef.current = onInterim;
107
- const isSupported = useSyncExternalStore(subscribeToNothing, isRecognitionAvailable, isUnavailableOnServer);
154
+ const isSupported = useSyncExternalStore(subscribeToTranscriber, isVoiceInputAvailable, isUnavailableOnServer);
155
+ const resolveUnmountSignal = () => {
156
+ if (!unmountControllerRef.current) unmountControllerRef.current = new AbortController();
157
+ return unmountControllerRef.current.signal;
158
+ };
159
+ const finishListening = useCallback(() => {
160
+ wantsListeningRef.current = false;
161
+ setIsListening(false);
162
+ }, []);
163
+ const detachSegmentRecorder = useCallback(() => {
164
+ recorderStartIdRef.current += 1;
165
+ const segmentRecorder = segmentRecorderRef.current;
166
+ segmentRecorderRef.current = null;
167
+ return segmentRecorder;
168
+ }, []);
169
+ const stopSegmentRecorder = useCallback(async () => {
170
+ const segmentRecorder = detachSegmentRecorder();
171
+ if (!segmentRecorder) return;
172
+ setPendingSegmentCount((count) => count + 1);
173
+ try {
174
+ await segmentRecorder.stop();
175
+ } finally {
176
+ if (isMountedRef.current) setPendingSegmentCount((count) => Math.max(0, count - 1));
177
+ }
178
+ }, [detachSegmentRecorder]);
179
+ const abortSegmentRecorder = useCallback(() => {
180
+ detachSegmentRecorder()?.abort();
181
+ }, [detachSegmentRecorder]);
182
+ const transcribeSegment = useCallback(
183
+ (segment) => {
184
+ const transcriber = configuredTranscriber;
185
+ if (!transcriber) return;
186
+ setPendingSegmentCount((count) => count + 1);
187
+ const outcome = settleTranscript(transcriber, segment, { lang, signal: resolveUnmountSignal() });
188
+ const previousCommit = commitQueueRef.current;
189
+ const commitInOrder = async () => {
190
+ await previousCommit;
191
+ const settled = await outcome;
192
+ if (!isMountedRef.current) return;
193
+ setPendingSegmentCount((count) => Math.max(0, count - 1));
194
+ if (!settled.ok) {
195
+ uiLogger.warn("[useVoiceTranscription] transcription failed", settled.error);
196
+ setError("network");
197
+ abortSegmentRecorder();
198
+ finishListening();
199
+ return;
200
+ }
201
+ if (!settled.text.trim()) return;
202
+ try {
203
+ onCommitRef.current(buildUpdateFromTranscript(settled.text));
204
+ } catch (commitError) {
205
+ uiLogger.error("[useVoiceTranscription] writing the transcript failed", commitError);
206
+ }
207
+ };
208
+ commitQueueRef.current = commitInOrder();
209
+ },
210
+ [abortSegmentRecorder, finishListening, lang]
211
+ );
212
+ const startSegmentRecorder = useCallback(async () => {
213
+ const startId = recorderStartIdRef.current + 1;
214
+ recorderStartIdRef.current = startId;
215
+ activeEngineRef.current = "recorder";
216
+ setEngine("recorder");
217
+ setIsListening(true);
218
+ try {
219
+ const segmentRecorder = await startSpeechSegmentRecorder({
220
+ onSegment: transcribeSegment,
221
+ onIdle: () => {
222
+ if (segmentRecorderRef.current !== segmentRecorder) return;
223
+ segmentRecorderRef.current = null;
224
+ finishListening();
225
+ },
226
+ onInterrupted: () => {
227
+ if (segmentRecorderRef.current !== segmentRecorder) return;
228
+ segmentRecorderRef.current = null;
229
+ setError("microphone");
230
+ finishListening();
231
+ }
232
+ });
233
+ if (recorderStartIdRef.current !== startId || !wantsListeningRef.current) {
234
+ segmentRecorder.abort();
235
+ return;
236
+ }
237
+ segmentRecorderRef.current = segmentRecorder;
238
+ } catch (startError) {
239
+ if (recorderStartIdRef.current !== startId || !isMountedRef.current) return;
240
+ uiLogger.warn("[useVoiceTranscription] recorder failed to start", startError);
241
+ setError(startError instanceof SpeechRecorderError ? startError.failure : "unavailable");
242
+ finishListening();
243
+ }
244
+ }, [finishListening, transcribeSegment]);
108
245
  const stop = useCallback(() => {
109
246
  wantsListeningRef.current = false;
110
247
  recognitionRef.current?.stop();
111
- }, []);
248
+ if (activeEngineRef.current === "recorder") {
249
+ void stopSegmentRecorder();
250
+ setIsListening(false);
251
+ }
252
+ }, [stopSegmentRecorder]);
112
253
  const startSession = useCallback(() => {
113
254
  const Ctor = getRecognitionCtor();
114
255
  if (!Ctor) return false;
@@ -147,6 +288,18 @@ const useVoiceTranscription = ({
147
288
  sessionEndedByError = true;
148
289
  if (event.error === "aborted") return;
149
290
  uiLogger.warn("[useVoiceTranscription] error", event.error);
291
+ const browserEngineIsUnreachable = BROWSER_ENGINE_FAILURES_TO_RECORD_INSTEAD.has(event.error);
292
+ const recordsInstead = browserEngineIsUnreachable || BROWSER_CAPTURE_FAILURES_TO_RECORD_INSTEAD.has(event.error);
293
+ if (wantsListeningRef.current && recordsInstead && canTranscribeRecordedSpeech()) {
294
+ if (browserEngineIsUnreachable) rememberBrowserEngineUnreachable();
295
+ detachRecognition(recognition);
296
+ recognitionRef.current = null;
297
+ recognition.abort();
298
+ if (uncommittedTranscript) onCommitRef.current(buildUpdateFromTranscript(uncommittedTranscript));
299
+ onInterimRef.current?.("");
300
+ void startSegmentRecorder();
301
+ return;
302
+ }
150
303
  setError(RECOGNITION_ERROR_TO_VOICE_ERROR[event.error] ?? "unavailable");
151
304
  };
152
305
  recognition.onend = () => {
@@ -171,38 +324,63 @@ const useVoiceTranscription = ({
171
324
  setError("unavailable");
172
325
  return false;
173
326
  }
174
- }, [lang]);
327
+ }, [lang, startSegmentRecorder]);
175
328
  const start = useCallback(() => {
176
329
  setError(null);
177
330
  silentRestartCountRef.current = 0;
178
331
  wantsListeningRef.current = true;
179
- if (startSession()) {
332
+ const canRecordInstead = canTranscribeRecordedSpeech();
333
+ const prefersBrowserEngine = getRecognitionCtor() !== null && (!canRecordInstead || !isBrowserEngineUnreachable());
334
+ if (prefersBrowserEngine && startSession()) {
335
+ activeEngineRef.current = "browser";
336
+ setEngine("browser");
180
337
  setIsListening(true);
181
338
  return;
182
339
  }
340
+ if (canRecordInstead) {
341
+ setError(null);
342
+ void startSegmentRecorder();
343
+ return;
344
+ }
183
345
  wantsListeningRef.current = false;
184
- }, [startSession]);
346
+ if (!prefersBrowserEngine) setError("unavailable");
347
+ }, [startSegmentRecorder, startSession]);
185
348
  const toggle = useCallback(() => {
186
349
  if (isListening) stop();
187
350
  else start();
188
351
  }, [isListening, start, stop]);
189
- useEffect(
190
- () => () => {
352
+ useEffect(() => {
353
+ isMountedRef.current = true;
354
+ return () => {
355
+ isMountedRef.current = false;
191
356
  wantsListeningRef.current = false;
357
+ recorderStartIdRef.current += 1;
358
+ segmentRecorderRef.current?.abort();
359
+ segmentRecorderRef.current = null;
360
+ unmountControllerRef.current?.abort();
361
+ unmountControllerRef.current = null;
192
362
  const recognition = recognitionRef.current;
193
363
  if (!recognition) return;
194
364
  detachRecognition(recognition);
195
365
  recognitionRef.current = null;
196
366
  recognition.abort();
197
- },
198
- []
199
- );
200
- return { isSupported, isListening, error, toggle, stop };
367
+ };
368
+ }, []);
369
+ return {
370
+ isSupported,
371
+ isListening,
372
+ isTranscribing: pendingSegmentCount > 0,
373
+ engine,
374
+ error,
375
+ toggle,
376
+ stop
377
+ };
201
378
  };
202
379
  export {
203
380
  VOICE_COMMANDS,
204
381
  appendInterimTranscript,
205
382
  applyVoiceUpdate,
383
+ configureVoiceTranscriber,
206
384
  useVoiceTranscription
207
385
  };
208
386
  //# sourceMappingURL=useVoiceTranscription.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useVoiceTranscription.js","sources":["../../src/hooks/useVoiceTranscription.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\n\nimport { uiLogger } from '@/helpers/uiLogger';\n\ninterface ISpeechRecognitionAlternative {\n transcript: string;\n}\n\ninterface ISpeechRecognitionResult {\n 0: ISpeechRecognitionAlternative;\n isFinal: boolean;\n}\n\ninterface ISpeechRecognitionEvent {\n resultIndex: number;\n results: { length: number; [index: number]: ISpeechRecognitionResult };\n}\n\ninterface ISpeechRecognition {\n lang: string;\n continuous: boolean;\n interimResults: boolean;\n start: () => void;\n stop: () => void;\n abort: () => void;\n onresult: ((event: ISpeechRecognitionEvent) => void) | null;\n onerror: ((event: { error: string }) => void) | null;\n onend: (() => void) | null;\n}\n\ntype TSpeechRecognitionCtor = new () => ISpeechRecognition;\n\nconst getRecognitionCtor = (): TSpeechRecognitionCtor | null => {\n const w = window as unknown as {\n SpeechRecognition?: TSpeechRecognitionCtor;\n webkitSpeechRecognition?: TSpeechRecognitionCtor;\n };\n return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;\n};\n\n/* The API never appears or goes away while a page is open, so there is nothing to subscribe to.\n The store exists for the server answer: `window` is not there, and the first client render has\n to agree with it for hydration to hold. */\nconst subscribeToNothing = () => () => undefined;\nconst isRecognitionAvailable = () => getRecognitionCtor() !== null;\nconst isUnavailableOnServer = () => false;\n\n/* Phones run another engine behind the same API. Asked to listen continuously it delivers earlier\n phrases again and flags unfinished ones as final, so `isFinal` cannot be trusted there and a phone\n listens one utterance per session, restarting between them. iPadOS reports itself as a Mac. */\nconst listensOneUtterancePerSession = (): boolean => {\n const { userAgent, maxTouchPoints } = navigator;\n return /Android|iPhone|iPad|iPod/i.test(userAgent) || (/Macintosh/i.test(userAgent) && maxTouchPoints > 1);\n};\n\n/* Those engines either grow one result in place or deliver the text so far again as a new result,\n so a result that already holds what came before replaces it instead of being appended to it. */\nconst readUtterance = (event: ISpeechRecognitionEvent): string => {\n let utterance = '';\n for (let resultIndex = 0; resultIndex < event.results.length; resultIndex += 1) {\n const transcript = event.results[resultIndex]?.[0]?.transcript?.trim() ?? '';\n const normalizedTranscript = transcript.toLowerCase();\n const normalizedUtterance = utterance.toLowerCase();\n if (!transcript || normalizedUtterance.endsWith(normalizedTranscript)) continue;\n utterance = normalizedTranscript.startsWith(normalizedUtterance) ? transcript : `${utterance} ${transcript}`;\n }\n return utterance;\n};\n\nexport type TVoiceCommandKey = 'comma' | 'period' | 'newline' | 'space' | 'question' | 'exclamation' | 'deleteWord';\n\ninterface IVoiceCommand {\n key: TVoiceCommandKey;\n phrases: Array<string>;\n insert?: string;\n action?: 'deleteWord';\n}\n\n// Spoken keywords matched against the user's speech. They must stay as literal\n// recognition tokens (not UI strings), so the i18n check is disabled here.\n/* eslint-disable i18n-check/no-portuguese-strings */\nexport const VOICE_COMMANDS: Array<IVoiceCommand> = [\n { key: 'comma', phrases: ['vírgula', 'virgula', 'comma'], insert: ', ' },\n { key: 'period', phrases: ['ponto', 'ponto final', 'period'], insert: '. ' },\n { key: 'newline', phrases: ['nova linha', 'quebra de linha', 'parágrafo', 'paragrafo', 'new line'], insert: '\\n' },\n { key: 'space', phrases: ['espaço', 'espaco', 'space'], insert: ' ' },\n {\n key: 'question',\n phrases: ['interrogação', 'interrogacao', 'ponto de interrogação', 'question mark'],\n insert: '? ',\n },\n {\n key: 'exclamation',\n phrases: ['exclamação', 'exclamacao', 'ponto de exclamação', 'exclamation mark'],\n insert: '! ',\n },\n { key: 'deleteWord', phrases: ['apagar', 'apaga', 'apagar palavra', 'delete'], action: 'deleteWord' },\n];\n/* eslint-enable i18n-check/no-portuguese-strings */\n\nconst PHRASE_TO_COMMAND = new Map<string, IVoiceCommand>();\nfor (const command of VOICE_COMMANDS) {\n for (const phrase of command.phrases) PHRASE_TO_COMMAND.set(phrase, command);\n}\n\nconst normalize = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[.,!?;:]+$/, '');\n\nexport interface IVoiceTranscriptionUpdate {\n insert: string;\n deleteWords: number;\n}\n\nconst buildUpdateFromTranscript = (transcript: string): IVoiceTranscriptionUpdate => {\n const words = transcript.trim().split(/\\s+/).filter(Boolean);\n let insert = '';\n let deleteWords = 0;\n\n for (const word of words) {\n const command = PHRASE_TO_COMMAND.get(normalize(word));\n if (command?.action === 'deleteWord') {\n deleteWords += 1;\n insert = '';\n continue;\n }\n if (command?.insert !== undefined) {\n insert = insert.replace(/\\s+$/, '') + command.insert;\n continue;\n }\n insert += (insert && !insert.endsWith(' ') && !insert.endsWith('\\n') ? ' ' : '') + word;\n }\n\n return { insert, deleteWords };\n};\n\nconst appendTranscriptText = (current: string, addition: string): string => {\n if (!addition) return current;\n const needsSpace = current.length > 0 && !/\\s$/.test(current) && !/^[\\s.,!?]/.test(addition);\n return current + (needsSpace ? ' ' : '') + addition;\n};\n\nexport const applyVoiceUpdate = (current: string, update: IVoiceTranscriptionUpdate): string => {\n let next = current;\n for (let wordIndex = 0; wordIndex < update.deleteWords; wordIndex += 1) {\n next = next.replace(/\\s*\\S+\\s*$/, '');\n }\n return appendTranscriptText(next, update.insert);\n};\n\nexport const appendInterimTranscript = (committed: string, interim: string): string =>\n appendTranscriptText(committed, interim);\n\nexport type TVoiceTranscriptionError = 'permission' | 'microphone' | 'network' | 'unavailable';\n\nconst RECOGNITION_ERROR_TO_VOICE_ERROR: Record<string, TVoiceTranscriptionError> = {\n 'not-allowed': 'permission',\n 'service-not-allowed': 'permission',\n 'audio-capture': 'microphone',\n network: 'network',\n 'language-not-supported': 'unavailable',\n 'bad-grammar': 'unavailable',\n};\n\nconst MAX_SILENT_RESTARTS = 2;\n\ninterface IUseVoiceTranscriptionParams {\n lang?: string;\n onCommit: (update: IVoiceTranscriptionUpdate) => void;\n onInterim?: (text: string) => void;\n}\n\ninterface IUseVoiceTranscriptionResult {\n isSupported: boolean;\n isListening: boolean;\n error: TVoiceTranscriptionError | null;\n toggle: () => void;\n stop: () => void;\n}\n\nconst detachRecognition = (recognition: ISpeechRecognition) => {\n recognition.onresult = null;\n recognition.onerror = null;\n recognition.onend = null;\n};\n\nexport const useVoiceTranscription = ({\n lang = 'pt-BR',\n onCommit,\n onInterim,\n}: IUseVoiceTranscriptionParams): IUseVoiceTranscriptionResult => {\n const [isListening, setIsListening] = useState(false);\n const [error, setError] = useState<TVoiceTranscriptionError | null>(null);\n const recognitionRef = useRef<ISpeechRecognition | null>(null);\n const wantsListeningRef = useRef(false);\n const silentRestartCountRef = useRef(0);\n const onCommitRef = useRef(onCommit);\n const onInterimRef = useRef(onInterim);\n\n onCommitRef.current = onCommit;\n onInterimRef.current = onInterim;\n\n const isSupported = useSyncExternalStore(subscribeToNothing, isRecognitionAvailable, isUnavailableOnServer);\n\n const stop = useCallback(() => {\n wantsListeningRef.current = false;\n recognitionRef.current?.stop();\n }, []);\n\n const startSession = useCallback((): boolean => {\n const Ctor = getRecognitionCtor();\n if (!Ctor) return false;\n\n const oneUtterancePerSession = listensOneUtterancePerSession();\n\n const recognition = new Ctor();\n recognition.lang = lang;\n recognition.continuous = !oneUtterancePerSession;\n recognition.interimResults = true;\n\n let sessionHeardSpeech = false;\n let sessionEndedByError = false;\n let uncommittedTranscript = '';\n\n recognition.onresult = (event) => {\n if (recognitionRef.current !== recognition) return;\n sessionHeardSpeech = true;\n\n if (oneUtterancePerSession) {\n uncommittedTranscript = readUtterance(event);\n onInterimRef.current?.(uncommittedTranscript);\n return;\n }\n\n let interim = '';\n for (let resultIndex = event.resultIndex; resultIndex < event.results.length; resultIndex += 1) {\n const result = event.results[resultIndex];\n const transcript = result?.[0]?.transcript ?? '';\n if (result?.isFinal) {\n onCommitRef.current(buildUpdateFromTranscript(transcript));\n } else {\n interim += transcript;\n }\n }\n uncommittedTranscript = interim.trim();\n onInterimRef.current?.(uncommittedTranscript);\n };\n\n recognition.onerror = (event) => {\n if (recognitionRef.current !== recognition) return;\n if (event.error === 'no-speech') return;\n sessionEndedByError = true;\n if (event.error === 'aborted') return;\n uiLogger.warn('[useVoiceTranscription] error', event.error);\n setError(RECOGNITION_ERROR_TO_VOICE_ERROR[event.error] ?? 'unavailable');\n };\n\n recognition.onend = () => {\n if (recognitionRef.current !== recognition) return;\n if (uncommittedTranscript) onCommitRef.current(buildUpdateFromTranscript(uncommittedTranscript));\n onInterimRef.current?.('');\n silentRestartCountRef.current = sessionHeardSpeech ? 0 : silentRestartCountRef.current + 1;\n const shouldResume =\n wantsListeningRef.current && !sessionEndedByError && silentRestartCountRef.current <= MAX_SILENT_RESTARTS;\n if (shouldResume && startSession()) return;\n wantsListeningRef.current = false;\n recognitionRef.current = null;\n setIsListening(false);\n };\n\n recognitionRef.current = recognition;\n try {\n recognition.start();\n return true;\n } catch (startError) {\n uiLogger.warn('[useVoiceTranscription] start failed', startError);\n detachRecognition(recognition);\n recognitionRef.current = null;\n setError('unavailable');\n return false;\n }\n }, [lang]);\n\n const start = useCallback(() => {\n setError(null);\n silentRestartCountRef.current = 0;\n wantsListeningRef.current = true;\n if (startSession()) {\n setIsListening(true);\n return;\n }\n wantsListeningRef.current = false;\n }, [startSession]);\n\n const toggle = useCallback(() => {\n if (isListening) stop();\n else start();\n }, [isListening, start, stop]);\n\n useEffect(\n () => () => {\n wantsListeningRef.current = false;\n const recognition = recognitionRef.current;\n if (!recognition) return;\n detachRecognition(recognition);\n recognitionRef.current = null;\n recognition.abort();\n },\n [],\n );\n\n return { isSupported, isListening, error, toggle, stop };\n};\n"],"names":[],"mappings":";;AAgCA,MAAM,qBAAqB,MAAqC;AAC9D,QAAM,IAAI;AAIV,SAAO,EAAE,qBAAqB,EAAE,2BAA2B;AAC7D;AAKA,MAAM,qBAAqB,MAAM,MAAM;AACvC,MAAM,yBAAyB,MAAM,mBAAA,MAAyB;AAC9D,MAAM,wBAAwB,MAAM;AAKpC,MAAM,gCAAgC,MAAe;AACnD,QAAM,EAAE,WAAW,eAAA,IAAmB;AACtC,SAAO,4BAA4B,KAAK,SAAS,KAAM,aAAa,KAAK,SAAS,KAAK,iBAAiB;AAC1G;AAIA,MAAM,gBAAgB,CAAC,UAA2C;AAChE,MAAI,YAAY;AAChB,WAAS,cAAc,GAAG,cAAc,MAAM,QAAQ,QAAQ,eAAe,GAAG;AAC9E,UAAM,aAAa,MAAM,QAAQ,WAAW,IAAI,CAAC,GAAG,YAAY,KAAA,KAAU;AAC1E,UAAM,uBAAuB,WAAW,YAAA;AACxC,UAAM,sBAAsB,UAAU,YAAA;AACtC,QAAI,CAAC,cAAc,oBAAoB,SAAS,oBAAoB,EAAG;AACvE,gBAAY,qBAAqB,WAAW,mBAAmB,IAAI,aAAa,GAAG,SAAS,IAAI,UAAU;AAAA,EAC5G;AACA,SAAO;AACT;AAcO,MAAM,iBAAuC;AAAA,EAClD,EAAE,KAAK,SAAS,SAAS,CAAC,WAAW,WAAW,OAAO,GAAG,QAAQ,KAAA;AAAA,EAClE,EAAE,KAAK,UAAU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BAAa,UAAU,EAAE;AACzB,4BAAsB,UAAU,qBAAqB,IAAI,sBAAsB,UAAU;AACzF,YAAM,eACJ,kBAAkB,WAAW,CAAC,uBAAuB,sBAAsB,WAAW;AACxF,UAAI,gBAAgB,eAAgB;AACpC,wBAAkB,UAAU;AAC5B,qBAAe,UAAU;AACzB,qBAAe,KAAK;AAAA,IACtB;AAEA,mBAAe,UAAU;AACzB,QAAI;AACF,kBAAY,MAAA;AACZ,aAAO;AAAA,IACT,SAAS,YAAY;AACnB,eAAS,KAAK,wCAAwC,UAAU;AAChE,wBAAkB,WAAW;AAC7B,qBAAe,UAAU;AACzB,eAAS,aAAa;AACtB,aAAO;AAAA,IACT;AAAA,EACF,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,QAAQ,YAAY,MAAM;AAC9B,aAAS,IAAI;AACb,0BAAsB,UAAU;AAChC,sBAAkB,UAAU;AAC5B,QAAI,gBAAgB;AAClB,qBAAe,IAAI;AACnB;AAAA,IACF;AACA,sBAAkB,UAAU;AAAA,EAC9B,GAAG,CAAC,YAAY,CAAC;AAEjB,QAAM,SAAS,YAAY,MAAM;AAC/B,QAAI,YAAa,MAAA;AAAA,QACZ,OAAA;AAAA,EACP,GAAG,CAAC,aAAa,OAAO,IAAI,CAAC;AAE7B;AAAA,IACE,MAAM,MAAM;AACV,wBAAkB,UAAU;AAC5B,YAAM,cAAc,eAAe;AACnC,UAAI,CAAC,YAAa;AAClB,wBAAkB,WAAW;AAC7B,qBAAe,UAAU;AACzB,kBAAY,MAAA;AAAA,IACd;AAAA,IACA,CAAA;AAAA,EAAC;AAGH,SAAO,EAAE,aAAa,aAAa,OAAO,QAAQ,KAAA;AACpD;"}
1
+ {"version":3,"file":"useVoiceTranscription.js","sources":["../../src/hooks/useVoiceTranscription.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\n\nimport {\n canRecordSpeech,\n ISpeechSegmentRecorder,\n SpeechRecorderError,\n startSpeechSegmentRecorder,\n} from '@/helpers/speechSegmentRecorder';\nimport { uiLogger } from '@/helpers/uiLogger';\nimport { readUiPreference, writeUiPreference } from '@/helpers/uiPreferences';\n\ninterface ISpeechRecognitionAlternative {\n transcript: string;\n}\n\ninterface ISpeechRecognitionResult {\n 0: ISpeechRecognitionAlternative;\n isFinal: boolean;\n}\n\ninterface ISpeechRecognitionEvent {\n resultIndex: number;\n results: { length: number; [index: number]: ISpeechRecognitionResult };\n}\n\ninterface ISpeechRecognition {\n lang: string;\n continuous: boolean;\n interimResults: boolean;\n start: () => void;\n stop: () => void;\n abort: () => void;\n onresult: ((event: ISpeechRecognitionEvent) => void) | null;\n onerror: ((event: { error: string }) => void) | null;\n onend: (() => void) | null;\n}\n\ntype TSpeechRecognitionCtor = new () => ISpeechRecognition;\n\nconst getRecognitionCtor = (): TSpeechRecognitionCtor | null => {\n const w = window as unknown as {\n SpeechRecognition?: TSpeechRecognitionCtor;\n webkitSpeechRecognition?: TSpeechRecognitionCtor;\n };\n return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;\n};\n\nexport interface IVoiceTranscriberRequest {\n /** BCP 47 tag of the language being spoken. */\n lang: string;\n signal: AbortSignal;\n}\n\n/** Turns one recorded phrase into text. Resolves with an empty string when nothing was said. */\nexport type TVoiceTranscriber = (audio: Blob, request: IVoiceTranscriberRequest) => Promise<string>;\n\nlet configuredTranscriber: TVoiceTranscriber | null = null;\nconst transcriberListeners = new Set<() => void>();\n\n/**\n * The host registers how recorded speech becomes text. It backs the browsers that ship no speech\n * engine (Firefox) or one that cannot reach its service (Arc, Brave, Opera): without it, those\n * browsers cannot dictate at all.\n */\nexport const configureVoiceTranscriber = (transcriber: TVoiceTranscriber | null): void => {\n configuredTranscriber = transcriber;\n transcriberListeners.forEach((listener) => listener());\n};\n\nconst canTranscribeRecordedSpeech = (): boolean => configuredTranscriber !== null && canRecordSpeech();\n\n/* The engines never appear or go away while a page is open; only the host's transcriber can arrive\n after the first render. The server answer is \"unsupported\": `window` is not there, and the first\n client render has to agree with it for hydration to hold. */\nconst subscribeToTranscriber = (listener: () => void) => {\n transcriberListeners.add(listener);\n return () => {\n transcriberListeners.delete(listener);\n };\n};\nconst isVoiceInputAvailable = () => getRecognitionCtor() !== null || canTranscribeRecordedSpeech();\nconst isUnavailableOnServer = () => false;\n\n/* A Chromium without Google's speech service (Arc, Brave, Opera, Vivaldi) exposes the API and fails\n every session with `network`. Once seen, dictation records instead, and the browser engine is\n tried again only after a week, in case it was a blocked network rather than the browser. */\nconst BROWSER_ENGINE_UNREACHABLE_PREFERENCE_KEY = 'umode-ui.voiceInput.browserEngineUnreachableAt';\nconst BROWSER_ENGINE_RETRY_AFTER_MS = 7 * 24 * 60 * 60 * 1000;\nconst BROWSER_ENGINE_FAILURES_TO_RECORD_INSTEAD: ReadonlySet<string> = new Set([\n 'network',\n 'service-not-allowed',\n 'language-not-supported',\n]);\n/* The engine could not open the microphone, which the page itself sometimes can: worth recording\n this once, but not remembered, since a microphone that is simply unplugged fails here too. */\nconst BROWSER_CAPTURE_FAILURES_TO_RECORD_INSTEAD: ReadonlySet<string> = new Set(['audio-capture']);\nlet browserEngineUnreachableThisPage = false;\n\nconst isBrowserEngineUnreachable = (): boolean => {\n if (browserEngineUnreachableThisPage) return true;\n const unreachableAt = readUiPreference<number>(BROWSER_ENGINE_UNREACHABLE_PREFERENCE_KEY);\n return typeof unreachableAt === 'number' && Date.now() - unreachableAt < BROWSER_ENGINE_RETRY_AFTER_MS;\n};\n\nconst rememberBrowserEngineUnreachable = () => {\n browserEngineUnreachableThisPage = true;\n writeUiPreference(BROWSER_ENGINE_UNREACHABLE_PREFERENCE_KEY, Date.now());\n};\n\n/* Phones run another engine behind the same API. Asked to listen continuously it delivers earlier\n phrases again and flags unfinished ones as final, so `isFinal` cannot be trusted there and a phone\n listens one utterance per session, restarting between them. iPadOS reports itself as a Mac. */\nconst listensOneUtterancePerSession = (): boolean => {\n const { userAgent, maxTouchPoints } = navigator;\n return /Android|iPhone|iPad|iPod/i.test(userAgent) || (/Macintosh/i.test(userAgent) && maxTouchPoints > 1);\n};\n\n/* Those engines either grow one result in place or deliver the text so far again as a new result,\n so a result that already holds what came before replaces it instead of being appended to it. */\nconst readUtterance = (event: ISpeechRecognitionEvent): string => {\n let utterance = '';\n for (let resultIndex = 0; resultIndex < event.results.length; resultIndex += 1) {\n const transcript = event.results[resultIndex]?.[0]?.transcript?.trim() ?? '';\n const normalizedTranscript = transcript.toLowerCase();\n const normalizedUtterance = utterance.toLowerCase();\n if (!transcript || normalizedUtterance.endsWith(normalizedTranscript)) continue;\n utterance = normalizedTranscript.startsWith(normalizedUtterance) ? transcript : `${utterance} ${transcript}`;\n }\n return utterance;\n};\n\nexport type TVoiceCommandKey = 'comma' | 'period' | 'newline' | 'space' | 'question' | 'exclamation' | 'deleteWord';\n\ninterface IVoiceCommand {\n key: TVoiceCommandKey;\n phrases: Array<string>;\n insert?: string;\n action?: 'deleteWord';\n}\n\n// Spoken keywords matched against the user's speech. They must stay as literal\n// recognition tokens (not UI strings), so the i18n check is disabled here.\n/* eslint-disable i18n-check/no-portuguese-strings */\nexport const VOICE_COMMANDS: Array<IVoiceCommand> = [\n { key: 'comma', phrases: ['vírgula', 'virgula', 'comma'], insert: ', ' },\n { key: 'period', phrases: ['ponto', 'ponto final', 'period'], insert: '. ' },\n { key: 'newline', phrases: ['nova linha', 'quebra de linha', 'parágrafo', 'paragrafo', 'new line'], insert: '\\n' },\n { key: 'space', phrases: ['espaço', 'espaco', 'space'], insert: ' ' },\n {\n key: 'question',\n phrases: ['interrogação', 'interrogacao', 'ponto de interrogação', 'question mark'],\n insert: '? ',\n },\n {\n key: 'exclamation',\n phrases: ['exclamação', 'exclamacao', 'ponto de exclamação', 'exclamation mark'],\n insert: '! ',\n },\n { key: 'deleteWord', phrases: ['apagar', 'apaga', 'apagar palavra', 'delete'], action: 'deleteWord' },\n];\n/* eslint-enable i18n-check/no-portuguese-strings */\n\nconst PHRASE_TO_COMMAND = new Map<string, IVoiceCommand>();\nfor (const command of VOICE_COMMANDS) {\n for (const phrase of command.phrases) PHRASE_TO_COMMAND.set(phrase, command);\n}\n\nconst normalize = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[.,!?;:]+$/, '');\n\nexport interface IVoiceTranscriptionUpdate {\n insert: string;\n deleteWords: number;\n}\n\nconst buildUpdateFromTranscript = (transcript: string): IVoiceTranscriptionUpdate => {\n const words = transcript.trim().split(/\\s+/).filter(Boolean);\n let insert = '';\n let deleteWords = 0;\n\n for (const word of words) {\n const command = PHRASE_TO_COMMAND.get(normalize(word));\n if (command?.action === 'deleteWord') {\n deleteWords += 1;\n insert = '';\n continue;\n }\n if (command?.insert !== undefined) {\n insert = insert.replace(/\\s+$/, '') + command.insert;\n continue;\n }\n insert += (insert && !insert.endsWith(' ') && !insert.endsWith('\\n') ? ' ' : '') + word;\n }\n\n return { insert, deleteWords };\n};\n\nconst appendTranscriptText = (current: string, addition: string): string => {\n if (!addition) return current;\n const needsSpace = current.length > 0 && !/\\s$/.test(current) && !/^[\\s.,!?]/.test(addition);\n return current + (needsSpace ? ' ' : '') + addition;\n};\n\nexport const applyVoiceUpdate = (current: string, update: IVoiceTranscriptionUpdate): string => {\n let next = current;\n for (let wordIndex = 0; wordIndex < update.deleteWords; wordIndex += 1) {\n next = next.replace(/\\s*\\S+\\s*$/, '');\n }\n return appendTranscriptText(next, update.insert);\n};\n\nexport const appendInterimTranscript = (committed: string, interim: string): string =>\n appendTranscriptText(committed, interim);\n\nexport type TVoiceTranscriptionError = 'permission' | 'microphone' | 'network' | 'unavailable';\n\n/** `browser`: the browser's own engine, live text. `recorder`: recorded phrases sent to the host. */\nexport type TVoiceTranscriptionEngine = 'browser' | 'recorder';\n\nconst RECOGNITION_ERROR_TO_VOICE_ERROR: Record<string, TVoiceTranscriptionError> = {\n 'not-allowed': 'permission',\n 'service-not-allowed': 'permission',\n 'audio-capture': 'microphone',\n network: 'network',\n 'language-not-supported': 'unavailable',\n 'bad-grammar': 'unavailable',\n};\n\nconst MAX_SILENT_RESTARTS = 2;\n\ninterface IUseVoiceTranscriptionParams {\n lang?: string;\n onCommit: (update: IVoiceTranscriptionUpdate) => void;\n onInterim?: (text: string) => void;\n}\n\ninterface IUseVoiceTranscriptionResult {\n isSupported: boolean;\n isListening: boolean;\n /** Recorded speech whose text has not arrived yet. Only the recorder engine waits for text. */\n isTranscribing: boolean;\n /** The engine of the current (or last) dictation. */\n engine: TVoiceTranscriptionEngine | null;\n error: TVoiceTranscriptionError | null;\n toggle: () => void;\n stop: () => void;\n}\n\ntype TTranscriptOutcome = { ok: true; text: string } | { ok: false; error: unknown };\n\nconst settleTranscript = async (\n transcriber: TVoiceTranscriber,\n segment: Blob,\n request: IVoiceTranscriberRequest,\n): Promise<TTranscriptOutcome> => {\n try {\n return { ok: true, text: await transcriber(segment, request) };\n } catch (error) {\n return { ok: false, error };\n }\n};\n\nconst detachRecognition = (recognition: ISpeechRecognition) => {\n recognition.onresult = null;\n recognition.onerror = null;\n recognition.onend = null;\n};\n\nexport const useVoiceTranscription = ({\n lang = 'pt-BR',\n onCommit,\n onInterim,\n}: IUseVoiceTranscriptionParams): IUseVoiceTranscriptionResult => {\n const [isListening, setIsListening] = useState(false);\n const [pendingSegmentCount, setPendingSegmentCount] = useState(0);\n const [engine, setEngine] = useState<TVoiceTranscriptionEngine | null>(null);\n const [error, setError] = useState<TVoiceTranscriptionError | null>(null);\n const recognitionRef = useRef<ISpeechRecognition | null>(null);\n const segmentRecorderRef = useRef<ISpeechSegmentRecorder | null>(null);\n const activeEngineRef = useRef<TVoiceTranscriptionEngine | null>(null);\n const recorderStartIdRef = useRef(0);\n const commitQueueRef = useRef<Promise<void>>(Promise.resolve());\n const unmountControllerRef = useRef<AbortController | null>(null);\n const isMountedRef = useRef(true);\n const wantsListeningRef = useRef(false);\n const silentRestartCountRef = useRef(0);\n const onCommitRef = useRef(onCommit);\n const onInterimRef = useRef(onInterim);\n\n onCommitRef.current = onCommit;\n onInterimRef.current = onInterim;\n\n const isSupported = useSyncExternalStore(subscribeToTranscriber, isVoiceInputAvailable, isUnavailableOnServer);\n\n const resolveUnmountSignal = (): AbortSignal => {\n if (!unmountControllerRef.current) unmountControllerRef.current = new AbortController();\n return unmountControllerRef.current.signal;\n };\n\n const finishListening = useCallback(() => {\n wantsListeningRef.current = false;\n setIsListening(false);\n }, []);\n\n const detachSegmentRecorder = useCallback((): ISpeechSegmentRecorder | null => {\n recorderStartIdRef.current += 1;\n const segmentRecorder = segmentRecorderRef.current;\n segmentRecorderRef.current = null;\n return segmentRecorder;\n }, []);\n\n /* The phrase in progress reaches `transcribeSegment` only when the recorder has closed it, a moment\n after `stop`; counting that moment as pending keeps `isTranscribing` true with no gap, so a host\n waiting for the text never reads \"done\" before the last phrase arrives. */\n const stopSegmentRecorder = useCallback(async () => {\n const segmentRecorder = detachSegmentRecorder();\n if (!segmentRecorder) return;\n setPendingSegmentCount((count) => count + 1);\n try {\n await segmentRecorder.stop();\n } finally {\n if (isMountedRef.current) setPendingSegmentCount((count) => Math.max(0, count - 1));\n }\n }, [detachSegmentRecorder]);\n\n const abortSegmentRecorder = useCallback(() => {\n detachSegmentRecorder()?.abort();\n }, [detachSegmentRecorder]);\n\n /* Every phrase is sent the moment it ends, so several can be in flight; the queue writes them in\n the order they were spoken, whatever order the answers come back in. */\n const transcribeSegment = useCallback(\n (segment: Blob) => {\n const transcriber = configuredTranscriber;\n if (!transcriber) return;\n\n setPendingSegmentCount((count) => count + 1);\n const outcome = settleTranscript(transcriber, segment, { lang, signal: resolveUnmountSignal() });\n const previousCommit = commitQueueRef.current;\n\n const commitInOrder = async () => {\n await previousCommit;\n const settled = await outcome;\n if (!isMountedRef.current) return;\n setPendingSegmentCount((count) => Math.max(0, count - 1));\n\n if (!settled.ok) {\n uiLogger.warn('[useVoiceTranscription] transcription failed', settled.error);\n setError('network');\n abortSegmentRecorder();\n finishListening();\n return;\n }\n\n if (!settled.text.trim()) return;\n try {\n onCommitRef.current(buildUpdateFromTranscript(settled.text));\n } catch (commitError) {\n uiLogger.error('[useVoiceTranscription] writing the transcript failed', commitError);\n }\n };\n commitQueueRef.current = commitInOrder();\n },\n [abortSegmentRecorder, finishListening, lang],\n );\n\n const startSegmentRecorder = useCallback(async () => {\n const startId = recorderStartIdRef.current + 1;\n recorderStartIdRef.current = startId;\n activeEngineRef.current = 'recorder';\n setEngine('recorder');\n setIsListening(true);\n\n try {\n const segmentRecorder = await startSpeechSegmentRecorder({\n onSegment: transcribeSegment,\n onIdle: () => {\n if (segmentRecorderRef.current !== segmentRecorder) return;\n segmentRecorderRef.current = null;\n finishListening();\n },\n onInterrupted: () => {\n if (segmentRecorderRef.current !== segmentRecorder) return;\n segmentRecorderRef.current = null;\n setError('microphone');\n finishListening();\n },\n });\n\n // Stopped (or unmounted) while the microphone permission was still being asked.\n if (recorderStartIdRef.current !== startId || !wantsListeningRef.current) {\n segmentRecorder.abort();\n return;\n }\n segmentRecorderRef.current = segmentRecorder;\n } catch (startError) {\n if (recorderStartIdRef.current !== startId || !isMountedRef.current) return;\n uiLogger.warn('[useVoiceTranscription] recorder failed to start', startError);\n setError(startError instanceof SpeechRecorderError ? startError.failure : 'unavailable');\n finishListening();\n }\n }, [finishListening, transcribeSegment]);\n\n const stop = useCallback(() => {\n wantsListeningRef.current = false;\n recognitionRef.current?.stop();\n if (activeEngineRef.current === 'recorder') {\n void stopSegmentRecorder();\n setIsListening(false);\n }\n }, [stopSegmentRecorder]);\n\n const startSession = useCallback((): boolean => {\n const Ctor = getRecognitionCtor();\n if (!Ctor) return false;\n\n const oneUtterancePerSession = listensOneUtterancePerSession();\n\n const recognition = new Ctor();\n recognition.lang = lang;\n recognition.continuous = !oneUtterancePerSession;\n recognition.interimResults = true;\n\n let sessionHeardSpeech = false;\n let sessionEndedByError = false;\n let uncommittedTranscript = '';\n\n recognition.onresult = (event) => {\n if (recognitionRef.current !== recognition) return;\n sessionHeardSpeech = true;\n\n if (oneUtterancePerSession) {\n uncommittedTranscript = readUtterance(event);\n onInterimRef.current?.(uncommittedTranscript);\n return;\n }\n\n let interim = '';\n for (let resultIndex = event.resultIndex; resultIndex < event.results.length; resultIndex += 1) {\n const result = event.results[resultIndex];\n const transcript = result?.[0]?.transcript ?? '';\n if (result?.isFinal) {\n onCommitRef.current(buildUpdateFromTranscript(transcript));\n } else {\n interim += transcript;\n }\n }\n uncommittedTranscript = interim.trim();\n onInterimRef.current?.(uncommittedTranscript);\n };\n\n recognition.onerror = (event) => {\n if (recognitionRef.current !== recognition) return;\n if (event.error === 'no-speech') return;\n sessionEndedByError = true;\n if (event.error === 'aborted') return;\n uiLogger.warn('[useVoiceTranscription] error', event.error);\n\n const browserEngineIsUnreachable = BROWSER_ENGINE_FAILURES_TO_RECORD_INSTEAD.has(event.error);\n const recordsInstead = browserEngineIsUnreachable || BROWSER_CAPTURE_FAILURES_TO_RECORD_INSTEAD.has(event.error);\n\n if (wantsListeningRef.current && recordsInstead && canTranscribeRecordedSpeech()) {\n if (browserEngineIsUnreachable) rememberBrowserEngineUnreachable();\n detachRecognition(recognition);\n recognitionRef.current = null;\n recognition.abort();\n if (uncommittedTranscript) onCommitRef.current(buildUpdateFromTranscript(uncommittedTranscript));\n onInterimRef.current?.('');\n void startSegmentRecorder();\n return;\n }\n\n setError(RECOGNITION_ERROR_TO_VOICE_ERROR[event.error] ?? 'unavailable');\n };\n\n recognition.onend = () => {\n if (recognitionRef.current !== recognition) return;\n if (uncommittedTranscript) onCommitRef.current(buildUpdateFromTranscript(uncommittedTranscript));\n onInterimRef.current?.('');\n silentRestartCountRef.current = sessionHeardSpeech ? 0 : silentRestartCountRef.current + 1;\n const shouldResume =\n wantsListeningRef.current && !sessionEndedByError && silentRestartCountRef.current <= MAX_SILENT_RESTARTS;\n if (shouldResume && startSession()) return;\n wantsListeningRef.current = false;\n recognitionRef.current = null;\n setIsListening(false);\n };\n\n recognitionRef.current = recognition;\n try {\n recognition.start();\n return true;\n } catch (startError) {\n uiLogger.warn('[useVoiceTranscription] start failed', startError);\n detachRecognition(recognition);\n recognitionRef.current = null;\n setError('unavailable');\n return false;\n }\n }, [lang, startSegmentRecorder]);\n\n const start = useCallback(() => {\n setError(null);\n silentRestartCountRef.current = 0;\n wantsListeningRef.current = true;\n\n const canRecordInstead = canTranscribeRecordedSpeech();\n const prefersBrowserEngine = getRecognitionCtor() !== null && (!canRecordInstead || !isBrowserEngineUnreachable());\n\n if (prefersBrowserEngine && startSession()) {\n activeEngineRef.current = 'browser';\n setEngine('browser');\n setIsListening(true);\n return;\n }\n\n if (canRecordInstead) {\n setError(null);\n void startSegmentRecorder();\n return;\n }\n\n wantsListeningRef.current = false;\n if (!prefersBrowserEngine) setError('unavailable');\n }, [startSegmentRecorder, startSession]);\n\n const toggle = useCallback(() => {\n if (isListening) stop();\n else start();\n }, [isListening, start, stop]);\n\n useEffect(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n wantsListeningRef.current = false;\n recorderStartIdRef.current += 1;\n segmentRecorderRef.current?.abort();\n segmentRecorderRef.current = null;\n unmountControllerRef.current?.abort();\n unmountControllerRef.current = null;\n const recognition = recognitionRef.current;\n if (!recognition) return;\n detachRecognition(recognition);\n recognitionRef.current = null;\n recognition.abort();\n };\n }, []);\n\n return {\n isSupported,\n isListening,\n isTranscribing: pendingSegmentCount > 0,\n engine,\n error,\n toggle,\n stop,\n };\n};\n"],"names":[],"mappings":";;;;AAuCA,MAAM,qBAAqB,MAAqC;AAC9D,QAAM,IAAI;AAIV,SAAO,EAAE,qBAAqB,EAAE,2BAA2B;AAC7D;AAWA,IAAI,wBAAkD;AACtD,MAAM,2CAA2B,IAAA;AAO1B,MAAM,4BAA4B,CAAC,gBAAgD;AACxF,0BAAwB;AACxB,uBAAqB,QAAQ,CAAC,aAAa,SAAA,CAAU;AACvD;AAEA,MAAM,8BAA8B,MAAe,0BAA0B,QAAQ,gBAAA;AAKrF,MAAM,yBAAyB,CAAC,aAAyB;AACvD,uBAAqB,IAAI,QAAQ;AACjC,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13 @@ declare const _default: {
668
668
  "voiceInput": {
669
669
  "start": "Transcribe by voice",
670
670
  "stop": "Stop transcription",
671
+ "listeningInPauses": "Listening. The text shows up at each pause in your speech.",
672
+ "transcribing": "Transcribing what you said...",
671
673
  "commandsHint": "Voice commands: say {{commands}} to insert punctuation or delete the last word.",
672
674
  "errors": {
673
675
  "permission": "Microphone access was blocked. Allow the microphone in your browser permissions and try again.",
674
676
  "microphone": "No microphone was found. Connect a microphone and try again.",
675
- "network": "The browser's transcription service did not respond. Check your connection or use Google Chrome or Microsoft Edge.",
677
+ "network": "The transcription service did not respond. Check your connection and try again.",
676
678
  "unavailable": "Voice transcription is not available in this browser. Use Google Chrome or Microsoft Edge."
677
679
  }
678
680
  }
@@ -35,7 +35,7 @@ const unifiedSearchBar = { "clearFilter": "Clear filter" };
35
35
  const uploader = { "dragOr": "Drag or", "selectFile": "select a file", "orPaste": "or paste (Ctrl+V)", "allowedFormats": "Allowed formats:", "upTo": "up to", "megabytesSuffix": "MB", "sendFiles": "Send file(s)", "filesIgnoredMaxSize": "Some files were ignored because they exceeded the maximum size of {{size}}MB", "invalidFormat": "Please add files in the allowed formats", "allowedFormatsTooltip": "Allowed formats: {{formats}} up to {{size}}MB" };
36
36
  const urlLinkCell = { "clickToAccess": "Click to access" };
37
37
  const userMenu = { "loading": "Loading...", "yourAccounts": "Your Accounts", "searchAccount": "Search account", "noAccounts": "No active accounts available", "logout": "Sign out" };
38
- const voiceInput = { "start": "Transcribe by voice", "stop": "Stop transcription", "commandsHint": "Voice commands: say {{commands}} to insert punctuation or delete the last word.", "errors": { "permission": "Microphone access was blocked. Allow the microphone in your browser permissions and try again.", "microphone": "No microphone was found. Connect a microphone and try again.", "network": "The browser's transcription service did not respond. Check your connection or use Google Chrome or Microsoft Edge.", "unavailable": "Voice transcription is not available in this browser. Use Google Chrome or Microsoft Edge." } };
38
+ const voiceInput = { "start": "Transcribe by voice", "stop": "Stop transcription", "listeningInPauses": "Listening. The text shows up at each pause in your speech.", "transcribing": "Transcribing what you said...", "commandsHint": "Voice commands: say {{commands}} to insert punctuation or delete the last word.", "errors": { "permission": "Microphone access was blocked. Allow the microphone in your browser permissions and try again.", "microphone": "No microphone was found. Connect a microphone and try again.", "network": "The transcription service did not respond. Check your connection and try again.", "unavailable": "Voice transcription is not available in this browser. Use Google Chrome or Microsoft Edge." } };
39
39
  const en = {
40
40
  accordion,
41
41
  actions,
@@ -670,6 +670,8 @@ export declare const uiLocales: {
670
670
  voiceInput: {
671
671
  start: string;
672
672
  stop: string;
673
+ listeningInPauses: string;
674
+ transcribing: string;
673
675
  commandsHint: string;
674
676
  errors: {
675
677
  permission: string;
@@ -1349,6 +1351,8 @@ export declare const uiLocales: {
1349
1351
  voiceInput: {
1350
1352
  start: string;
1351
1353
  stop: string;
1354
+ listeningInPauses: string;
1355
+ transcribing: string;
1352
1356
  commandsHint: string;
1353
1357
  errors: {
1354
1358
  permission: string;
@@ -668,11 +668,13 @@ declare const _default: {
668
668
  "voiceInput": {
669
669
  "start": "Transcrever por voz",
670
670
  "stop": "Parar transcrição",
671
+ "listeningInPauses": "Ouvindo. O texto aparece a cada pausa na fala.",
672
+ "transcribing": "Transcrevendo o que você falou...",
671
673
  "commandsHint": "Comandos de voz: diga {{commands}} para inserir pontuação ou apagar a última palavra.",
672
674
  "errors": {
673
675
  "permission": "O acesso ao microfone foi bloqueado. Libere o microfone nas permissões do navegador e tente de novo.",
674
676
  "microphone": "Nenhum microfone foi encontrado. Conecte um microfone e tente de novo.",
675
- "network": "O serviço de transcrição do navegador não respondeu. Verifique a conexão ou use o Google Chrome ou o Microsoft Edge.",
677
+ "network": "O serviço de transcrição não respondeu. Verifique a conexão e tente de novo.",
676
678
  "unavailable": "A transcrição por voz não está disponível neste navegador. Use o Google Chrome ou o Microsoft Edge."
677
679
  }
678
680
  }
@@ -35,7 +35,7 @@ const unifiedSearchBar = { "clearFilter": "Limpar Filtro" };
35
35
  const uploader = { "dragOr": "Arraste ou", "selectFile": "selecione um arquivo", "orPaste": "ou cole (Ctrl+V)", "allowedFormats": "Formatos permitidos:", "upTo": "até", "megabytesSuffix": "MB", "sendFiles": "Enviar arquivo(s)", "filesIgnoredMaxSize": "Alguns arquivos foram ignorados porque excederam o tamanho máximo de {{size}}MB", "invalidFormat": "Por favor, insira arquivos nos formatos permitidos", "allowedFormatsTooltip": "Formatos permitidos: {{formats}} até {{size}}MB" };
36
36
  const urlLinkCell = { "clickToAccess": "Clique para acessar" };
37
37
  const userMenu = { "loading": "Carregando...", "yourAccounts": "Suas Contas", "searchAccount": "Buscar conta", "noAccounts": "Nenhuma conta ativa disponível", "logout": "Sair" };
38
- const voiceInput = { "start": "Transcrever por voz", "stop": "Parar transcrição", "commandsHint": "Comandos de voz: diga {{commands}} para inserir pontuação ou apagar a última palavra.", "errors": { "permission": "O acesso ao microfone foi bloqueado. Libere o microfone nas permissões do navegador e tente de novo.", "microphone": "Nenhum microfone foi encontrado. Conecte um microfone e tente de novo.", "network": "O serviço de transcrição do navegador não respondeu. Verifique a conexão ou use o Google Chrome ou o Microsoft Edge.", "unavailable": "A transcrição por voz não está disponível neste navegador. Use o Google Chrome ou o Microsoft Edge." } };
38
+ const voiceInput = { "start": "Transcrever por voz", "stop": "Parar transcrição", "listeningInPauses": "Ouvindo. O texto aparece a cada pausa na fala.", "transcribing": "Transcrevendo o que você falou...", "commandsHint": "Comandos de voz: diga {{commands}} para inserir pontuação ou apagar a última palavra.", "errors": { "permission": "O acesso ao microfone foi bloqueado. Libere o microfone nas permissões do navegador e tente de novo.", "microphone": "Nenhum microfone foi encontrado. Conecte um microfone e tente de novo.", "network": "O serviço de transcrição não respondeu. Verifique a conexão e tente de novo.", "unavailable": "A transcrição por voz não está disponível neste navegador. Use o Google Chrome ou o Microsoft Edge." } };
39
39
  const pt = {
40
40
  accordion,
41
41
  actions,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umodeapporg/ui",
3
- "version": "0.32.0",
3
+ "version": "0.33.0",
4
4
  "license": "UNLICENSED",
5
5
  "type": "module",
6
6
  "sideEffects": [