@djangocfg/ui-core 2.1.641 → 2.1.643

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.
package/README.md CHANGED
@@ -114,7 +114,8 @@ fields (`DateField` / `TimeField` / `DateTimeField`) have their own reference in
114
114
  |---|---|
115
115
  | `dom/` | `useSize` · `useResizeObserver` · `useMeasure` · `useMutationObserver` · `useIntersection` · `useHighlight` |
116
116
  | `device/` | `useIsMobile` · `useIsTouch` · `useMediaQuery` · `useOnline` · `useViewportSize` · `useOrientation` |
117
- | `state/` | `useLocalStorage` · `useSessionStorage` · `useToggle` · `useCounter` · `useDebouncedValue` |
117
+ | `state/` | `useDebounce` · `useDebouncedCallback` · `useStateMachine` · `useCallbackRef` · `usePrevious` |
118
+ | `storage/` | `useLocalStorage` · `useSessionStorage` · `useStoredValue` · the key scheme (`storage-namespace`) |
118
119
  | `events/` | `useEventListener` · `useClickOutside` · `useKeyPress` · `useFocusWithin` |
119
120
  | `theme/` | `useTheme` · `useResolvedTheme` · `useThemePreset` |
120
121
  | `feedback/` | `useToast` · `useDialog` · `useClipboard` · `useConfirm` |
@@ -125,7 +126,7 @@ fields (`DateField` / `TimeField` / `DateTimeField`) have their own reference in
125
126
  | `time/` | `useNow` · `useInterval` · `useTimeout` |
126
127
  | `router/` | `useLink` · `useRouter` (router-adapter consumer) |
127
128
 
128
- ### Storage keys and namespaces (`hooks/state`)
129
+ ### Storage keys and namespaces (`hooks/storage`)
129
130
 
130
131
  `useLocalStorage`, `useSessionStorage` and `useStoredValue` (every component
131
132
  `storageKey` prop) write under one scheme, `<owner>.<area>.<name>`, e.g.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djangocfg/ui-core",
3
- "version": "2.1.641",
3
+ "version": "2.1.643",
4
4
  "description": "Pure React UI component library without Next.js dependencies - for Electron, Vite, CRA apps",
5
5
  "keywords": [
6
6
  "ui-components",
@@ -81,6 +81,11 @@
81
81
  "import": "./src/lib/dialog-service/index.ts",
82
82
  "require": "./src/lib/dialog-service/index.ts"
83
83
  },
84
+ "./lib/speech-language": {
85
+ "types": "./src/lib/speech-language/index.ts",
86
+ "import": "./src/lib/speech-language/index.ts",
87
+ "require": "./src/lib/speech-language/index.ts"
88
+ },
84
89
  "./lib/pretext": {
85
90
  "types": "./src/lib/pretext/index.ts",
86
91
  "import": "./src/lib/pretext/index.ts",
@@ -139,8 +144,8 @@
139
144
  "check:docs": "node scripts/check-docs.mjs"
140
145
  },
141
146
  "peerDependencies": {
142
- "@djangocfg/api": "^2.1.641",
143
- "@djangocfg/i18n": "^2.1.641",
147
+ "@djangocfg/api": "^2.1.643",
148
+ "@djangocfg/i18n": "^2.1.643",
144
149
  "consola": "^3.4.2",
145
150
  "lucide-react": "^1.68.0",
146
151
  "moment": "^2.30.1",
@@ -215,10 +220,10 @@
215
220
  "vaul": "1.1.2"
216
221
  },
