@rexezuge/web 1.2.0 → 1.4.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.
- package/dist/AppPage.d.ts +6 -2
- package/dist/AppPage.d.ts.map +1 -1
- package/dist/AppPage.js +1 -7
- package/dist/AppPage.js.map +7 -1
- package/dist/Badge.d.ts +9 -3
- package/dist/Badge.d.ts.map +1 -1
- package/dist/Badge.js +1 -25
- package/dist/Badge.js.map +7 -1
- package/dist/Button.d.ts +6 -2
- package/dist/Button.d.ts.map +1 -1
- package/dist/Button.js +1 -39
- package/dist/Button.js.map +7 -1
- package/dist/Card.d.ts +12 -9
- package/dist/Card.d.ts.map +1 -1
- package/dist/Card.js +1 -42
- package/dist/Card.js.map +7 -1
- package/dist/ContextBar.d.ts +9 -3
- package/dist/ContextBar.d.ts.map +1 -1
- package/dist/ContextBar.js +1 -7
- package/dist/ContextBar.js.map +7 -1
- package/dist/FocusInput.d.ts +1 -2
- package/dist/FocusInput.d.ts.map +1 -1
- package/dist/FocusInput.js +1 -19
- package/dist/FocusInput.js.map +7 -1
- package/dist/Input.d.ts +9 -8
- package/dist/Input.d.ts.map +1 -1
- package/dist/Input.js +1 -49
- package/dist/Input.js.map +7 -1
- package/dist/LanguageSelector.d.ts +6 -2
- package/dist/LanguageSelector.d.ts.map +1 -1
- package/dist/LanguageSelector.js +1 -12
- package/dist/LanguageSelector.js.map +7 -1
- package/dist/LoadingButton.d.ts +19 -7
- package/dist/LoadingButton.d.ts.map +1 -1
- package/dist/LoadingButton.js +1 -30
- package/dist/LoadingButton.js.map +7 -1
- package/dist/ModalShell.d.ts +12 -4
- package/dist/ModalShell.d.ts.map +1 -1
- package/dist/ModalShell.js +1 -22
- package/dist/ModalShell.js.map +7 -1
- package/dist/NoticeBar.d.ts +7 -3
- package/dist/NoticeBar.d.ts.map +1 -1
- package/dist/NoticeBar.js +1 -12
- package/dist/NoticeBar.js.map +7 -1
- package/dist/PageHeaderCard.d.ts +6 -2
- package/dist/PageHeaderCard.d.ts.map +1 -1
- package/dist/PageHeaderCard.js +1 -7
- package/dist/PageHeaderCard.js.map +7 -1
- package/dist/PageState.d.ts +9 -3
- package/dist/PageState.d.ts.map +1 -1
- package/dist/PageState.js +1 -47
- package/dist/PageState.js.map +7 -1
- package/dist/Pagination.d.ts +36 -12
- package/dist/Pagination.d.ts.map +1 -1
- package/dist/Pagination.js +1 -75
- package/dist/Pagination.js.map +7 -1
- package/dist/ReadOnlyField.d.ts +12 -4
- package/dist/ReadOnlyField.d.ts.map +1 -1
- package/dist/ReadOnlyField.js +1 -17
- package/dist/ReadOnlyField.js.map +7 -1
- package/dist/RefreshButton.d.ts +6 -2
- package/dist/RefreshButton.d.ts.map +1 -1
- package/dist/RefreshButton.js +1 -8
- package/dist/RefreshButton.js.map +7 -1
- package/dist/Spinner.d.ts +15 -5
- package/dist/Spinner.d.ts.map +1 -1
- package/dist/Spinner.js +1 -14
- package/dist/Spinner.js.map +7 -1
- package/dist/TypeToConfirmModal.d.ts +15 -5
- package/dist/TypeToConfirmModal.d.ts.map +1 -1
- package/dist/TypeToConfirmModal.js +1 -24
- package/dist/TypeToConfirmModal.js.map +7 -1
- package/dist/Unauthorized.d.ts +6 -2
- package/dist/Unauthorized.d.ts.map +1 -1
- package/dist/Unauthorized.js +1 -11
- package/dist/Unauthorized.js.map +7 -1
- package/dist/api.d.ts +27 -9
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +1 -258
- package/dist/api.js.map +7 -1
- package/dist/constants.js +1 -49
- package/dist/constants.js.map +7 -1
- package/dist/index.d.ts +51 -51
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -89
- package/dist/index.js.map +7 -1
- package/dist/theme.d.ts +24 -8
- package/dist/theme.d.ts.map +1 -1
- package/dist/theme.js +1 -134
- package/dist/theme.js.map +7 -1
- package/dist/useCopyToClipboard.d.ts +3 -1
- package/dist/useCopyToClipboard.d.ts.map +1 -1
- package/dist/useCopyToClipboard.js +1 -40
- package/dist/useCopyToClipboard.js.map +7 -1
- package/dist/useCurrentUser.d.ts +22 -8
- package/dist/useCurrentUser.d.ts.map +1 -1
- package/dist/useCurrentUser.js +1 -49
- package/dist/useCurrentUser.js.map +7 -1
- package/dist/useNotice.d.ts +21 -7
- package/dist/useNotice.d.ts.map +1 -1
- package/dist/useNotice.js +1 -34
- package/dist/useNotice.js.map +7 -1
- package/dist/useSpaLanguage.d.ts +27 -11
- package/dist/useSpaLanguage.d.ts.map +1 -1
- package/dist/useSpaLanguage.js +1 -149
- package/dist/useSpaLanguage.js.map +7 -1
- package/dist/utils.d.ts +6 -2
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +1 -346
- package/dist/utils.js.map +7 -1
- package/package.json +4 -4
package/dist/useCurrentUser.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ServiceError } from '@rexezuge/errors';
|
|
2
|
-
import type { ApiClient } from './api';
|
|
2
|
+
import type { ApiClient } from './api.ts';
|
|
3
3
|
/**
|
|
4
4
|
* The signed-in account, fetched once on mount.
|
|
5
5
|
*
|
|
@@ -41,25 +41,39 @@ import type { ApiClient } from './api';
|
|
|
41
41
|
* change to the account is a refresh (`reload()`), which is what the sources
|
|
42
42
|
* do at every call site anyway.
|
|
43
43
|
*/
|
|
44
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
The account shape a caller reads. `preferredLanguage` is what `useSpaLanguage` consumes.
|
|
46
|
+
*/
|
|
45
47
|
interface CurrentUser {
|
|
46
48
|
preferredLanguage?: string | null;
|
|
47
49
|
}
|
|
48
50
|
interface UseCurrentUserOptions {
|
|
49
|
-
/**
|
|
51
|
+
/**
|
|
52
|
+
The path to GET. Defaults to `/user/me`, the family's profile route.
|
|
53
|
+
*/
|
|
50
54
|
path?: string;
|
|
51
55
|
}
|
|
52
56
|
interface UseCurrentUserResult<TUser> {
|
|
53
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
The account, or `null` until it loads (and after a failure).
|
|
59
|
+
*/
|
|
54
60
|
user: TUser | null;
|
|
55
|
-
/**
|
|
61
|
+
/**
|
|
62
|
+
`true` while the request is in flight, including the first one.
|
|
63
|
+
*/
|
|
56
64
|
loading: boolean;
|
|
57
|
-
/**
|
|
65
|
+
/**
|
|
66
|
+
The normalized failure, or `null`. A `ServiceError`, always.
|
|
67
|
+
*/
|
|
58
68
|
error: ServiceError | null;
|
|
59
|
-
/**
|
|
69
|
+
/**
|
|
70
|
+
Re-runs the request.
|
|
71
|
+
*/
|
|
60
72
|
reload: () => void;
|
|
61
73
|
}
|
|
62
|
-
/**
|
|
74
|
+
/**
|
|
75
|
+
The profile route every repo in the family serves.
|
|
76
|
+
*/
|
|
63
77
|
declare const CURRENT_USER_PATH = "/user/me";
|
|
64
78
|
declare function useCurrentUser<TUser = CurrentUser>(client: ApiClient, { path }?: Readonly<UseCurrentUserOptions>): UseCurrentUserResult<TUser>;
|
|
65
79
|
export { CURRENT_USER_PATH, useCurrentUser };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCurrentUser.d.ts","sourceRoot":"","sources":["../src/useCurrentUser.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"useCurrentUser.d.ts","sourceRoot":"","sources":["../src/useCurrentUser.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAEH;;EAEE;AACF,UAAU,WAAW;IACnB,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACnC;AAED,UAAU,qBAAqB;IAC7B;;MAEE;IACF,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,UAAU,oBAAoB,CAAC,KAAK;IAClC;;MAEE;IACF,IAAI,EAAE,KAAK,GAAG,IAAI,CAAC;IACnB;;MAEE;IACF,OAAO,EAAE,OAAO,CAAC;IACjB;;MAEE;IACF,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;IAC3B;;MAEE;IACF,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB;AAED;;EAEE;AACF,QAAA,MAAM,iBAAiB,aAAa,CAAC;AAErC,iBAAS,cAAc,CAAC,KAAK,GAAG,WAAW,EACzC,MAAM,EAAE,SAAS,EACjB,EAAE,IAAwB,EAAE,GAAE,QAAQ,CAAC,qBAAqB,CAAM,GACjE,oBAAoB,CAAC,KAAK,CAAC,CAiD7B;AAED,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,CAAC;AAC7C,YAAY,EAAE,WAAW,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,CAAC"}
|
package/dist/useCurrentUser.js
CHANGED
|
@@ -1,49 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { ServiceError } from '@rexezuge/errors';
|
|
3
|
-
/** The profile route every repo in the family serves. */
|
|
4
|
-
const CURRENT_USER_PATH = '/user/me';
|
|
5
|
-
function useCurrentUser(client, { path = CURRENT_USER_PATH } = {}) {
|
|
6
|
-
const [user, setUser] = useState(null);
|
|
7
|
-
const [loading, setLoading] = useState(true);
|
|
8
|
-
const [error, setError] = useState(null);
|
|
9
|
-
const [reloadKey, setReloadKey] = useState(0);
|
|
10
|
-
// Read through a ref so a caller's fresh client instance cannot re-run the
|
|
11
|
-
// effect; refreshing is explicit, through `reload`.
|
|
12
|
-
const clientRef = useRef(client);
|
|
13
|
-
useEffect(() => {
|
|
14
|
-
clientRef.current = client;
|
|
15
|
-
}, [client]);
|
|
16
|
-
const reload = useCallback(() => {
|
|
17
|
-
setReloadKey((key) => key + 1);
|
|
18
|
-
}, []);
|
|
19
|
-
useEffect(() => {
|
|
20
|
-
let cancelled = false;
|
|
21
|
-
setLoading(true);
|
|
22
|
-
clientRef.current
|
|
23
|
-
.get(path)
|
|
24
|
-
.then((me) => {
|
|
25
|
-
if (cancelled) {
|
|
26
|
-
return;
|
|
27
|
-
}
|
|
28
|
-
setUser(me);
|
|
29
|
-
setError(null);
|
|
30
|
-
setLoading(false);
|
|
31
|
-
})
|
|
32
|
-
.catch((cause) => {
|
|
33
|
-
if (cancelled) {
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
// Normalized here as well as in the client: a client that is not this
|
|
37
|
-
// package's (`createApiClient`) may throw anything, and a hook that
|
|
38
|
-
// promises a `ServiceError` should deliver one.
|
|
39
|
-
setError(ServiceError.from(cause));
|
|
40
|
-
setLoading(false);
|
|
41
|
-
});
|
|
42
|
-
return () => {
|
|
43
|
-
cancelled = true;
|
|
44
|
-
};
|
|
45
|
-
}, [path, reloadKey]);
|
|
46
|
-
return { user, loading, error, reload };
|
|
47
|
-
}
|
|
48
|
-
export { CURRENT_USER_PATH, useCurrentUser };
|
|
49
|
-
//# sourceMappingURL=useCurrentUser.js.map
|
|
1
|
+
import{useCallback as g,useEffect as c,useRef as C,useState as r}from"react";import{ServiceError as S}from"@rexezuge/errors";const f="/user/me";function p(t,{path:o=f}={}){const[a,i]=r(null),[d,s]=r(!0),[m,u]=r(null),[R,E]=r(0),l=C(t);c(()=>{l.current=t},[t]);const U=g(()=>{s(!0),E(e=>e+1)},[]);return c(()=>{let e=!1;return l.current.get(o).then(n=>{e||(i(n),u(null),s(!1))}).catch(n=>{e||(u(S.from(n)),s(!1))}),()=>{e=!0}},[o,R]),{user:a,loading:d,error:m,reload:U}}export{f as CURRENT_USER_PATH,p as useCurrentUser};
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/useCurrentUser.ts"],
|
|
4
|
+
"sourcesContent": ["import { useCallback, useEffect, useRef, useState } from 'react';\nimport { ServiceError } from '@rexezuge/errors';\nimport type { ApiClient } from './api.ts';\n\n/**\n * The signed-in account, fetched once on mount.\n *\n * ## Provenance\n *\n * `hooks/useCurrentUser.ts` in **CalDAV-Bridge**, **Durable-DAV**,\n * **Durable-DAV-Router**, **Edge-Git**, **Edge-Sonic** and **Mail-Otter** — six\n * copies that differ on the three questions this hook exists to answer:\n *\n * 1. **Who fetches.** CalDAV-Bridge, Edge-Git, Edge-Sonic and Mail-Otter call a\n * module-level `loadCurrentUser()` from `services/userService`; Durable-DAV\n * and Durable-DAV-Router call the same helper but keep the client injectable.\n * The kit normalizes to the injectable form: the hook takes the client, so\n * nothing about the request path is baked in and a test hands it a stub.\n * 2. **What a failure means.** Durable-DAV-Router records the bug in a comment:\n * `authorized` was set to `false` for *any* failure, so a 500 or a dropped\n * connection rendered \"Sign In With Cloudflare Access\" to a caller who was\n * signed in — and the only way back was a hard reload. Its fix is a separate\n * `error` flag meaning \"we could not find out\", rendered as a retry. That is\n * the shape here: `error` carries the failure, `user` stays `null`, and the\n * caller decides what a retry looks like. A 401 is not special-cased — a 401\n * *is* an error, and a shell that renders a sign-in prompt from it should do\n * so because the app says so.\n * 3. **Effect dependencies.** Durable-DAV documents the other half of the bug:\n * the effect listed `onError` (its only dependency), `SpaApp` passed an\n * inline arrow, so the effect re-ran on every render and issued an\n * unbounded stream of `GET /user/me` from first paint. The kit takes the\n * same cure: the client is read through a ref, and the effect is keyed on\n * `reloadKey` alone. A caller can pass a fresh client every render and the\n * request count is unchanged.\n *\n * ## Normalization\n *\n * `useCurrentUser(client)` returns `{ user, loading, error, reload }`. The\n * `authorized` tri-state (`null`/`true`/`false`) is gone: `loading` already\n * distinguishes \"in flight\" from \"answered\", and `error` distinguishes\n * \"answered badly\" from \"not signed in\" — a caller that wants `authorized`\n * derives it as `loading ? null : user !== null`. `setUser` is gone too; a\n * change to the account is a refresh (`reload()`), which is what the sources\n * do at every call site anyway.\n */\n\n/**\nThe account shape a caller reads. `preferredLanguage` is what `useSpaLanguage` consumes.\n*/\ninterface CurrentUser {\n preferredLanguage?: string | null;\n}\n\ninterface UseCurrentUserOptions {\n /**\n The path to GET. Defaults to `/user/me`, the family's profile route.\n */\n path?: string;\n}\n\ninterface UseCurrentUserResult<TUser> {\n /**\n The account, or `null` until it loads (and after a failure).\n */\n user: TUser | null;\n /**\n `true` while the request is in flight, including the first one.\n */\n loading: boolean;\n /**\n The normalized failure, or `null`. A `ServiceError`, always.\n */\n error: ServiceError | null;\n /**\n Re-runs the request.\n */\n reload: () => void;\n}\n\n/**\nThe profile route every repo in the family serves.\n*/\nconst CURRENT_USER_PATH = '/user/me';\n\nfunction useCurrentUser<TUser = CurrentUser>(\n client: ApiClient,\n { path = CURRENT_USER_PATH }: Readonly<UseCurrentUserOptions> = {},\n): UseCurrentUserResult<TUser> {\n const [user, setUser] = useState<TUser | null>(null);\n const [loading, setLoading] = useState(true);\n const [error, setError] = useState<ServiceError | null>(null);\n const [reloadKey, setReloadKey] = useState(0);\n\n // Read through a ref so a caller's fresh client instance cannot re-run the\n // effect; refreshing is explicit, through `reload`.\n const clientRef = useRef(client);\n useEffect(() => {\n clientRef.current = client;\n }, [client]);\n\n const reload = useCallback(() => {\n // Set here, in the event, rather than in the effect below: the effect\n // adopting it would be a set-state-in-effect, and the initial `useState`\n // already covers the first load.\n setLoading(true);\n setReloadKey((key) => key + 1);\n }, []);\n\n useEffect(() => {\n let cancelled = false;\n clientRef.current\n .get<TUser>(path)\n .then((me) => {\n if (cancelled) {\n return;\n }\n setUser(me);\n setError(null);\n setLoading(false);\n })\n .catch((cause: unknown) => {\n if (cancelled) {\n return;\n }\n // Normalized here as well as in the client: a client that is not this\n // package's (`createApiClient`) may throw anything, and a hook that\n // promises a `ServiceError` should deliver one.\n setError(ServiceError.from(cause));\n setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [path, reloadKey]);\n\n return { user, loading, error, reload };\n}\n\nexport { CURRENT_USER_PATH, useCurrentUser };\nexport type { CurrentUser, UseCurrentUserOptions, UseCurrentUserResult };\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,eAAAA,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QACzD,OAAS,gBAAAC,MAAoB,mBAiF7B,MAAMC,EAAoB,WAE1B,SAASC,EACPC,EACA,CAAE,KAAAC,EAAOH,CAAiB,EAAsC,CAAA,EAAE,CAElE,KAAM,CAACI,EAAMC,CAAO,EAAIP,EAAuB,IAAI,EAC7C,CAACQ,EAASC,CAAU,EAAIT,EAAS,EAAI,EACrC,CAACU,EAAOC,CAAQ,EAAIX,EAA8B,IAAI,EACtD,CAACY,EAAWC,CAAY,EAAIb,EAAS,CAAC,EAItCc,EAAYf,EAAOK,CAAM,EAC/BN,EAAU,IAAK,CACbgB,EAAU,QAAUV,CACtB,EAAG,CAACA,CAAM,CAAC,EAEX,MAAMW,EAASlB,EAAY,IAAK,CAI9BY,EAAW,EAAI,EACfI,EAAcG,GAAQA,EAAM,CAAC,CAC/B,EAAG,CAAA,CAAE,EAEL,OAAAlB,EAAU,IAAK,CACb,IAAImB,EAAY,GAChB,OAAAH,EAAU,QACP,IAAWT,CAAI,EACf,KAAMa,GAAM,CACPD,IAGJV,EAAQW,CAAE,EACVP,EAAS,IAAI,EACbF,EAAW,EAAK,EAClB,CAAC,EACA,MAAOU,GAAkB,CACpBF,IAMJN,EAASV,EAAa,KAAKkB,CAAK,CAAC,EACjCV,EAAW,EAAK,EAClB,CAAC,EACI,IAAK,CACVQ,EAAY,EACd,CACF,EAAG,CAACZ,EAAMO,CAAS,CAAC,EAEb,CAAE,KAAAN,EAAM,QAAAE,EAAS,MAAAE,EAAO,OAAAK,CAAM,CACvC",
|
|
6
|
+
"names": ["useCallback", "useEffect", "useRef", "useState", "ServiceError", "CURRENT_USER_PATH", "useCurrentUser", "client", "path", "user", "setUser", "loading", "setLoading", "error", "setError", "reloadKey", "setReloadKey", "clientRef", "reload", "key", "cancelled", "me", "cause"]
|
|
7
|
+
}
|
package/dist/useNotice.d.ts
CHANGED
|
@@ -33,25 +33,39 @@
|
|
|
33
33
|
* call site reads as the event it reports — plus `dismissNotice()`.
|
|
34
34
|
*/
|
|
35
35
|
type NoticeKind = 'success' | 'error';
|
|
36
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
One transient message. `kind` is the tone, `message` the sentence.
|
|
38
|
+
*/
|
|
37
39
|
interface Notice {
|
|
38
40
|
kind: NoticeKind;
|
|
39
41
|
message: string;
|
|
40
42
|
}
|
|
41
|
-
/**
|
|
43
|
+
/**
|
|
44
|
+
The setter views and hooks are handed.
|
|
45
|
+
*/
|
|
42
46
|
type ShowNotice = (kind: NoticeKind, message: string) => void;
|
|
43
47
|
interface UseNoticeOptions {
|
|
44
|
-
/**
|
|
48
|
+
/**
|
|
49
|
+
How long a notice stays up. Defaults to `NOTICE_TIMEOUT_MS`.
|
|
50
|
+
*/
|
|
45
51
|
dismissAfterMs?: number;
|
|
46
|
-
/**
|
|
52
|
+
/**
|
|
53
|
+
A notice to start with — the URL-seeded OAuth result, in a consumer.
|
|
54
|
+
*/
|
|
47
55
|
initial?: Notice | null;
|
|
48
56
|
}
|
|
49
57
|
interface UseNoticeResult {
|
|
50
|
-
/**
|
|
58
|
+
/**
|
|
59
|
+
The notice to render, or `null` when there is nothing to say.
|
|
60
|
+
*/
|
|
51
61
|
notice: Notice | null;
|
|
52
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
Shows a notice, replacing any notice already showing (and its timer).
|
|
64
|
+
*/
|
|
53
65
|
showNotice: ShowNotice;
|
|
54
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
Hides the notice and cancels its pending dismissal.
|
|
68
|
+
*/
|
|
55
69
|
dismissNotice: () => void;
|
|
56
70
|
}
|
|
57
71
|
declare function useNotice({ dismissAfterMs, initial }?: Readonly<UseNoticeOptions>): UseNoticeResult;
|
package/dist/useNotice.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNotice.d.ts","sourceRoot":"","sources":["../src/useNotice.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,KAAK,UAAU,GAAG,SAAS,GAAG,OAAO,CAAC;AAEtC
|
|
1
|
+
{"version":3,"file":"useNotice.d.ts","sourceRoot":"","sources":["../src/useNotice.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,KAAK,UAAU,GAAG,SAAS,GAAG,OAAO,CAAC;AAEtC;;EAEE;AACF,UAAU,MAAM;IACd,IAAI,EAAE,UAAU,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;EAEE;AACF,KAAK,UAAU,GAAG,CAAC,IAAI,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAE9D,UAAU,gBAAgB;IACxB;;MAEE;IACF,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;MAEE;IACF,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED,UAAU,eAAe;IACvB;;MAEE;IACF,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB;;MAEE;IACF,UAAU,EAAE,UAAU,CAAC;IACvB;;MAEE;IACF,aAAa,EAAE,MAAM,IAAI,CAAC;CAC3B;AAED,iBAAS,SAAS,CAAC,EAAE,cAAkC,EAAE,OAAc,EAAE,GAAE,QAAQ,CAAC,gBAAgB,CAAM,GAAG,eAAe,CAqC3H;AAED,OAAO,EAAE,SAAS,EAAE,CAAC;AACrB,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,gBAAgB,EAAE,eAAe,EAAE,CAAC"}
|
package/dist/useNotice.js
CHANGED
|
@@ -1,34 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { NOTICE_TIMEOUT_MS } from './constants';
|
|
3
|
-
function useNotice({ dismissAfterMs = NOTICE_TIMEOUT_MS, initial = null } = {}) {
|
|
4
|
-
const [notice, setNotice] = useState(initial);
|
|
5
|
-
const timerRef = useRef(null);
|
|
6
|
-
const clearPendingDismissal = useCallback(() => {
|
|
7
|
-
if (timerRef.current === null) {
|
|
8
|
-
return;
|
|
9
|
-
}
|
|
10
|
-
clearTimeout(timerRef.current);
|
|
11
|
-
timerRef.current = null;
|
|
12
|
-
}, []);
|
|
13
|
-
const dismissNotice = useCallback(() => {
|
|
14
|
-
clearPendingDismissal();
|
|
15
|
-
setNotice(null);
|
|
16
|
-
}, [clearPendingDismissal]);
|
|
17
|
-
const showNotice = useCallback((kind, message) => {
|
|
18
|
-
// Replace the pending dismissal rather than stacking a second timer: two
|
|
19
|
-
// live timers mean the first notice's timeout fires while the second is
|
|
20
|
-
// still on screen.
|
|
21
|
-
clearPendingDismissal();
|
|
22
|
-
setNotice({ kind, message });
|
|
23
|
-
timerRef.current = setTimeout(() => {
|
|
24
|
-
timerRef.current = null;
|
|
25
|
-
setNotice(null);
|
|
26
|
-
}, dismissAfterMs);
|
|
27
|
-
}, [clearPendingDismissal, dismissAfterMs]);
|
|
28
|
-
// Unmounting cancels the dismissal. Without this the timer outlives the
|
|
29
|
-
// component and calls `setState` on a tree that is gone.
|
|
30
|
-
useEffect(() => clearPendingDismissal, [clearPendingDismissal]);
|
|
31
|
-
return { notice, showNotice, dismissNotice };
|
|
32
|
-
}
|
|
33
|
-
export { useNotice };
|
|
34
|
-
//# sourceMappingURL=useNotice.js.map
|
|
1
|
+
import{useCallback as u,useEffect as f,useRef as a,useState as N}from"react";import{NOTICE_TIMEOUT_MS as T}from"./constants.js";function p({dismissAfterMs:r=T,initial:c=null}={}){const[l,n]=N(c),t=a(null),e=u(()=>{t.current!==null&&(clearTimeout(t.current),t.current=null)},[]),o=u(()=>{e(),n(null)},[e]),i=u((s,m)=>{e(),n({kind:s,message:m}),t.current=setTimeout(()=>{t.current=null,n(null)},r)},[e,r]);return f(()=>e,[e]),{notice:l,showNotice:i,dismissNotice:o}}export{p as useNotice};
|
package/dist/useNotice.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/useNotice.ts"],
|
|
4
|
+
"sourcesContent": ["import { useCallback, useEffect, useRef, useState } from 'react';\nimport { NOTICE_TIMEOUT_MS } from './constants.ts';\n\n/**\n * A transient status message.\n *\n * ## Provenance\n *\n * `hooks/useNotice.ts` in **CalDAV-Bridge**, **Durable-DAV**,\n * **Durable-DAV-Router**, **Edge-Git**, **Edge-Sonic** and **Mail-Otter** — six\n * copies of one hook, with AWS-AccessBridge's `useToast` as the seventh in\n * everything but name. Each contributes one thing:\n *\n * - **Durable-DAV** — the unmount cleanup. Its comment records the bug: the\n * timer was only ever cleared in favour of the *next* notice, so unmounting\n * with a notice showing left it live to call `setState` on a gone component.\n * - **Edge-Sonic** — `clearNotice`, a dismissal that is not just \"replace it\",\n * and the exported `ShowNotice` type so feature tabs stop re-spelling the\n * setter's signature.\n * - **CalDAV-Bridge / Mail-Otter** — seeding the first notice from the URL's\n * `?oauth2=` result. That is *left local*: the parameter names are\n * product-specific, and a hook that reads a query string is a hook a test\n * has to fake a location for. A consumer seeds its own notice by passing\n * `initial` — see `UseNoticeOptions`.\n * - **All six** — a ref-held timer, so a new notice replaces the old one's\n * dismissal instead of being cut short by it (\"the error banner vanished\n * before I read it\").\n *\n * ## Normalization\n *\n * The type is `{ kind, message }`. Every copy used `{ type, text }`, and the\n * field names collided with the DOM's `type` on unrelated elements often enough\n * that `kind`/`message` read better at the call sites that build one by hand\n * (`describeProbe` in Edge-Sonic returns a notice-shaped value). The imperative\n * API is `showNotice(kind, message)` — positional, as every copy had it, so a\n * call site reads as the event it reports — plus `dismissNotice()`.\n */\n\ntype NoticeKind = 'success' | 'error';\n\n/**\nOne transient message. `kind` is the tone, `message` the sentence.\n*/\ninterface Notice {\n kind: NoticeKind;\n message: string;\n}\n\n/**\nThe setter views and hooks are handed.\n*/\ntype ShowNotice = (kind: NoticeKind, message: string) => void;\n\ninterface UseNoticeOptions {\n /**\n How long a notice stays up. Defaults to `NOTICE_TIMEOUT_MS`.\n */\n dismissAfterMs?: number;\n /**\n A notice to start with — the URL-seeded OAuth result, in a consumer.\n */\n initial?: Notice | null;\n}\n\ninterface UseNoticeResult {\n /**\n The notice to render, or `null` when there is nothing to say.\n */\n notice: Notice | null;\n /**\n Shows a notice, replacing any notice already showing (and its timer).\n */\n showNotice: ShowNotice;\n /**\n Hides the notice and cancels its pending dismissal.\n */\n dismissNotice: () => void;\n}\n\nfunction useNotice({ dismissAfterMs = NOTICE_TIMEOUT_MS, initial = null }: Readonly<UseNoticeOptions> = {}): UseNoticeResult {\n const [notice, setNotice] = useState<Notice | null>(initial);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const clearPendingDismissal = useCallback(() => {\n if (timerRef.current === null) {\n return;\n }\n clearTimeout(timerRef.current);\n timerRef.current = null;\n }, []);\n\n const dismissNotice = useCallback(() => {\n clearPendingDismissal();\n setNotice(null);\n }, [clearPendingDismissal]);\n\n const showNotice = useCallback<ShowNotice>(\n (kind, message) => {\n // Replace the pending dismissal rather than stacking a second timer: two\n // live timers mean the first notice's timeout fires while the second is\n // still on screen.\n clearPendingDismissal();\n setNotice({ kind, message });\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n setNotice(null);\n }, dismissAfterMs);\n },\n [clearPendingDismissal, dismissAfterMs],\n );\n\n // Unmounting cancels the dismissal. Without this the timer outlives the\n // component and calls `setState` on a tree that is gone.\n useEffect(() => clearPendingDismissal, [clearPendingDismissal]);\n\n return { notice, showNotice, dismissNotice };\n}\n\nexport { useNotice };\nexport type { Notice, NoticeKind, ShowNotice, UseNoticeOptions, UseNoticeResult };\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,eAAAA,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QACzD,OAAS,qBAAAC,MAAyB,iBA8ElC,SAASC,EAAU,CAAE,eAAAC,EAAiBF,EAAmB,QAAAG,EAAU,IAAI,EAAiC,CAAA,EAAE,CACxG,KAAM,CAACC,EAAQC,CAAS,EAAIN,EAAwBI,CAAO,EACrDG,EAAWR,EAA6C,IAAI,EAE5DS,EAAwBX,EAAY,IAAK,CACzCU,EAAS,UAAY,OAGzB,aAAaA,EAAS,OAAO,EAC7BA,EAAS,QAAU,KACrB,EAAG,CAAA,CAAE,EAECE,EAAgBZ,EAAY,IAAK,CACrCW,EAAqB,EACrBF,EAAU,IAAI,CAChB,EAAG,CAACE,CAAqB,CAAC,EAEpBE,EAAab,EACjB,CAACc,EAAMC,IAAW,CAIhBJ,EAAqB,EACrBF,EAAU,CAAE,KAAAK,EAAM,QAAAC,CAAO,CAAE,EAC3BL,EAAS,QAAU,WAAW,IAAK,CACjCA,EAAS,QAAU,KACnBD,EAAU,IAAI,CAChB,EAAGH,CAAc,CACnB,EACA,CAACK,EAAuBL,CAAc,CAAC,EAKzC,OAAAL,EAAU,IAAMU,EAAuB,CAACA,CAAqB,CAAC,EAEvD,CAAE,OAAAH,EAAQ,WAAAK,EAAY,cAAAD,CAAa,CAC5C",
|
|
6
|
+
"names": ["useCallback", "useEffect", "useRef", "useState", "NOTICE_TIMEOUT_MS", "useNotice", "dismissAfterMs", "initial", "notice", "setNotice", "timerRef", "clearPendingDismissal", "dismissNotice", "showNotice", "kind", "message"]
|
|
7
|
+
}
|
package/dist/useSpaLanguage.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { canonicalizeLanguageTag } from '@rexezuge/shared';
|
|
2
1
|
import type { LanguageTag } from '@rexezuge/shared';
|
|
3
2
|
/**
|
|
4
3
|
* The language the SPA is rendering, and the setter that changes it.
|
|
@@ -35,11 +34,17 @@ import type { LanguageTag } from '@rexezuge/shared';
|
|
|
35
34
|
* awaits its own bundle load before or after calling it. `supported` comes back
|
|
36
35
|
* too, so a `LanguageSelector` does not need a second import to render the list.
|
|
37
36
|
*/
|
|
38
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
The tags offered when a caller does not say. English-only is the safe default.
|
|
39
|
+
*/
|
|
39
40
|
declare const DEFAULT_SUPPORTED_LANGUAGES: readonly LanguageTag[];
|
|
40
|
-
/**
|
|
41
|
+
/**
|
|
42
|
+
The tag used when nothing supported can be resolved.
|
|
43
|
+
*/
|
|
41
44
|
declare const DEFAULT_FALLBACK_LANGUAGE: LanguageTag;
|
|
42
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
The `localStorage` key used when a caller does not say.
|
|
47
|
+
*/
|
|
43
48
|
declare const DEFAULT_LANGUAGE_STORAGE_KEY = "language";
|
|
44
49
|
/**
|
|
45
50
|
* Resolves a tag against the supported list: an exact match wins, then the
|
|
@@ -56,15 +61,23 @@ interface UseSpaLanguageOptions {
|
|
|
56
61
|
* `null`/`undefined` while the profile is not known. Adopted when it changes.
|
|
57
62
|
*/
|
|
58
63
|
preferred?: string | null;
|
|
59
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
The tags the app ships bundles for. Memoize it: it is a dependency.
|
|
66
|
+
*/
|
|
60
67
|
supported?: readonly LanguageTag[];
|
|
61
|
-
/**
|
|
68
|
+
/**
|
|
69
|
+
The `localStorage` key the choice is persisted under.
|
|
70
|
+
*/
|
|
62
71
|
storageKey?: string;
|
|
63
|
-
/**
|
|
72
|
+
/**
|
|
73
|
+
The tag used when nothing supported resolves. Defaults to `en`.
|
|
74
|
+
*/
|
|
64
75
|
fallbackLanguage?: LanguageTag;
|
|
65
76
|
}
|
|
66
77
|
interface UseSpaLanguageResult {
|
|
67
|
-
/**
|
|
78
|
+
/**
|
|
79
|
+
The tag currently in effect — a member of `supported`.
|
|
80
|
+
*/
|
|
68
81
|
language: LanguageTag;
|
|
69
82
|
/**
|
|
70
83
|
* Switches the language: resolves the tag, persists it, and syncs
|
|
@@ -72,10 +85,13 @@ interface UseSpaLanguageResult {
|
|
|
72
85
|
* being ignored, so a mistake is visible instead of silent.
|
|
73
86
|
*/
|
|
74
87
|
setLanguage: (tag: string) => void;
|
|
75
|
-
/**
|
|
88
|
+
/**
|
|
89
|
+
The tags offered, as resolved — render this list in a selector.
|
|
90
|
+
*/
|
|
76
91
|
supported: readonly LanguageTag[];
|
|
77
92
|
}
|
|
78
93
|
declare function useSpaLanguage({ preferred, supported, storageKey, fallbackLanguage, }?: Readonly<UseSpaLanguageOptions>): UseSpaLanguageResult;
|
|
79
|
-
export {
|
|
80
|
-
export type {
|
|
94
|
+
export { DEFAULT_FALLBACK_LANGUAGE, DEFAULT_LANGUAGE_STORAGE_KEY, DEFAULT_SUPPORTED_LANGUAGES, resolveLanguageTag, useSpaLanguage };
|
|
95
|
+
export type { UseSpaLanguageOptions, UseSpaLanguageResult };
|
|
96
|
+
export { canonicalizeLanguageTag, type LanguageTag } from '@rexezuge/shared';
|
|
81
97
|
//# sourceMappingURL=useSpaLanguage.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSpaLanguage.d.ts","sourceRoot":"","sources":["../src/useSpaLanguage.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useSpaLanguage.d.ts","sourceRoot":"","sources":["../src/useSpaLanguage.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH;;EAEE;AACF,QAAA,MAAM,2BAA2B,EAAE,SAAS,WAAW,EAAW,CAAC;AAEnE;;EAEE;AACF,QAAA,MAAM,yBAAyB,EAAE,WAAkB,CAAC;AAEpD;;EAEE;AACF,QAAA,MAAM,4BAA4B,aAAa,CAAC;AA8BhD;;;;;;;GAOG;AACH,iBAAS,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,SAAS,EAAE,SAAS,WAAW,EAAE,EAAE,QAAQ,EAAE,WAAW,GAAG,WAAW,CAmBnI;AA6BD,UAAU,qBAAqB;IAC7B;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B;;MAEE;IACF,SAAS,CAAC,EAAE,SAAS,WAAW,EAAE,CAAC;IACnC;;MAEE;IACF,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;MAEE;IACF,gBAAgB,CAAC,EAAE,WAAW,CAAC;CAChC;AAED,UAAU,oBAAoB;IAC5B;;MAEE;IACF,QAAQ,EAAE,WAAW,CAAC;IACtB;;;;OAIG;IACH,WAAW,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC;;MAEE;IACF,SAAS,EAAE,SAAS,WAAW,EAAE,CAAC;CACnC;AAED,iBAAS,cAAc,CAAC,EACtB,SAAS,EACT,SAAuC,EACvC,UAAyC,EACzC,gBAA4C,GAC7C,GAAE,QAAQ,CAAC,qBAAqB,CAAM,GAAG,oBAAoB,CAwD7D;AAED,OAAO,EAAE,yBAAyB,EAAE,4BAA4B,EAAE,2BAA2B,EAAE,kBAAkB,EAAE,cAAc,EAAE,CAAC;AACpI,YAAY,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,CAAC;AAE5D,OAAO,EAAE,uBAAuB,EAAE,KAAK,WAAW,EAAE,MAAM,kBAAkB,CAAC"}
|
package/dist/useSpaLanguage.js
CHANGED
|
@@ -1,149 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { canonicalizeLanguageTag } from '@rexezuge/shared';
|
|
3
|
-
/**
|
|
4
|
-
* The language the SPA is rendering, and the setter that changes it.
|
|
5
|
-
*
|
|
6
|
-
* ## Provenance
|
|
7
|
-
*
|
|
8
|
-
* `hooks/useSpaLanguage.ts` in **AWS-AccessBridge**, **Durable-DAV**,
|
|
9
|
-
* **Durable-DAV-Router**, **Edge-Git**, **Edge-Sonic** and **Mail-Otter** — six
|
|
10
|
-
* copies that agree on the detection precedence and disagree on everything
|
|
11
|
-
* else, because each one also owned its app's i18next wiring:
|
|
12
|
-
*
|
|
13
|
-
* - **Detection precedence.** All six: backend `preferredLanguage` when present
|
|
14
|
-
* > `localStorage` > `navigator.language` > `en`, with the *first present
|
|
15
|
-
* source* winning rather than the first *supported* one — AWS's
|
|
16
|
-
* `lib/language.ts` spells out why: an unsupported backend value falls to
|
|
17
|
-
* `en` rather than to the next source, because the backend value is the
|
|
18
|
-
* user's own choice and silently replacing it with whatever the browser
|
|
19
|
-
* reports would flip the UI the moment the profile loaded.
|
|
20
|
-
* - **`<html lang>` sync**, in all six, guarded because a non-browser
|
|
21
|
-
* environment has no `document`.
|
|
22
|
-
* - **Bundle loading, `languageChanged` bridging, and the backend write** —
|
|
23
|
-
* Mail-Otter/AWS `await updatePreferredLanguage(...)`, the others
|
|
24
|
-
* localStorage-only. These are *left to the app*: the kit hook keeps
|
|
25
|
-
* i18next out so it can be exercised without an i18n instance, and a caller
|
|
26
|
-
* that wants the authoritative save calls its own API from its `setLanguage`
|
|
27
|
-
* wrapper.
|
|
28
|
-
* - **`languageStatus`/`languagePending`** — left out for the same reason: both
|
|
29
|
-
* exist to describe *bundle* loading, which the app now owns.
|
|
30
|
-
*
|
|
31
|
-
* ## Normalization
|
|
32
|
-
*
|
|
33
|
-
* The hook returns `{ language, setLanguage }`. `setLanguage` is synchronous and
|
|
34
|
-
* total: it resolves the tag, persists it, and syncs `<html lang>`; the caller
|
|
35
|
-
* awaits its own bundle load before or after calling it. `supported` comes back
|
|
36
|
-
* too, so a `LanguageSelector` does not need a second import to render the list.
|
|
37
|
-
*/
|
|
38
|
-
/** The tags offered when a caller does not say. English-only is the safe default. */
|
|
39
|
-
const DEFAULT_SUPPORTED_LANGUAGES = ['en'];
|
|
40
|
-
/** The tag used when nothing supported can be resolved. */
|
|
41
|
-
const DEFAULT_FALLBACK_LANGUAGE = 'en';
|
|
42
|
-
/** The `localStorage` key used when a caller does not say. */
|
|
43
|
-
const DEFAULT_LANGUAGE_STORAGE_KEY = 'language';
|
|
44
|
-
/** The supported list in canonical form, computed once per render of the hook. */
|
|
45
|
-
function describeSupported(supported) {
|
|
46
|
-
return supported.map((tag) => {
|
|
47
|
-
const key = canonicalizeLanguageTag(tag);
|
|
48
|
-
return { tag, key, primary: key.split('-')[0] ?? key };
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Resolves a tag against the supported list: an exact match wins, then the
|
|
53
|
-
* primary subtag (`de-DE` resolves to a supported `de`), then the fallback.
|
|
54
|
-
*
|
|
55
|
-
* The prefix step is why a browser reporting `en-US` does not defeat an
|
|
56
|
-
* English-only app, and why a browser reporting `zh-TW` does not land on
|
|
57
|
-
* `zh-CN` when both are supported.
|
|
58
|
-
*/
|
|
59
|
-
function resolveLanguageTag(value, supported, fallback) {
|
|
60
|
-
if (typeof value !== 'string' || value.trim() === '') {
|
|
61
|
-
return fallback;
|
|
62
|
-
}
|
|
63
|
-
// The shared canonicalizer maps a degenerate tag to `en`, so the empty check
|
|
64
|
-
// above has to happen first — otherwise an empty stored value would silently
|
|
65
|
-
// resolve to `en` instead of the caller's fallback.
|
|
66
|
-
const key = canonicalizeLanguageTag(value);
|
|
67
|
-
const primary = key.split('-')[0] ?? key;
|
|
68
|
-
let prefixMatch = null;
|
|
69
|
-
for (const entry of describeSupported(supported)) {
|
|
70
|
-
if (entry.key === key) {
|
|
71
|
-
return entry.tag;
|
|
72
|
-
}
|
|
73
|
-
if (prefixMatch === null && entry.primary === primary) {
|
|
74
|
-
prefixMatch = entry.tag;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
return prefixMatch ?? fallback;
|
|
78
|
-
}
|
|
79
|
-
function readStoredLanguage(storageKey) {
|
|
80
|
-
try {
|
|
81
|
-
return globalThis.localStorage?.getItem(storageKey) ?? null;
|
|
82
|
-
}
|
|
83
|
-
catch {
|
|
84
|
-
// Private-mode Safari and a blocked-storage context both throw. Detection
|
|
85
|
-
// carries on without the stored value; the language still works.
|
|
86
|
-
return null;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
function writeStoredLanguage(storageKey, language) {
|
|
90
|
-
try {
|
|
91
|
-
globalThis.localStorage?.setItem(storageKey, language);
|
|
92
|
-
}
|
|
93
|
-
catch {
|
|
94
|
-
// Non-fatal: the selection still applies to this session, it just does not
|
|
95
|
-
// survive a reload.
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
function readNavigatorLanguage() {
|
|
99
|
-
try {
|
|
100
|
-
return globalThis.navigator?.language ?? null;
|
|
101
|
-
}
|
|
102
|
-
catch {
|
|
103
|
-
return null;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
function useSpaLanguage({ preferred, supported = DEFAULT_SUPPORTED_LANGUAGES, storageKey = DEFAULT_LANGUAGE_STORAGE_KEY, fallbackLanguage = DEFAULT_FALLBACK_LANGUAGE, } = {}) {
|
|
107
|
-
// Serialized so an inline `supported` array literal does not change identity
|
|
108
|
-
// on every render and re-run the effects below. Tags never contain spaces.
|
|
109
|
-
const supportedKey = supported.join(' ');
|
|
110
|
-
const supportedLanguages = useMemo(() => (supportedKey === '' ? [] : supportedKey.split(' ')), [supportedKey]);
|
|
111
|
-
const [language, setLanguageState] = useState(() =>
|
|
112
|
-
// Precedence: backend > stored > navigator > fallback. The backend value is
|
|
113
|
-
// undefined on a first paint and arrives later, which is what the effect
|
|
114
|
-
// below is for.
|
|
115
|
-
resolveLanguageTag(preferred ?? readStoredLanguage(storageKey) ?? readNavigatorLanguage(), supportedLanguages, fallbackLanguage));
|
|
116
|
-
// Adopt the backend preference once it is known. `preferred` is the
|
|
117
|
-
// authoritative source, so it overrides a value detection picked earlier —
|
|
118
|
-
// which is also what makes a returning user land on the language they chose
|
|
119
|
-
// on another device.
|
|
120
|
-
useEffect(() => {
|
|
121
|
-
if (preferred === undefined || preferred === null || preferred.trim() === '') {
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
const next = resolveLanguageTag(preferred, supportedLanguages, fallbackLanguage);
|
|
125
|
-
setLanguageState((current) => (current === next ? current : next));
|
|
126
|
-
}, [preferred, supportedLanguages, fallbackLanguage]);
|
|
127
|
-
// `<html lang>` drives hyphenation, font choice and screen-reader
|
|
128
|
-
// pronunciation, so it has to follow the tag even when the change came from
|
|
129
|
-
// detection rather than from `setLanguage`.
|
|
130
|
-
useEffect(() => {
|
|
131
|
-
try {
|
|
132
|
-
document.documentElement.lang = language;
|
|
133
|
-
}
|
|
134
|
-
catch {
|
|
135
|
-
// No DOM: server rendering, or a worker-ish test environment.
|
|
136
|
-
}
|
|
137
|
-
}, [language]);
|
|
138
|
-
const setLanguage = useCallback((tag) => {
|
|
139
|
-
const next = resolveLanguageTag(tag, supportedLanguages, fallbackLanguage);
|
|
140
|
-
setLanguageState((current) => (current === next ? current : next));
|
|
141
|
-
// Persisted only on an explicit choice. Writing on mount would turn "the
|
|
142
|
-
// browser happened to report `de`" into a stored preference, which is a
|
|
143
|
-
// different claim.
|
|
144
|
-
writeStoredLanguage(storageKey, next);
|
|
145
|
-
}, [supportedLanguages, fallbackLanguage, storageKey]);
|
|
146
|
-
return { language, setLanguage, supported: supportedLanguages };
|
|
147
|
-
}
|
|
148
|
-
export { canonicalizeLanguageTag, DEFAULT_FALLBACK_LANGUAGE, DEFAULT_LANGUAGE_STORAGE_KEY, DEFAULT_SUPPORTED_LANGUAGES, resolveLanguageTag, useSpaLanguage, };
|
|
149
|
-
//# sourceMappingURL=useSpaLanguage.js.map
|
|
1
|
+
import{useCallback as T,useEffect as d,useMemo as h,useState as m}from"react";import{canonicalizeLanguageTag as p}from"@rexezuge/shared";const L=["en"],f="en",A="language";function G(t){return t.map(a=>{const n=p(a);return{tag:a,key:n,primary:n.split("-",1)[0]??n}})}function c(t,a,n){if(typeof t!="string"||t.trim()==="")return n;const u=p(t),r=u.split("-",1)[0]??u;let e=null;for(const o of G(a)){if(o.key===u)return o.tag;e===null&&o.primary===r&&(e=o.tag)}return e??n}function U(t){try{return globalThis.localStorage?.getItem(t)??null}catch{return null}}function _(t,a){try{globalThis.localStorage?.setItem(t,a)}catch{}}function x(){try{return globalThis.navigator?.language??null}catch{return null}}function P({preferred:t,supported:a=L,storageKey:n=A,fallbackLanguage:u=f}={}){const r=a.join(" "),e=h(()=>r===""?[]:r.split(" "),[r]),[o,g]=m(()=>c(t??U(n)??x(),e,u)),[y,E]=m(t);if(t!==y&&(E(t),t!=null&&t.trim()!=="")){const i=c(t,e,u);i!==o&&g(i)}d(()=>{try{document.documentElement.lang=o}catch{}},[o]);const S=T(i=>{const s=c(i,e,u);g(l=>l===s?l:s),_(n,s)},[e,u,n]);return{language:o,setLanguage:S,supported:e}}import{canonicalizeLanguageTag as z}from"@rexezuge/shared";export{f as DEFAULT_FALLBACK_LANGUAGE,A as DEFAULT_LANGUAGE_STORAGE_KEY,L as DEFAULT_SUPPORTED_LANGUAGES,z as canonicalizeLanguageTag,c as resolveLanguageTag,P as useSpaLanguage};
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{"version":3,"file":"useSpaLanguage.js","sourceRoot":"","sources":["../src/useSpaLanguage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAClE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAG3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,qFAAqF;AACrF,MAAM,2BAA2B,GAA2B,CAAC,IAAI,CAAC,CAAC;AAEnE,2DAA2D;AAC3D,MAAM,yBAAyB,GAAgB,IAAI,CAAC;AAEpD,8DAA8D;AAC9D,MAAM,4BAA4B,GAAG,UAAU,CAAC;AAYhD,kFAAkF;AAClF,SAAS,iBAAiB,CAAC,SAAiC;IAC1D,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE;QAC3B,MAAM,GAAG,GAAG,uBAAuB,CAAC,GAAG,CAAC,CAAC;QACzC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,OAAO,EAAE,GAA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icalizeLanguageTag } from '@rexezuge/shared';\nimport type { LanguageTag } from '@rexezuge/shared';\n\n/**\n * The language the SPA is rendering, and the setter that changes it.\n *\n * ## Provenance\n *\n * `hooks/useSpaLanguage.ts` in **AWS-AccessBridge**, **Durable-DAV**,\n * **Durable-DAV-Router**, **Edge-Git**, **Edge-Sonic** and **Mail-Otter** — six\n * copies that agree on the detection precedence and disagree on everything\n * else, because each one also owned its app's i18next wiring:\n *\n * - **Detection precedence.** All six: backend `preferredLanguage` when present\n * > `localStorage` > `navigator.language` > `en`, with the *first present\n * source* winning rather than the first *supported* one — AWS's\n * `lib/language.ts` spells out why: an unsupported backend value falls to\n * `en` rather than to the next source, because the backend value is the\n * user's own choice and silently replacing it with whatever the browser\n * reports would flip the UI the moment the profile loaded.\n * - **`<html lang>` sync**, in all six, guarded because a non-browser\n * environment has no `document`.\n * - **Bundle loading, `languageChanged` bridging, and the backend write** —\n * Mail-Otter/AWS `await updatePreferredLanguage(...)`, the others\n * localStorage-only. These are *left to the app*: the kit hook keeps\n * i18next out so it can be exercised without an i18n instance, and a caller\n * that wants the authoritative save calls its own API from its `setLanguage`\n * wrapper.\n * - **`languageStatus`/`languagePending`** — left out for the same reason: both\n * exist to describe *bundle* loading, which the app now owns.\n *\n * ## Normalization\n *\n * The hook returns `{ language, setLanguage }`. `setLanguage` is synchronous and\n * total: it resolves the tag, persists it, and syncs `<html lang>`; the caller\n * awaits its own bundle load before or after calling it. `supported` comes back\n * too, so a `LanguageSelector` does not need a second import to render the list.\n */\n\n/** The tags offered when a caller does not say. English-only is the safe default. */\nconst DEFAULT_SUPPORTED_LANGUAGES: readonly LanguageTag[] = ['en'];\n\n/** The tag used when nothing supported can be resolved. */\nconst DEFAULT_FALLBACK_LANGUAGE: LanguageTag = 'en';\n\n/** The `localStorage` key used when a caller does not say. */\nconst DEFAULT_LANGUAGE_STORAGE_KEY = 'language';\n\n/** One entry of the supported list, pre-canonicalized for comparison. */\ninterface SupportedLanguage {\n /** The tag as the caller spells it — what the hook returns. */\n tag: LanguageTag;\n /** Its canonical form, for matching. */\n key: string;\n /** Its primary subtag (`zh` for `zh-CN`). */\n primary: string;\n}\n\n/** The supported list in canonical form, computed once per render of the hook. */\nfunction describeSupported(supported: readonly LanguageTag[]): SupportedLanguage[] {\n return supported.map((tag) => {\n const key = canonicalizeLanguageTag(tag);\n return { tag, key, primary: key.split('-')[0] ?? key };\n });\n}\n\n/**\n * Resolves a tag against the supported list: an exact match wins, then the\n * primary subtag (`de-DE` resolves to a supported `de`), then the fallback.\n *\n * The prefix step is why a browser reporting `en-US` does not defeat an\n * English-only app, and why a browser reporting `zh-TW` does not land on\n * `zh-CN` when both are supported.\n */\nfunction resolveLanguageTag(value: string | null | undefined, supported: readonly LanguageTag[], fallback: LanguageTag): LanguageTag {\n if (typeof value !== 'string' || value.trim() === '') {\n return fallback;\n }\n // The shared canonicalizer maps a degenerate tag to `en`, so the empty check\n // above has to happen first — otherwise an empty stored value would silently\n // resolve to `en` instead of the caller's fallback.\n const key = canonicalizeLanguageTag(value);\n const primary = key.split('-')[0] ?? key;\n let prefixMatch: LanguageTag | null = null;\n for (const entry of describeSupported(supported)) {\n if (entry.key === key) {\n return entry.tag;\n }\n if (prefixMatch === null && entry.primary === primary) {\n prefixMatch = entry.tag;\n }\n }\n return prefixMatch ?? fallback;\n}\n\nfunction readStoredLanguage(storageKey: string): string | null {\n try {\n return globalThis.localStorage?.getItem(storageKey) ?? null;\n } catch {\n // Private-mode Safari and a blocked-storage context both throw. Detection\n // carries on without the stored value; the language still works.\n return null;\n }\n}\n\nfunction writeStoredLanguage(storageKey: string, language: LanguageTag): void {\n try {\n globalThis.localStorage?.setItem(storageKey, language);\n } catch {\n // Non-fatal: the selection still applies to this session, it just does not\n // survive a reload.\n }\n}\n\nfunction readNavigatorLanguage(): string | null {\n try {\n return globalThis.navigator?.language ?? null;\n } catch {\n return null;\n }\n}\n\ninterface UseSpaLanguageOptions {\n /**\n * The backend-authoritative preference (a user's `preferredLanguage`), or\n * `null`/`undefined` while the profile is not known. Adopted when it changes.\n */\n preferred?: string | null;\n /** The tags the app ships bundles for. Memoize it: it is a dependency. */\n supported?: readonly LanguageTag[];\n /** The `localStorage` key the choice is persisted under. */\n storageKey?: string;\n /** The tag used when nothing supported resolves. Defaults to `en`. */\n fallbackLanguage?: LanguageTag;\n}\n\ninterface UseSpaLanguageResult {\n /** The tag currently in effect — a member of `supported`. */\n language: LanguageTag;\n /**\n * Switches the language: resolves the tag, persists it, and syncs\n * `<html lang>`. An unsupported tag resolves to the fallback rather than\n * being ignored, so a mistake is visible instead of silent.\n */\n setLanguage: (tag: string) => void;\n /** The tags offered, as resolved — render this list in a selector. */\n supported: readonly LanguageTag[];\n}\n\nfunction useSpaLanguage({\n preferred,\n supported = DEFAULT_SUPPORTED_LANGUAGES,\n storageKey = DEFAULT_LANGUAGE_STORAGE_KEY,\n fallbackLanguage = DEFAULT_FALLBACK_LANGUAGE,\n}: Readonly<UseSpaLanguageOptions> = {}): UseSpaLanguageResult {\n // Serialized so an inline `supported` array literal does not change identity\n // on every render and re-run the effects below. Tags never contain spaces.\n const supportedKey = supported.join(' ');\n const supportedLanguages = useMemo<readonly LanguageTag[]>(() => (supportedKey === '' ? [] : supportedKey.split(' ')), [supportedKey]);\n\n const [language, setLanguageState] = useState<LanguageTag>(() =>\n // Precedence: backend > stored > navigator > fallback. The backend value is\n // undefined on a first paint and arrives later, which is what the effect\n // below is for.\n resolveLanguageTag(preferred ?? readStoredLanguage(storageKey) ?? readNavigatorLanguage(), supportedLanguages, fallbackLanguage),\n );\n\n // Adopt the backend preference once it is known. `preferred` is the\n // authoritative source, so it overrides a value detection picked earlier —\n // which is also what makes a returning user land on the language they chose\n // on another device.\n useEffect(() => {\n if (preferred === undefined || preferred === null || preferred.trim() === '') {\n return;\n }\n const next = resolveLanguageTag(preferred, supportedLanguages, fallbackLanguage);\n setLanguageState((current) => (current === next ? current : next));\n }, [preferred, supportedLanguages, fallbackLanguage]);\n\n // `<html lang>` drives hyphenation, font choice and screen-reader\n // pronunciation, so it has to follow the tag even when the change came from\n // detection rather than from `setLanguage`.\n useEffect(() => {\n try {\n document.documentElement.lang = language;\n } catch {\n // No DOM: server rendering, or a worker-ish test environment.\n }\n }, [language]);\n\n const setLanguage = useCallback(\n (tag: string) => {\n const next = resolveLanguageTag(tag, supportedLanguages, fallbackLanguage);\n setLanguageState((current) => (current === next ? current : next));\n // Persisted only on an explicit choice. Writing on mount would turn \"the\n // browser happened to report `de`\" into a stored preference, which is a\n // different claim.\n writeStoredLanguage(storageKey, next);\n },\n [supportedLanguages, fallbackLanguage, storageKey],\n );\n\n return { language, setLanguage, supported: supportedLanguages };\n}\n\nexport {\n canonicalizeLanguageTag,\n DEFAULT_FALLBACK_LANGUAGE,\n DEFAULT_LANGUAGE_STORAGE_KEY,\n DEFAULT_SUPPORTED_LANGUAGES,\n resolveLanguageTag,\n useSpaLanguage,\n};\nexport type { LanguageTag, UseSpaLanguageOptions, UseSpaLanguageResult };\n"]}
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/useSpaLanguage.ts"],
|
|
4
|
+
"sourcesContent": ["import { useCallback, useEffect, useMemo, useState } from 'react';\nimport { canonicalizeLanguageTag } from '@rexezuge/shared';\nimport type { LanguageTag } from '@rexezuge/shared';\n\n/**\n * The language the SPA is rendering, and the setter that changes it.\n *\n * ## Provenance\n *\n * `hooks/useSpaLanguage.ts` in **AWS-AccessBridge**, **Durable-DAV**,\n * **Durable-DAV-Router**, **Edge-Git**, **Edge-Sonic** and **Mail-Otter** — six\n * copies that agree on the detection precedence and disagree on everything\n * else, because each one also owned its app's i18next wiring:\n *\n * - **Detection precedence.** All six: backend `preferredLanguage` when present\n * > `localStorage` > `navigator.language` > `en`, with the *first present\n * source* winning rather than the first *supported* one — AWS's\n * `lib/language.ts` spells out why: an unsupported backend value falls to\n * `en` rather than to the next source, because the backend value is the\n * user's own choice and silently replacing it with whatever the browser\n * reports would flip the UI the moment the profile loaded.\n * - **`<html lang>` sync**, in all six, guarded because a non-browser\n * environment has no `document`.\n * - **Bundle loading, `languageChanged` bridging, and the backend write** —\n * Mail-Otter/AWS `await updatePreferredLanguage(...)`, the others\n * localStorage-only. These are *left to the app*: the kit hook keeps\n * i18next out so it can be exercised without an i18n instance, and a caller\n * that wants the authoritative save calls its own API from its `setLanguage`\n * wrapper.\n * - **`languageStatus`/`languagePending`** — left out for the same reason: both\n * exist to describe *bundle* loading, which the app now owns.\n *\n * ## Normalization\n *\n * The hook returns `{ language, setLanguage }`. `setLanguage` is synchronous and\n * total: it resolves the tag, persists it, and syncs `<html lang>`; the caller\n * awaits its own bundle load before or after calling it. `supported` comes back\n * too, so a `LanguageSelector` does not need a second import to render the list.\n */\n\n/**\nThe tags offered when a caller does not say. English-only is the safe default.\n*/\nconst DEFAULT_SUPPORTED_LANGUAGES: readonly LanguageTag[] = ['en'];\n\n/**\nThe tag used when nothing supported can be resolved.\n*/\nconst DEFAULT_FALLBACK_LANGUAGE: LanguageTag = 'en';\n\n/**\nThe `localStorage` key used when a caller does not say.\n*/\nconst DEFAULT_LANGUAGE_STORAGE_KEY = 'language';\n\n/**\nOne entry of the supported list, pre-canonicalized for comparison.\n*/\ninterface SupportedLanguage {\n /**\n The tag as the caller spells it — what the hook returns.\n */\n tag: LanguageTag;\n /**\n Its canonical form, for matching.\n */\n key: string;\n /**\n Its primary subtag (`zh` for `zh-CN`).\n */\n primary: string;\n}\n\n/**\nThe supported list in canonical form, computed once per render of the hook.\n*/\nfunction describeSupported(supported: readonly LanguageTag[]): SupportedLanguage[] {\n return supported.map((tag) => {\n const key = canonicalizeLanguageTag(tag);\n return { tag, key, primary: key.split('-', 1)[0] ?? key };\n });\n}\n\n/**\n * Resolves a tag against the supported list: an exact match wins, then the\n * primary subtag (`de-DE` resolves to a supported `de`), then the fallback.\n *\n * The prefix step is why a browser reporting `en-US` does not defeat an\n * English-only app, and why a browser reporting `zh-TW` does not land on\n * `zh-CN` when both are supported.\n */\nfunction resolveLanguageTag(value: string | null | undefined, supported: readonly LanguageTag[], fallback: LanguageTag): LanguageTag {\n if (typeof value !== 'string' || value.trim() === '') {\n return fallback;\n }\n // The shared canonicalizer maps a degenerate tag to `en`, so the empty check\n // above has to happen first — otherwise an empty stored value would silently\n // resolve to `en` instead of the caller's fallback.\n const key = canonicalizeLanguageTag(value);\n const primary = key.split('-', 1)[0] ?? key;\n let prefixMatch: LanguageTag | null = null;\n for (const entry of describeSupported(supported)) {\n if (entry.key === key) {\n return entry.tag;\n }\n if (prefixMatch === null && entry.primary === primary) {\n prefixMatch = entry.tag;\n }\n }\n return prefixMatch ?? fallback;\n}\n\nfunction readStoredLanguage(storageKey: string): string | null {\n try {\n return globalThis.localStorage?.getItem(storageKey) ?? null;\n } catch {\n // Private-mode Safari and a blocked-storage context both throw. Detection\n // carries on without the stored value; the language still works.\n return null;\n }\n}\n\nfunction writeStoredLanguage(storageKey: string, language: LanguageTag): void {\n try {\n globalThis.localStorage?.setItem(storageKey, language);\n } catch {\n // Non-fatal: the selection still applies to this session, it just does not\n // survive a reload.\n }\n}\n\nfunction readNavigatorLanguage(): string | null {\n try {\n return globalThis.navigator?.language ?? null;\n } catch {\n return null;\n }\n}\n\ninterface UseSpaLanguageOptions {\n /**\n * The backend-authoritative preference (a user's `preferredLanguage`), or\n * `null`/`undefined` while the profile is not known. Adopted when it changes.\n */\n preferred?: string | null;\n /**\n The tags the app ships bundles for. Memoize it: it is a dependency.\n */\n supported?: readonly LanguageTag[];\n /**\n The `localStorage` key the choice is persisted under.\n */\n storageKey?: string;\n /**\n The tag used when nothing supported resolves. Defaults to `en`.\n */\n fallbackLanguage?: LanguageTag;\n}\n\ninterface UseSpaLanguageResult {\n /**\n The tag currently in effect — a member of `supported`.\n */\n language: LanguageTag;\n /**\n * Switches the language: resolves the tag, persists it, and syncs\n * `<html lang>`. An unsupported tag resolves to the fallback rather than\n * being ignored, so a mistake is visible instead of silent.\n */\n setLanguage: (tag: string) => void;\n /**\n The tags offered, as resolved — render this list in a selector.\n */\n supported: readonly LanguageTag[];\n}\n\nfunction useSpaLanguage({\n preferred,\n supported = DEFAULT_SUPPORTED_LANGUAGES,\n storageKey = DEFAULT_LANGUAGE_STORAGE_KEY,\n fallbackLanguage = DEFAULT_FALLBACK_LANGUAGE,\n}: Readonly<UseSpaLanguageOptions> = {}): UseSpaLanguageResult {\n // Serialized so an inline `supported` array literal does not change identity\n // on every render and re-run the effects below. Tags never contain spaces.\n const supportedKey = supported.join(' ');\n const supportedLanguages = useMemo<readonly LanguageTag[]>(() => (supportedKey === '' ? [] : supportedKey.split(' ')), [supportedKey]);\n\n const [language, setLanguageState] = useState<LanguageTag>(() =>\n // Precedence: backend > stored > navigator > fallback. The backend value is\n // undefined on a first paint and arrives later, which is what the adoption\n // below is for.\n resolveLanguageTag(preferred ?? readStoredLanguage(storageKey) ?? readNavigatorLanguage(), supportedLanguages, fallbackLanguage),\n );\n\n // Adopt the backend preference once it is known. `preferred` is the\n // authoritative source, so it overrides a value detection picked earlier —\n // which is also what makes a returning user land on the language they chose\n // on another device.\n //\n // Adjusted during render, not in an effect: the guarded `prevPreferred`\n // comparison is React's documented derive-from-props pattern, and it adopts\n // in the render the value arrives in rather than one render later.\n const [prevPreferred, setPrevPreferred] = useState<string | null | undefined>(preferred);\n if (preferred !== prevPreferred) {\n setPrevPreferred(preferred);\n if (preferred !== undefined && preferred !== null && preferred.trim() !== '') {\n const next = resolveLanguageTag(preferred, supportedLanguages, fallbackLanguage);\n if (next !== language) {\n setLanguageState(next);\n }\n }\n }\n\n // `<html lang>` drives hyphenation, font choice and screen-reader\n // pronunciation, so it has to follow the tag even when the change came from\n // detection rather than from `setLanguage`.\n useEffect(() => {\n try {\n document.documentElement.lang = language;\n } catch {\n // No DOM: server rendering, or a worker-ish test environment.\n }\n }, [language]);\n\n const setLanguage = useCallback(\n (tag: string) => {\n const next = resolveLanguageTag(tag, supportedLanguages, fallbackLanguage);\n setLanguageState((current) => (current === next ? current : next));\n // Persisted only on an explicit choice. Writing on mount would turn \"the\n // browser happened to report `de`\" into a stored preference, which is a\n // different claim.\n writeStoredLanguage(storageKey, next);\n },\n [supportedLanguages, fallbackLanguage, storageKey],\n );\n\n return { language, setLanguage, supported: supportedLanguages };\n}\n\nexport { DEFAULT_FALLBACK_LANGUAGE, DEFAULT_LANGUAGE_STORAGE_KEY, DEFAULT_SUPPORTED_LANGUAGES, resolveLanguageTag, useSpaLanguage };\nexport type { UseSpaLanguageOptions, UseSpaLanguageResult };\n\nexport { canonicalizeLanguageTag, type LanguageTag } from '@rexezuge/shared';\n"],
|
|
5
|
+
"mappings": "AAAA,OAAS,eAAAA,EAAa,aAAAC,EAAW,WAAAC,EAAS,YAAAC,MAAgB,QAC1D,OAAS,2BAAAC,MAA+B,mBA0CxC,MAAMC,EAAsD,CAAC,IAAI,EAK3DC,EAAyC,KAKzCC,EAA+B,WAuBrC,SAASC,EAAkBC,EAAiC,CAC1D,OAAOA,EAAU,IAAKC,GAAO,CAC3B,MAAMC,EAAMP,EAAwBM,CAAG,EACvC,MAAO,CAAE,IAAAA,EAAK,IAAAC,EAAK,QAASA,EAAI,MAAM,IAAK,CAAC,EAAE,CAAC,GAAKA,CAAG,CACzD,CAAC,CACH,CAUA,SAASC,EAAmBC,EAAkCJ,EAAmCK,EAAqB,CACpH,GAAI,OAAOD,GAAU,UAAYA,EAAM,KAAI,IAAO,GAChD,OAAOC,EAKT,MAAMH,EAAMP,EAAwBS,CAAK,EACnCE,EAAUJ,EAAI,MAAM,IAAK,CAAC,EAAE,CAAC,GAAKA,EACxC,IAAIK,EAAkC,KACtC,UAAWC,KAAST,EAAkBC,CAAS,EAAG,CAChD,GAAIQ,EAAM,MAAQN,EAChB,OAAOM,EAAM,IAEXD,IAAgB,MAAQC,EAAM,UAAYF,IAC5CC,EAAcC,EAAM,IAExB,CACA,OAAOD,GAAeF,CACxB,CAEA,SAASI,EAAmBC,EAAkB,CAC5C,GAAI,CACF,OAAO,WAAW,cAAc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AE,EAAU,YAAAW,EAAa,UAAWL,CAAkB,CAC/D,CAKA,OAAS,2BAAAvB,MAAiD",
|
|
6
|
+
"names": ["useCallback", "useEffect", "useMemo", "useState", "canonicalizeLanguageTag", "DEFAULT_SUPPORTED_LANGUAGES", "DEFAULT_FALLBACK_LANGUAGE", "DEFAULT_LANGUAGE_STORAGE_KEY", "describeSupported", "supported", "tag", "key", "resolveLanguageTag", "value", "fallback", "primary", "prefixMatch", "entry", "readStoredLanguage", "storageKey", "writeStoredLanguage", "language", "readNavigatorLanguage", "useSpaLanguage", "preferred", "fallbackLanguage", "supportedKey", "supportedLanguages", "setLanguageState", "prevPreferred", "setPrevPreferred", "next", "setLanguage", "current"]
|
|
7
|
+
}
|
package/dist/utils.d.ts
CHANGED
|
@@ -33,9 +33,13 @@
|
|
|
33
33
|
* colour. A consumer that needs the complete table can wrap this one:
|
|
34
34
|
* `const cn = (...values: ClassValue[]) => twMerge(kitCn(...values))`.
|
|
35
35
|
*/
|
|
36
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
Everything `cn` accepts, mirroring clsx's `ClassValue`.
|
|
38
|
+
*/
|
|
37
39
|
type ClassValue = string | number | boolean | null | undefined | ClassDictionary | readonly ClassValue[];
|
|
38
|
-
/**
|
|
40
|
+
/**
|
|
41
|
+
`{ 'px-4': isActive }` — a class is present when its value is truthy.
|
|
42
|
+
*/
|
|
39
43
|
interface ClassDictionary {
|
|
40
44
|
[className: string]: boolean | null | undefined;
|
|
41
45
|
}
|
package/dist/utils.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH;;EAEE;AACF,KAAK,UAAU,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,GAAG,eAAe,GAAG,SAAS,UAAU,EAAE,CAAC;AAEzG;;EAEE;AACF,UAAU,eAAe;IACvB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,CAAC;CACjD;AA6TD;;;;;;;GAOG;AACH,iBAAS,EAAE,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,GAAG,MAAM,CAI3C;AAED,OAAO,EAAE,EAAE,EAAE,CAAC;AACd,YAAY,EAAE,eAAe,EAAE,UAAU,EAAE,CAAC"}
|