217
222
  "devDependencies": {
218
- "@djangocfg/api": "^2.1.641",
219
- "@djangocfg/eslint-config": "^2.1.641",
220
- "@djangocfg/i18n": "^2.1.641",
221
- "@djangocfg/typescript-config": "^2.1.641",
223
+ "@djangocfg/api": "^2.1.643",
224
+ "@djangocfg/eslint-config": "^2.1.643",
225
+ "@djangocfg/i18n": "^2.1.643",
226
+ "@djangocfg/typescript-config": "^2.1.643",
222
227
  "@storybook/react-vite": "^10.6.5",
223
228
  "@types/node": "^24.13.3",
224
229
  "@types/react": "19.3.0",
@@ -40,7 +40,7 @@ TooltipContent.displayName = TooltipPrimitive.Content.displayName
40
40
 
41
41
  /** What a control says about itself on hover: a text (or node), or this config. One shape for every control that takes a `tooltip` prop. */
42
42
  export interface TooltipConfig {
43
- /** The name of the action. */
43
+ /** The name of the action. Pass `null` for a hotkey-only hint (an icon that already says what it does). */
44
44
  content: React.ReactNode
45
45
  /** A `useHotkey` string (`mod+j`), shown after the content in a muted tone, written for the viewer's system (⌘J on a Mac, Ctrl+J elsewhere). */
46
46
  hotkey?: string
@@ -77,7 +77,7 @@ function TooltipHint({ tooltip, children, disabled = false }: { tooltip: Tooltip
77
77
  sideOffset={config.sideOffset}
78
78
  className={cn('flex items-center gap-3', config.hotkey ? 'whitespace-nowrap' : undefined, config.hoverable && 'pointer-events-auto')}
79
79
  >
80
- <span>{config.content}</span>
80
+ {config.content != null && config.content !== '' ? <span>{config.content}</span> : null}
81
81
  {config.hotkey ? <span className="opacity-60">{formatHotkey(config.hotkey)}</span> : null}
82
82
  </TooltipContent>
83
83
  </TooltipPrimitive.Root>
@@ -4,6 +4,8 @@ export { useBrowserDetect } from './useBrowserDetect';
4
4
  export type { BrowserInfo } from './useBrowserDetect';
5
5
  export { useDeviceDetect } from './useDeviceDetect';
6
6
  export type { DeviceDetectResult } from './useDeviceDetect';
7
+ export { useBrowserLanguages } from './useBrowserLanguages';
8
+ export type { BrowserLanguages } from './useBrowserLanguages';
7
9
  export { useShortcutModLabel } from './useShortcutModLabel';
8
10
  export { useTouchSafeStyle } from './useTouchSafeStyle';
9
11
  export type { TouchSafeStyleOptions } from './useTouchSafeStyle';
@@ -0,0 +1,57 @@
1
+ 'use client';
2
+
3
+ import { useSyncExternalStore } from 'react';
4
+
5
+ /** What the browser says about the reader's languages. */
6
+ export interface BrowserLanguages {
7
+ /** `navigator.languages` in the browser's own order (`navigator.language` alone when the list is empty). Empty on the server and on the first client render. */
8
+ languages: readonly string[]
9
+ /** `navigator.language`, or `undefined` where there is none. */
10
+ primary: string | undefined
11
+ /** The locale the runtime formats dates with (`Intl`), taken from the OS region/language settings. A weak extra signal when `languages` says nothing usable. */
12
+ intl: string | undefined
13
+ }
14
+
15
+ const EMPTY: BrowserLanguages = { languages: [], primary: undefined, intl: undefined };
16
+
17
+ let cached: BrowserLanguages = EMPTY;
18
+ let cachedKey = '';
19
+
20
+ function snapshot(): BrowserLanguages {
21
+ if (typeof navigator === 'undefined') return EMPTY;
22
+ const languages = navigator.languages?.length ? [...navigator.languages] : navigator.language ? [navigator.language] : [];
23
+ let intl: string | undefined;
24
+ try {
25
+ intl = Intl.DateTimeFormat().resolvedOptions().locale || undefined;
26
+ } catch {
27
+ intl = undefined;
28
+ }
29
+ const key = `${languages.join(',')}|${navigator.language ?? ''}|${intl ?? ''}`;
30
+ // useSyncExternalStore needs the SAME object while nothing changed, or it loops.
31
+ if (key !== cachedKey) {
32
+ cachedKey = key;
33
+ cached = { languages, primary: navigator.language || undefined, intl };
34
+ }
35
+ return cached;
36
+ }
37
+
38
+ function subscribe(onChange: () => void): () => void {
39
+ window.addEventListener('languagechange', onChange);
40
+ return () => window.removeEventListener('languagechange', onChange);
41
+ }
42
+
43
+ /**
44
+ * The reader's languages as the browser reports them, kept current on `languagechange`.
45
+ * Raw tags, not a decision: what to do with them (speech, translation, a default
46
+ * locale) belongs to the caller, which knows which tags it supports.
47
+ *
48
+ * SSR-safe: the server and the first client render both see empty values, so
49
+ * nothing mismatches on hydration; the real values arrive right after.
50
+ *
51
+ * @example
52
+ * const { languages } = useBrowserLanguages()
53
+ * const first = languages.find((tag) => supported.has(tag.split('-')[0]))
54
+ */
55
+ export function useBrowserLanguages(): BrowserLanguages {
56
+ return useSyncExternalStore(subscribe, snapshot, () => EMPTY);
57
+ }
@@ -12,6 +12,7 @@
12
12
 
13
13
  export * from './dom';
14
14
  export * from './state';
15
+ export * from './storage';
15
16
  export * from './media';
16
17
  export * from './device';
17
18
  export * from './feedback';
@@ -2,36 +2,7 @@
2
2
 
3
3
  export { useDebounce } from './useDebounce';
4
4
  export { useDebouncedCallback } from './useDebouncedCallback';
5
- export { useLocalStorage } from './useLocalStorage';
6
- export type { UseLocalStorageOptions, UseLocalStorageReturn } from './useLocalStorage';
7
- export { useSessionStorage } from './useSessionStorage';
8
- export type {
9
- UseSessionStorageOptions,
10
- UseSessionStorageReturn,
11
- } from './useSessionStorage';
12
- export { useStoredValue } from './useStoredValue';
13
- export type {
14
- UseStoredValueOptions,
15
- UseStoredValueReturn,
16
- StorageType,
17
- } from './useStoredValue';
18
5
  export { useStateMachine } from './useStateMachine';
19
6
  export type { StateMachineConfig } from './useStateMachine';
20
7
  export { useCallbackRef } from './useCallbackRef';
21
8
  export { usePrevious } from './usePrevious';
22
- export {
23
- DEFAULT_STORAGE_NAMESPACE,
24
- StorageNamespaceProvider,
25
- useStorageNamespace,
26
- resolveStorageKey,
27
- isSchemeKey,
28
- listStorageKeys,
29
- clearStorageNamespace,
30
- createStorageNamespace,
31
- } from './storage-namespace';
32
- export type {
33
- StorageNamespace,
34
- StorageNamespaceProviderProps,
35
- StorageArea,
36
- ClearStorageOptions,
37
- } from './storage-namespace';
@@ -0,0 +1,38 @@
1
+ 'use client';
2
+
3
+ // Everything that remembers a value between renders, visits or tabs:
4
+ // useLocalStorage / useSessionStorage — one key, validated on read, healed when broken
5
+ // useStoredValue — the `storageKey` prop of form components
6
+ // storage-namespace — the key scheme (`<owner>.<area>.<name>`) and its cleanup
7
+ // storage-quota — recovery when the browser's quota is full
8
+ // The decoding rule shared with `@djangocfg/api` lives in `@djangocfg/api/storage` (`decodeStored`).
9
+
10
+ export { useLocalStorage } from './useLocalStorage';
11
+ export type { UseLocalStorageOptions, UseLocalStorageReturn } from './useLocalStorage';
12
+ export { useSessionStorage } from './useSessionStorage';
13
+ export type {
14
+ UseSessionStorageOptions,
15
+ UseSessionStorageReturn,
16
+ } from './useSessionStorage';
17
+ export { useStoredValue } from './useStoredValue';
18
+ export type {
19
+ UseStoredValueOptions,
20
+ UseStoredValueReturn,
21
+ StorageType,
22
+ } from './useStoredValue';
23
+ export {
24
+ DEFAULT_STORAGE_NAMESPACE,
25
+ StorageNamespaceProvider,
26
+ useStorageNamespace,
27
+ resolveStorageKey,
28
+ isSchemeKey,
29
+ listStorageKeys,
30
+ clearStorageNamespace,
31
+ createStorageNamespace,
32
+ } from './storage-namespace';
33
+ export type {
34
+ StorageNamespace,
35
+ StorageNamespaceProviderProps,
36
+ StorageArea,
37
+ ClearStorageOptions,
38
+ } from './storage-namespace';
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Reading a stored value without trusting it.
3
+ *
4
+ * What sits in `localStorage` was written by an earlier build of the app, by
5
+ * another tab, by a browser extension or by hand. A value of the wrong shape must
6
+ * never reach a component: it is treated as absent, the key is healed (removed),
7
+ * and the caller falls back to its initial value. Losing a stale preference is
8
+ * always cheaper than crashing on it.
9
+ *
10
+ * Shared by `useLocalStorage` and `useSessionStorage`, so both heal the same way.
11
+ */
12
+
13
+ interface StorageWrapper<T> {
14
+ _meta: { createdAt: number; ttl: number };
15
+ _value: T;
16
+ }
17
+
18
+ export type StorageValidator<T> = (value: unknown) => value is T;
19
+
20
+ function isWrapped<T>(data: unknown): data is StorageWrapper<T> {
21
+ return (
22
+ data !== null &&
23
+ typeof data === 'object' &&
24
+ '_meta' in data &&
25
+ '_value' in data &&
26
+ typeof (data as StorageWrapper<T>)._meta === 'object' &&
27
+ typeof (data as StorageWrapper<T>)._meta.createdAt === 'number'
28
+ );
29
+ }
30
+
31
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
32
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
33
+ }
34
+
35
+ /**
36
+ * Does `value` have the same shape as `initial`?
37
+ *
38
+ * - `null` / `undefined` initial: anything goes (the caller declared no shape).
39
+ * - primitives: same `typeof`.
40
+ * - arrays: an array.
41
+ * - plain objects: an object whose keys that exist in both have the same
42
+ * `typeof` (an object field that was a string and is now a number is a stale
43
+ * shape). Keys missing from the stored value are fine: they are filled from
44
+ * `initial`, which is how a field added in a later release arrives.
45
+ */
46
+ function conforms(value: unknown, initial: unknown): boolean {
47
+ if (initial === null || initial === undefined) return true;
48
+ if (Array.isArray(initial)) return Array.isArray(value);
49
+ if (isPlainObject(initial)) {
50
+ if (!isPlainObject(value)) return false;
51
+ for (const key of Object.keys(initial)) {
52
+ if (!(key in value)) continue;
53
+ const a = initial[key];
54
+ const b = value[key];
55
+ if (a === null || a === undefined || b === null || b === undefined) continue;
56
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
57
+ if (typeof a !== typeof b) return false;
58
+ }
59
+ return true;
60
+ }
61
+ return typeof value === typeof initial;
62
+ }
63
+
64
+ export type DecodeResult<T> = { ok: true; value: T } | { ok: false; reason: 'absent' | 'expired' | 'invalid' };
65
+
66
+ /**
67
+ * Turn a raw stored string into a `T`, or say why not. Never throws.
68
+ *
69
+ * `bareStrings`: whether a non-JSON string is a valid stored string (the hooks that
70
+ * write strings without quotes) or corruption (the hook that always JSON-encodes).
71
+ *
72
+ * `validate` replaces the shape check when a caller knows better (a union, an
73
+ * enum, a range). It is guarded: a validator that throws counts as "invalid".
74
+ */
75
+ export function decodeStored<T>(
76
+ raw: string | null,
77
+ initial: T,
78
+ validate?: StorageValidator<T>,
79
+ bareStrings = true,
80
+ ): DecodeResult<T> {
81
+ if (raw === null) return { ok: false, reason: 'absent' };
82
+
83
+ let value: unknown;
84
+ try {
85
+ value = JSON.parse(raw);
86
+ } catch {
87
+ // Not JSON. Strings are stored bare, so for a string value this IS the value;
88
+ // for anything else it is garbage and must not be cast into a `T`.
89
+ value = bareStrings && typeof initial === 'string' ? raw : undefined;
90
+ if (value === undefined) return { ok: false, reason: 'invalid' };
91
+ }
92
+
93
+ if (isWrapped<unknown>(value)) {
94
+ const { createdAt, ttl } = value._meta;
95
+ if (ttl && Date.now() - createdAt > ttl) return { ok: false, reason: 'expired' };
96
+ value = value._value;
97
+ }
98
+
99
+ try {
100
+ if (validate) return validate(value) ? { ok: true, value } : { ok: false, reason: 'invalid' };
101
+ if (!conforms(value, initial)) return { ok: false, reason: 'invalid' };
102
+ } catch {
103
+ return { ok: false, reason: 'invalid' };
104
+ }
105
+
106
+ if (isPlainObject(initial) && isPlainObject(value) && !validate) {
107
+ return { ok: true, value: { ...initial, ...value } as T };
108
+ }
109
+ return { ok: true, value: value as T };
110
+ }
@@ -3,6 +3,7 @@
3
3
  import { useCallback, useEffect, useRef, useState } from 'react';
4
4
 
5
5
  import { isQuotaExceededError } from './storage-quota';
6
+ import { decodeStored, type StorageValidator } from './storage-decode';
6
7
  import { evictableKeys, useResolvedStorageKey } from './storage-namespace';
7
8
 
8
9
  /**
@@ -34,6 +35,13 @@ export interface UseLocalStorageOptions {
34
35
  * A key that already follows `<owner>.<area>.<name>` is used as is.
35
36
  */
36
37
  namespace?: string;
38
+ /**
39
+ * Accept a stored value only if this returns true. Replaces the default shape
40
+ * check (same `typeof` as the initial value, same keys for an object). A value
41
+ * that fails is dropped, the key is removed and the initial value is used: a
42
+ * stale or hand-edited entry can never reach the component.
43
+ */
44
+ validate?: StorageValidator<unknown>;
37
45
  }
38
46
 
39
47
  /**
@@ -50,29 +58,6 @@ export type UseLocalStorageReturn<T> = readonly [
50
58
  patch: (partial: Partial<T>) => void,
51
59
  ];
52
60
 
53
- /**
54
- * Check if data is in new wrapped format with _meta
55
- */
56
- function isWrappedFormat<T>(data: unknown): data is StorageWrapper<T> {
57
- return (
58
- data !== null &&
59
- typeof data === 'object' &&
60
- '_meta' in data &&
61
- '_value' in data &&
62
- typeof (data as StorageWrapper<T>)._meta === 'object' &&
63
- typeof (data as StorageWrapper<T>)._meta.createdAt === 'number'
64
- );
65
- }
66
-
67
- /**
68
- * Check if wrapped data is expired
69
- */
70
- function isExpired<T>(wrapped: StorageWrapper<T>): boolean {
71
- if (!wrapped._meta.ttl) return false;
72
- const age = Date.now() - wrapped._meta.createdAt;
73
- return age > wrapped._meta.ttl;
74
- }
75
-
76
61
  /** True for a plain object (eligible for shallow-merge `patch`). */
77
62
  function isPlainObject(v: unknown): v is Record<string, unknown> {
78
63
  return v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -185,27 +170,24 @@ export function useLocalStorage<T>(
185
170
  * Parse a raw localStorage string into a value of T, honoring TTL.
186
171
  * Returns `{ value }` or `null` when the entry is absent / expired.
187
172
  */
173
+ const validate = options?.validate as StorageValidator<T> | undefined;
174
+ const validateRef = useRef(validate);
175
+ validateRef.current = validate;
176
+ const initialForParse = useRef<T>(initialValue);
177
+ initialForParse.current = initialValue;
178
+
188
179
  const parseRaw = useCallback(
189
180
  (raw: string | null): { value: T } | null => {
190
181
  if (raw === null) return null;
182
+ const decoded = decodeStored<T>(raw, initialForParse.current, validateRef.current);
183
+ if (decoded.ok) return { value: decoded.value };
184
+ // Expired or not what we expect: heal the key so the next read is clean.
191
185
  try {
192
- const parsed = JSON.parse(raw);
193
- if (isWrappedFormat<T>(parsed)) {
194
- if (isExpired(parsed)) {
195
- try {
196
- window.localStorage.removeItem(key);
197
- } catch {
198
- // ignore
199
- }
200
- return null;
201
- }
202
- return { value: parsed._value };
203
- }
204
- return { value: parsed as T };
186
+ window.localStorage.removeItem(key);
205
187
  } catch {
206
- // Not JSON — treat as a raw string value.
207
- return { value: raw as T };
188
+ // ignore
208
189
  }
190
+ return null;
209
191
  },
210
192
  [key],
211
193
  );
@@ -3,6 +3,7 @@
3
3
  import { useState } from 'react';
4
4
 
5
5
  import { isQuotaExceededError } from './storage-quota';
6
+ import { decodeStored, type StorageValidator } from './storage-decode';
6
7
  import { evictableKeys, useResolvedStorageKey } from './storage-namespace';
7
8
 
8
9
  /**
@@ -34,6 +35,11 @@ export interface UseSessionStorageOptions {
34
35
  * A key that already follows `<owner>.<area>.<name>` is used as is.
35
36
  */
36
37
  namespace?: string;
38
+ /**
39
+ * Accept a stored value only if this returns true; otherwise the key is
40
+ * removed and the initial value is used. Replaces the default shape check.
41
+ */
42
+ validate?: StorageValidator<unknown>;
37
43
  }
38
44
 
39
45
  /**
@@ -54,29 +60,6 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {
54
60
  return v !== null && typeof v === 'object' && !Array.isArray(v);
55
61
  }
56
62
 
57
- /**
58
- * Check if data is in new wrapped format with _meta
59
- */
60
- function isWrappedFormat<T>(data: unknown): data is StorageWrapper<T> {
61
- return (
62
- data !== null &&
63
- typeof data === 'object' &&
64
- '_meta' in data &&
65
- '_value' in data &&
66
- typeof (data as StorageWrapper<T>)._meta === 'object' &&
67
- typeof (data as StorageWrapper<T>)._meta.createdAt === 'number'
68
- );
69
- }
70
-
71
- /**
72
- * Check if wrapped data is expired
73
- */
74
- function isExpired<T>(wrapped: StorageWrapper<T>): boolean {
75
- if (!wrapped._meta.ttl) return false;
76
- const age = Date.now() - wrapped._meta.createdAt;
77
- return age > wrapped._meta.ttl;
78
- }
79
-
80
63
  /**
81
64
  * Simple sessionStorage hook with better error handling and optional TTL support
82
65
  *
@@ -113,27 +96,11 @@ export function useSessionStorage<T>(
113
96
  const item = window.sessionStorage.getItem(key);
114
97
  if (item === null) return initialValue;
115
98
 
116
- try {
117
- const parsed = JSON.parse(item);
118
-
119
- // Check if new format with _meta
120
- if (isWrappedFormat<T>(parsed)) {
121
- // Check TTL expiration
122
- if (isExpired(parsed)) {
123
- // Expired! Clean up and use initial value
124
- window.sessionStorage.removeItem(key);
125
- return initialValue;
126
- }
127
- // Not expired, extract value
128
- return parsed._value;
129
- }
130
-
131
- // Old format (backwards compatible)
132
- return parsed as T;
133
- } catch {
134
- // If JSON.parse fails, return as string
135
- return item as T;
136
- }
99
+ const decoded = decodeStored<T>(item, initialValue, options?.validate as StorageValidator<T> | undefined);
100
+ if (decoded.ok) return decoded.value;
101
+ // Expired or not what we expect: heal the key and start from the initial value.
102
+ window.sessionStorage.removeItem(key);
103
+ return initialValue;
137
104
  } catch (error) {
138
105
  console.error(`Error reading sessionStorage key "${key}":`, error);
139
106
  return initialValue;
@@ -3,6 +3,7 @@
3
3
  import { useCallback } from 'react';
4
4
 
5
5
  import { useLocalStorage } from './useLocalStorage';
6
+ import type { StorageValidator } from './storage-decode';
6
7
  import { useSessionStorage } from './useSessionStorage';
7
8
 
8
9
  export type StorageType = 'local' | 'session';
@@ -24,6 +25,8 @@ export interface UseStoredValueOptions {
24
25
  * @see resolveStorageKey
25
26
  */
26
27
  namespace?: string;
28
+ /** Accept a stored value only if this returns true; otherwise it is dropped and the initial value used. */
29
+ validate?: StorageValidator<unknown>;
27
30
  }
28
31
 
29
32
  /**
@@ -63,7 +66,7 @@ export function useStoredValue<T>(
63
66
  options?: UseStoredValueOptions,
64
67
  ): UseStoredValueReturn<T> {
65
68
  const storageType = options?.storage ?? 'local';
66
- const ttlOption = { ttl: options?.ttl, namespace: options?.namespace };
69
+ const ttlOption = { ttl: options?.ttl, namespace: options?.namespace, validate: options?.validate };
67
70
 
68
71
  // Both hooks are always called (rules of hooks — no conditional calls).
69
72
  // Only one of them is actually used depending on storageType.
@@ -0,0 +1,13 @@
1
+ export {
2
+ WEB_SPEECH_LANGUAGES,
3
+ WEB_SPEECH_TAGS,
4
+ findSpeechLanguage,
5
+ countryFromTag,
6
+ buildLanguageRows,
7
+ } from "./languages";
8
+ export type { SpeechLanguage, SpeechLanguageDialect, SpeechLanguageRow } from "./languages";
9
+ export { expandQueryLayouts, matchesLanguageQuery } from "./search";
10
+ export { resolveLanguage, toSpeechTag, browserSpeechTags } from "./resolve";
11
+ export type { LanguageSignals } from "./resolve";
12
+ export { useSpeechLanguage } from "./useSpeechLanguage";
13
+ export type { UseSpeechLanguageResult, SpeechLanguageOptions } from "./useSpeechLanguage";
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Canonical list of BCP-47 language tags that the browser Web Speech
3
+ * API is known to accept. Sourced from the official Google Chrome
4
+ * Speech API demo (`google.com/intl/en/chrome/demos/speech.html`),
5
+ * which is the de-facto reference — the spec itself doesn't expose a
6
+ * way to enumerate supported languages, so this list is the
7
+ * best-effort guarantee for what works in Chromium-based browsers.
8
+ *
9
+ * Each entry groups one human-readable language with its dialect
10
+ * variants. The default tag (first in `dialects`) is what `lang` is
11
+ * set to when the user picks the language without a regional dialect.
12
+ *
13
+ * A host whose engine is not the browser can narrow this list — a server
14
+ * transcriber may accept more or fewer tags than Web Speech does.
15
+ */
16
+
17
+ export interface SpeechLanguageDialect {
18
+ /** BCP-47 tag (e.g. `en-US`). */
19
+ code: string;
20
+ /** Region label in the language's native script (e.g. "United States"). */
21
+ region: string;
22
+ }
23
+
24
+ export interface SpeechLanguage {
25
+ /** Native-script name (e.g. "Русский", "中文"). */
26
+ name: string;
27
+ /**
28
+ * English name used as a secondary search key so users typing
29
+ * "russian" / "chinese" / "korean" land on the right row regardless
30
+ * of the native script. Always lowercase.
31
+ */
32
+ englishName: string;
33
+ /**
34
+ * Primary-subtag ISO-639 code (e.g. `en`, `ru`, `cmn`). The key a UI locale
35
+ * is matched against when resolving a default.
36
+ */
37
+ iso: string;
38
+ /** One or more region dialects. Length >= 1. */
39
+ dialects: SpeechLanguageDialect[];
40
+ }
41
+
42
+ export const WEB_SPEECH_LANGUAGES: SpeechLanguage[] = [
43
+ { name: 'Afrikaans', iso: 'af', englishName: 'afrikaans', dialects: [{ code: 'af-ZA', region: 'South Africa' }] },
44
+ { name: 'አማርኛ', iso: 'am', englishName: 'amharic', dialects: [{ code: 'am-ET', region: 'Ethiopia' }] },
45
+ { name: 'Azərbaycanca', iso: 'az', englishName: 'azerbaijani', dialects: [{ code: 'az-AZ', region: 'Azerbaijan' }] },
46
+ {
47
+ name: 'বাংলা', iso: 'bn', englishName: 'bengali',
48
+ dialects: [
49
+ { code: 'bn-BD', region: 'Bangladesh' },
50
+ { code: 'bn-IN', region: 'India' },
51
+ ],
52
+ },
53
+ { name: 'Bahasa Indonesia', iso: 'id', englishName: 'indonesian', dialects: [{ code: 'id-ID', region: 'Indonesia' }] },
54
+ { name: 'Bahasa Melayu', iso: 'ms', englishName: 'malay', dialects: [{ code: 'ms-MY', region: 'Malaysia' }] },
55
+ { name: 'Català', iso: 'ca', englishName: 'catalan', dialects: [{ code: 'ca-ES', region: 'Spain' }] },
56
+ { name: 'Čeština', iso: 'cs', englishName: 'czech', dialects: [{ code: 'cs-CZ', region: 'Czechia' }] },
57
+ { name: 'Dansk', iso: 'da', englishName: 'danish', dialects: [{ code: 'da-DK', region: 'Denmark' }] },
58
+ { name: 'Deutsch', iso: 'de', englishName: 'german', dialects: [{ code: 'de-DE', region: 'Germany' }] },
59
+ {
60
+ name: 'English', iso: 'en', englishName: 'english',
61
+ dialects: [
62
+ { code: 'en-US', region: 'United States' },
63
+ { code: 'en-GB', region: 'United Kingdom' },
64
+ { code: 'en-AU', region: 'Australia' },
65
+ { code: 'en-CA', region: 'Canada' },
66
+ { code: 'en-IN', region: 'India' },
67
+ { code: 'en-NZ', region: 'New Zealand' },
68
+ { code: 'en-PH', region: 'Philippines' },
69
+ { code: 'en-ZA', region: 'South Africa' },
70
+ { code: 'en-NG', region: 'Nigeria' },
71
+ { code: 'en-GH', region: 'Ghana' },
72
+ { code: 'en-KE', region: 'Kenya' },
73
+ { code: 'en-TZ', region: 'Tanzania' },
74
+ ],
75
+ },
76
+ {
77
+ name: 'Español', iso: 'es', englishName: 'spanish',
78
+ dialects: [
79
+ { code: 'es-ES', region: 'España' },
80
+ { code: 'es-MX', region: 'México' },
81
+ { code: 'es-US', region: 'Estados Unidos' },
82
+ { code: 'es-AR', region: 'Argentina' },
83
+ { code: 'es-CL', region: 'Chile' },
84
+ { code: 'es-CO', region: 'Colombia' },
85
+ { code: 'es-PE', region: 'Perú' },
86
+ { code: 'es-VE', region: 'Venezuela' },
87
+ { code: 'es-EC', region: 'Ecuador' },
88
+ { code: 'es-GT', region: 'Guatemala' },
89
+ { code: 'es-CR', region: 'Costa Rica' },
90
+ { code: 'es-PA', region: 'Panamá' },
91
+ { code: 'es-DO', region: 'Rep. Dominicana' },
92
+ { code: 'es-UY', region: 'Uruguay' },
93
+ { code: 'es-PY', region: 'Paraguay' },
94
+ { code: 'es-BO', region: 'Bolivia' },
95
+ { code: 'es-SV', region: 'El Salvador' },
96
+ { code: 'es-HN', region: 'Honduras' },
97
+ { code: 'es-NI', region: 'Nicaragua' },
98
+ { code: 'es-PR', region: 'Puerto Rico' },
99
+ ],
100
+ },
101
+ { name: 'Euskara', iso: 'eu', englishName: 'basque', dialects: [{ code: 'eu-ES', region: 'Spain' }] },
102
+ { name: 'Filipino', iso: 'fil', englishName: 'filipino tagalog', dialects: [{ code: 'fil-PH', region: 'Philippines' }] },
103
+ { name: 'Français', iso: 'fr', englishName: 'french', dialects: [{ code: 'fr-FR', region: 'France' }] },
104
+ { name: 'Basa Jawa', iso: 'jv', englishName: 'javanese', dialects: [{ code: 'jv-ID', region: 'Indonesia' }] },
105
+ { name: 'Galego', iso: 'gl', englishName: 'galician', dialects: [{ code: 'gl-ES', region: 'Spain' }] },
106
+ { name: 'ગુજરાતી', iso: 'gu', englishName: 'gujarati', dialects: [{ code: 'gu-IN', region: 'India' }] },
107
+ { name: 'Hrvatski', iso: 'hr', englishName: 'croatian', dialects: [{ code: 'hr-HR', region: 'Croatia' }] },
108
+ { name: 'IsiZulu', iso: 'zu', englishName: 'zulu', dialects: [{ code: 'zu-ZA', region: 'South Africa' }] },
109
+ { name: 'Íslenska', iso: 'is', englishName: 'icelandic', dialects: [{ code: 'is-IS', region: 'Iceland' }] },
110
+ {
111
+ name: 'Italiano', iso: 'it', englishName: 'italian',
112
+ dialects: [
113
+ { code: 'it-IT', region: 'Italia' },
114
+ { code: 'it-CH', region: 'Svizzera' },
115
+ ],
116
+ },
117
+ { name: 'ಕನ್ನಡ', iso: 'kn', englishName: 'kannada', dialects: [{ code: 'kn-IN', region: 'India' }] },
118
+ { name: 'ភាសាខ្មែរ', iso: 'km', englishName: 'khmer cambodian', dialects: [{ code: 'km-KH', region: 'Cambodia' }] },
119
+ { name: 'Latviešu', iso: 'lv', englishName: 'latvian', dialects: [{ code: 'lv-LV', region: 'Latvia' }] },
120
+ { name: 'Lietuvių', iso: 'lt', englishName: 'lithuanian', dialects: [{ code: 'lt-LT', region: 'Lithuania' }] },
121
+ { name: 'മലയാളം', iso: 'ml', englishName: 'malayalam', dialects: [{ code: 'ml-IN', region: 'India' }] },
122
+ { name: 'मराठी', iso: 'mr', englishName: 'marathi', dialects: [{ code: 'mr-IN', region: 'India' }] },
123
+ { name: 'Magyar', iso: 'hu', englishName: 'hungarian', dialects: [{ code: 'hu-HU', region: 'Hungary' }] },
124
+ { name: 'ລາວ', iso: 'lo', englishName: 'lao laotian', dialects: [{ code: 'lo-LA', region: 'Laos' }] },
125
+ { name: 'Nederlands', iso: 'nl', englishName: 'dutch', dialects: [{ code: 'nl-NL', region: 'Netherlands' }] },
126
+ { name: 'नेपाली भाषा', iso: 'ne', englishName: 'nepali', dialects: [{ code: 'ne-NP', region: 'Nepal' }] },
127
+ { name: 'Norsk bokmål', iso: 'nb', englishName: 'norwegian bokmal', dialects: [{ code: 'nb-NO', region: 'Norway' }] },
128
+ { name: 'Polski', iso: 'pl', englishName: 'polish', dialects: [{ code: 'pl-PL', region: 'Poland' }] },
129
+ {
130
+ name: 'Português', iso: 'pt', englishName: 'portuguese',
131
+ dialects: [
132
+ { code: 'pt-BR', region: 'Brasil' },
133
+ { code: 'pt-PT', region: 'Portugal' },
134
+ ],
135
+ },
136
+ { name: 'Română', iso: 'ro', englishName: 'romanian', dialects: [{ code: 'ro-RO', region: 'Romania' }] },
137
+ { name: 'සිංහල', iso: 'si', englishName: 'sinhala sinhalese', dialects: [{ code: 'si-LK', region: 'Sri Lanka' }] },
138
+ { name: 'Slovenščina', iso: 'sl', englishName: 'slovenian', dialects: [{ code: 'sl-SI', region: 'Slovenia' }] },
139
+ { name: 'Basa Sunda', iso: 'su', englishName: 'sundanese', dialects: [{ code: 'su-ID', region: 'Indonesia' }] },
140
+ { name: 'Slovenčina', iso: 'sk', englishName: 'slovak', dialects: [{ code: 'sk-SK', region: 'Slovakia' }] },
141
+ { name: 'Suomi', iso: 'fi', englishName: 'finnish', dialects: [{ code: 'fi-FI', region: 'Finland' }] },
142
+ { name: 'Svenska', iso: 'sv', englishName: 'swedish', dialects: [{ code: 'sv-SE', region: 'Sweden' }] },
143
+ {
144
+ name: 'Kiswahili', iso: 'sw', englishName: 'swahili',
145
+ dialects: [
146
+ { code: 'sw-TZ', region: 'Tanzania' },
147
+ { code: 'sw-KE', region: 'Kenya' },
148
+ ],
149
+ },
150
+ { name: 'ქართული', iso: 'ka', englishName: 'georgian', dialects: [{ code: 'ka-GE', region: 'Georgia' }] },
151
+ { name: 'Հայերեն', iso: 'hy', englishName: 'armenian', dialects: [{ code: 'hy-AM', region: 'Armenia' }] },
152
+ {
153
+ name: 'தமிழ்', iso: 'ta', englishName: 'tamil',
154
+ dialects: [
155
+ { code: 'ta-IN', region: 'இந்தியா' },
156
+ { code: 'ta-SG', region: 'சிங்கப்பூர்' },
157
+ { code: 'ta-LK', region: 'இலங்கை' },
158
+ { code: 'ta-MY', region: 'மலேசியா' },
159
+ ],
160
+ },
161
+ { name: 'తెలుగు', iso: 'te', englishName: 'telugu', dialects: [{ code: 'te-IN', region: 'India' }] },
162
+ { name: 'Tiếng Việt', iso: 'vi', englishName: 'vietnamese', dialects: [{ code: 'vi-VN', region: 'Vietnam' }] },
163
+ { name: 'Türkçe', iso: 'tr', englishName: 'turkish', dialects: [{ code: 'tr-TR', region: 'Türkiye' }] },
164
+ {
165
+ name: 'اُردُو', iso: 'ur', englishName: 'urdu',
166
+ dialects: [
167
+ { code: 'ur-PK', region: 'پاکستان' },
168
+ { code: 'ur-IN', region: 'بھارت' },
169
+ ],
170
+ },
171
+ { name: 'Ελληνικά', iso: 'el', englishName: 'greek', dialects: [{ code: 'el-GR', region: 'Greece' }] },
172
+ { name: 'български', iso: 'bg', englishName: 'bulgarian', dialects: [{ code: 'bg-BG', region: 'Bulgaria' }] },
173
+ { name: 'Русский', iso: 'ru', englishName: 'russian', dialects: [{ code: 'ru-RU', region: 'Russia' }] },
174
+ { name: 'Српски', iso: 'sr', englishName: 'serbian', dialects: [{ code: 'sr-RS', region: 'Serbia' }] },
175
+ { name: 'Українська', iso: 'uk', englishName: 'ukrainian', dialects: [{ code: 'uk-UA', region: 'Ukraine' }] },
176
+ { name: '한국어', iso: 'ko', englishName: 'korean', dialects: [{ code: 'ko-KR', region: 'Korea' }] },
177
+ {
178
+ name: '中文', iso: 'cmn', englishName: 'chinese mandarin cantonese',
179
+ dialects: [
180
+ { code: 'cmn-Hans-CN', region: '普通话 (中国大陆)' },
181
+ { code: 'cmn-Hans-HK', region: '普通话 (香港)' },
182
+ { code: 'cmn-Hant-TW', region: '中文 (台灣)' },
183
+ { code: 'yue-Hant-HK', region: '粵語 (香港)' },
184
+ ],
185
+ },
186
+ { name: '日本語', iso: 'ja', englishName: 'japanese', dialects: [{ code: 'ja-JP', region: 'Japan' }] },
187
+ { name: 'हिन्दी', iso: 'hi', englishName: 'hindi', dialects: [{ code: 'hi-IN', region: 'India' }] },
188
+ { name: 'ภาษาไทย', iso: 'th', englishName: 'thai', dialects: [{ code: 'th-TH', region: 'Thailand' }] },
189
+ {
190
+ name: 'العربية', iso: 'ar', englishName: 'arabic',
191
+ dialects: [
192
+ { code: 'ar-SA', region: 'المملكة العربية السعودية' },
193
+ { code: 'ar-EG', region: 'مصر' },
194
+ { code: 'ar-AE', region: 'الإمارات' },
195
+ { code: 'ar-MA', region: 'المغرب' },
196
+ { code: 'ar-DZ', region: 'الجزائر' },
197
+ { code: 'ar-JO', region: 'الأردن' },
198
+ { code: 'ar-IQ', region: 'العراق' },
199
+ { code: 'ar-KW', region: 'الكويت' },
200
+ { code: 'ar-LB', region: 'لبنان' },
201
+ { code: 'ar-QA', region: 'قطر' },
202
+ { code: 'ar-TN', region: 'تونس' },
203
+ ],
204
+ },
205
+ ];
206
+
207
+ /** Flat list of every supported BCP-47 tag, useful for validation. */
208
+ export const WEB_SPEECH_TAGS: string[] = WEB_SPEECH_LANGUAGES.flatMap((l) =>
209
+ l.dialects.map((d) => d.code),
210
+ );
211
+
212
+ /**
213
+ * Find the human-readable language entry that owns a given BCP-47 tag.
214
+ * Returns `null` for unknown / custom tags (custom engines may use
215
+ * codes outside this catalogue).
216
+ */
217
+ export function findSpeechLanguage(tag: string | null | undefined): {
218
+ language: SpeechLanguage;
219
+ dialect: SpeechLanguageDialect;
220
+ } | null {
221
+ if (!tag) return null;
222
+ const lower = tag.toLowerCase();
223
+ for (const language of WEB_SPEECH_LANGUAGES) {
224
+ for (const dialect of language.dialects) {
225
+ if (dialect.code.toLowerCase() === lower) return { language, dialect };
226
+ }
227
+ }
228
+ return null;
229
+ }
230
+
231
+ /**
232
+ * Extract the ISO-3166 country code (2 uppercase letters) from a
233
+ * BCP-47 tag, or `null` if the tag has no region subtag. Used by the
234
+ * language flag button to find the right country flag asset.
235
+ */
236
+ export function countryFromTag(tag: string | null | undefined): string | null {
237
+ if (!tag) return null;
238
+ const parts = tag.split('-');
239
+ for (let i = parts.length - 1; i >= 0; i -= 1) {
240
+ const p = parts[i];
241
+ if (p && p.length === 2 && /^[A-Za-z]{2}$/.test(p)) return p.toUpperCase();
242
+ }
243
+ return null;
244
+ }
245
+
246
+ export interface SpeechLanguageRow {
247
+ /** BCP-47 tag (e.g. `ru-RU`). */
248
+ tag: string;
249
+ /** Display label: native name, plus region when the language has >1 dialect. */
250
+ label: string;
251
+ /** ISO-3166 country for the flag asset, or null for region-less tags. */
252
+ country: string | null;
253
+ /**
254
+ * Lowercased search haystack: native name + English name + ISO + tag
255
+ * + region. Match with `matchesLanguageQuery` (layout-independent).
256
+ */
257
+ search: string;
258
+ }
259
+
260
+ /**
261
+ * Flatten the catalogue into ready-to-render menu rows — the single
262
+ * builder behind every language list surface (`VoiceControlMenu`
263
+ * submenu, the in-recording `LanguageChip` dropdown). `allowedTags`
264
+ * narrows the list for backend engines that support a subset.
265
+ */
266
+ export function buildLanguageRows(allowedTags?: string[]): SpeechLanguageRow[] {
267
+ const allow = allowedTags ? new Set(allowedTags) : null;
268
+ const rows: SpeechLanguageRow[] = [];
269
+ for (const lang of WEB_SPEECH_LANGUAGES) {
270
+ for (const d of lang.dialects) {
271
+ if (allow && !allow.has(d.code)) continue;
272
+ rows.push({
273
+ tag: d.code,
274
+ label:
275
+ lang.dialects.length === 1 ? lang.name : `${lang.name} — ${d.region}`,
276
+ country: countryFromTag(d.code),
277
+ search:
278
+ `${lang.name} ${lang.englishName} ${lang.iso} ${d.code} ${d.region}`.toLowerCase(),
279
+ });
280
+ }
281
+ }
282
+ return rows;
283
+ }
@@ -0,0 +1,140 @@
1
+ import { WEB_SPEECH_LANGUAGES } from "./languages";
2
+
3
+ /**
4
+ * The signals a default language is resolved from.
5
+ *
6
+ * Passed in rather than read from `navigator`/`localStorage` here: this is the
7
+ * one rule in dictation worth testing exhaustively, and a function that reaches
8
+ * for globals can only be tested by faking them.
9
+ */
10
+ export interface LanguageSignals {
11
+ /** What the user picked, if they ever did. Wins outright. */
12
+ readonly picked?: string | undefined;
13
+ /** The host UI's locale — an ISO subtag such as `ru`. A TIE-BREAKER only. */
14
+ readonly uiLocale?: string | undefined;
15
+ /** `navigator.languages`, in the browser's own order. */
16
+ readonly browserLanguages?: readonly string[] | undefined;
17
+ /** `navigator.language`. */
18
+ readonly browserLanguage?: string | undefined;
19
+ /** The runtime's `Intl` locale: the OS language/region, used only when no browser language is usable. */
20
+ readonly intlLocale?: string | undefined;
21
+ }
22
+
23
+ const FALLBACK = "en-US";
24
+
25
+ /** ISO primary subtag → the catalogue's default dialect (`uk` → `uk-UA`). */
26
+ const ISO_TO_TAG: ReadonlyMap<string, string> = new Map(
27
+ WEB_SPEECH_LANGUAGES.flatMap((language) => {
28
+ const first = language.dialects[0];
29
+ return first === undefined ? [] : [[language.iso.toLowerCase(), first.code] as const];
30
+ }),
31
+ );
32
+
33
+ /** Every tag the catalogue knows, lowercased, for validating a candidate. */
34
+ const KNOWN_TAGS: ReadonlySet<string> = new Set(
35
+ WEB_SPEECH_LANGUAGES.flatMap((language) =>
36
+ language.dialects.map((dialect) => dialect.code.toLowerCase()),
37
+ ),
38
+ );
39
+
40
+ /**
41
+ * Primary subtags a browser or a UI locale spells differently from the catalogue:
42
+ * `zh` is Chinese (the catalogue keys it `cmn`), `no`/`nn` are Norwegian (keyed `nb`).
43
+ * Without this the 17 bundled UI locales left `zh` and `no` unresolved and dictation fell back to English.
44
+ */
45
+ const ISO_ALIASES: Readonly<Record<string, string>> = { zh: "cmn", no: "nb", nn: "nb" };
46
+
47
+ /** Whole tags that name a catalogue dialect under another spelling (`zh-TW` is Mandarin in Traditional script). */
48
+ const TAG_ALIASES: Readonly<Record<string, string>> = {
49
+ "zh-tw": "cmn-Hant-TW",
50
+ "zh-hant": "cmn-Hant-TW",
51
+ "zh-hant-tw": "cmn-Hant-TW",
52
+ "zh-hk": "cmn-Hans-HK",
53
+ "zh-cn": "cmn-Hans-CN",
54
+ "zh-hans": "cmn-Hans-CN",
55
+ "zh-hans-cn": "cmn-Hans-CN",
56
+ };
57
+
58
+ function isoOf(tag: string): string {
59
+ const iso = tag.toLowerCase().split("-")[0] ?? "";
60
+ return ISO_ALIASES[iso] ?? iso;
61
+ }
62
+
63
+ /**
64
+ * Normalise anything language-shaped to a tag the Web Speech API accepts.
65
+ *
66
+ * A bare ISO subtag becomes the catalogue's default dialect for it; a full tag
67
+ * is kept when the catalogue knows it, and otherwise falls back to that
68
+ * language's default dialect. The last step is what rescues the measured case:
69
+ * `en-ID` is a real browser value and not a speech tag, so it resolves to
70
+ * `en-US` rather than being handed to an engine that will reject it.
71
+ */
72
+ export function toSpeechTag(code: string | null | undefined): string | undefined {
73
+ if (code === null || code === undefined) return undefined;
74
+ const trimmed = code.trim();
75
+ if (trimmed === "") return undefined;
76
+ if (KNOWN_TAGS.has(trimmed.toLowerCase())) return trimmed;
77
+ const aliased = TAG_ALIASES[trimmed.toLowerCase()];
78
+ if (aliased !== undefined) return aliased;
79
+ return ISO_TO_TAG.get(isoOf(trimmed));
80
+ }
81
+
82
+ /**
83
+ * Which language dictation should listen for.
84
+ *
85
+ * Guessing for the user, in this order:
86
+ *
87
+ * 1. the user's explicit pick
88
+ * 2. the UI locale, IF the browser also lists it as spoken
89
+ * 3. the first language in `navigator.languages` that dictation supports
90
+ * 4. `navigator.language`, then the `Intl` locale
91
+ * 5. `en-US`
92
+ *
93
+ * The BROWSER decides, the app only breaks ties. A host that passes `ru` on a
94
+ * browser that lists only English still gets English; a host that passes
95
+ * nothing still gets the browser's language. Pinning speech to the app locale
96
+ * is a known regression — an English UI then cannot dictate Russian.
97
+ *
98
+ * Rung 2 exists because of a measured failure: `navigator.language` was `en-ID`
99
+ * while `navigator.languages` contained `ru` and the app was set to Russian.
100
+ * Rung 3 walks the whole list rather than trusting position one: the first
101
+ * entry may be a language dictation has no engine for (`xx`), and the second is
102
+ * then the real answer.
103
+ */
104
+ export function resolveLanguage(signals: LanguageSignals): string {
105
+ const picked = toSpeechTag(signals.picked);
106
+ if (picked !== undefined) return picked;
107
+
108
+ const list = signals.browserLanguages ?? [];
109
+ const uiIso = isoOf(signals.uiLocale ?? "");
110
+ if (uiIso !== "" && list.map(isoOf).includes(uiIso)) {
111
+ const tag = ISO_TO_TAG.get(uiIso);
112
+ if (tag !== undefined) return tag;
113
+ }
114
+
115
+ for (const candidate of list) {
116
+ const tag = toSpeechTag(candidate);
117
+ if (tag !== undefined) return tag;
118
+ }
119
+
120
+ return toSpeechTag(signals.browserLanguage) ?? toSpeechTag(signals.intlLocale) ?? FALLBACK;
121
+ }
122
+
123
+ /**
124
+ * The browser's languages as speech tags, best first, one per language: the
125
+ * candidate set a picker shows ahead of the full catalogue (a user whose browser
126
+ * UI is Indonesian usually still lists Russian or English right after it).
127
+ */
128
+ export function browserSpeechTags(languages: readonly string[]): string[] {
129
+ const seen = new Set<string>();
130
+ const out: string[] = [];
131
+ for (const code of languages) {
132
+ const tag = toSpeechTag(code);
133
+ if (tag === undefined) continue;
134
+ const iso = isoOf(tag);
135
+ if (seen.has(iso)) continue;
136
+ seen.add(iso);
137
+ out.push(tag);
138
+ }
139
+ return out;
140
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Layout-independent language search.
3
+ *
4
+ * Typing "he,bq" on an EN layout while thinking «русый», or "hecc" for
5
+ * «русс», is the single most common way a bilingual user searches a
6
+ * language list — the physical keys are right, the layout is wrong.
7
+ * Every query is therefore expanded through the QWERTY↔ЙЦУКЕН key maps
8
+ * and EVERY variant is matched, so «рус», "rus", "russian" and "hec"
9
+ * (=рус on EN keys) all find Русский.
10
+ *
11
+ * The maps cover the RU↔EN pair only — the pair our users actually mix.
12
+ * The mechanism is additive: more layout pairs can be appended to
13
+ * `LAYOUT_PAIRS` without touching the matcher.
14
+ */
15
+
16
+ /** QWERTY key → ЙЦУКЕН character on the same physical key. */
17
+ const EN_TO_RU: Record<string, string> = {
18
+ q: 'й', w: 'ц', e: 'у', r: 'к', t: 'е', y: 'н', u: 'г', i: 'ш', o: 'щ',
19
+ p: 'з', '[': 'х', ']': 'ъ', a: 'ф', s: 'ы', d: 'в', f: 'а', g: 'п',
20
+ h: 'р', j: 'о', k: 'л', l: 'д', ';': 'ж', "'": 'э', z: 'я', x: 'ч',
21
+ c: 'с', v: 'м', b: 'и', n: 'т', m: 'ь', ',': 'б', '.': 'ю',
22
+ };
23
+
24
+ /** ЙЦУКЕН character → QWERTY key on the same physical key. */
25
+ const RU_TO_EN: Record<string, string> = Object.fromEntries(
26
+ Object.entries(EN_TO_RU).map(([en, ru]) => [ru, en]),
27
+ );
28
+
29
+ const LAYOUT_PAIRS: Record<string, string>[] = [EN_TO_RU, RU_TO_EN];
30
+
31
+ function remap(query: string, table: Record<string, string>): string {
32
+ let out = '';
33
+ for (const ch of query) out += table[ch] ?? ch;
34
+ return out;
35
+ }
36
+
37
+ /**
38
+ * All layout interpretations of a raw query, lowercased and de-duplicated.
39
+ * Always includes the query itself.
40
+ */
41
+ export function expandQueryLayouts(query: string): string[] {
42
+ const q = query.trim().toLowerCase();
43
+ if (!q) return [];
44
+ const variants = new Set<string>([q]);
45
+ for (const table of LAYOUT_PAIRS) {
46
+ const mapped = remap(q, table);
47
+ if (mapped !== q) variants.add(mapped);
48
+ }
49
+ return [...variants];
50
+ }
51
+
52
+ /**
53
+ * True when ANY layout variant of `query` is a substring of `haystack`.
54
+ * `haystack` must already be lowercase (build it once per row —
55
+ * `SpeechLanguageRow.search` packs native name, English name, ISO, tag
56
+ * and region).
57
+ */
58
+ export function matchesLanguageQuery(haystack: string, query: string): boolean {
59
+ const variants = expandQueryLayouts(query);
60
+ if (variants.length === 0) return true;
61
+ return variants.some((v) => haystack.includes(v));
62
+ }
@@ -0,0 +1,68 @@
1
+ "use client";
2
+
3
+ import { useCallback, useMemo } from "react";
4
+
5
+ import { CFG_KEYS } from "@djangocfg/api/storage";
6
+
7
+ import { useBrowserLanguages } from "../../hooks/device/useBrowserLanguages";
8
+ import { useLocalStorage } from "../../hooks/storage/useLocalStorage";
9
+ import { resolveLanguage } from "./resolve";
10
+
11
+ /**
12
+ * Which language dictation listens for, and how it is remembered. ONE answer for
13
+ * every dictation surface (chats, a composer, a form field), wherever it is
14
+ * embedded.
15
+ *
16
+ * A language is a property of the SPEAKER, not of the surface they are in, so the
17
+ * pick is global. It lives in `localStorage` under one key and is read through
18
+ * `useLocalStorage`, whose same-tab registry and `storage` event make a change
19
+ * in one place visible in all the others at once, without a reload. An empty
20
+ * value means "not picked": the language is then guessed from the browser
21
+ * (`resolveLanguage`).
22
+ */
23
+ const STORAGE_KEY = CFG_KEYS.chatSpeechLanguage.key;
24
+
25
+ export interface UseSpeechLanguageResult {
26
+ /** The BCP-47 speech tag in force. Never empty. */
27
+ readonly language: string;
28
+ /** Whether the user chose it, as opposed to it being guessed for them. */
29
+ readonly explicit: boolean;
30
+ readonly setLanguage: (tag: string) => void;
31
+ /** Forget the pick and go back to guessing. */
32
+ readonly clear: () => void;
33
+ }
34
+
35
+ export interface SpeechLanguageOptions {
36
+ /**
37
+ * The host UI's locale (`ru`). A TIE-BREAKER, never the source: it counts only
38
+ * when the browser also lists that language as spoken, so an English app on a
39
+ * browser that lists Russian can dictate Russian and the reverse holds too.
40
+ */
41
+ readonly uiLocale?: string | undefined;
42
+ }
43
+
44
+ export function useSpeechLanguage(options: SpeechLanguageOptions = {}): UseSpeechLanguageResult {
45
+ const [stored, setStored, removeStored] = useLocalStorage<string>(STORAGE_KEY, "");
46
+ const browser = useBrowserLanguages();
47
+ const picked = stored === "" ? undefined : stored;
48
+
49
+ const language = useMemo(
50
+ () =>
51
+ resolveLanguage({
52
+ picked,
53
+ uiLocale: options.uiLocale,
54
+ browserLanguages: browser.languages,
55
+ browserLanguage: browser.primary,
56
+ intlLocale: browser.intl,
57
+ }),
58
+ [picked, options.uiLocale, browser],
59
+ );
60
+
61
+ const setLanguage = useCallback((tag: string) => setStored(tag), [setStored]);
62
+ const clear = useCallback(() => removeStored(), [removeStored]);
63
+
64
+ return useMemo(
65
+ () => ({ language, explicit: picked !== undefined, setLanguage, clear }),
66
+ [language, picked, setLanguage, clear],
67
+ );
68
+ }
File without changes