shared-lib-web 0.0.3 → 0.0.4

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.
Files changed (44) hide show
  1. package/README.md +193 -783
  2. package/dist/components/otp-modal.d.ts +5 -0
  3. package/dist/components/otp-modal.d.ts.map +1 -0
  4. package/dist/components/otp-modal.js +77 -0
  5. package/dist/components/otp-modal.js.map +1 -0
  6. package/dist/i18n/default-messages.d.ts.map +1 -1
  7. package/dist/i18n/default-messages.js +12 -0
  8. package/dist/i18n/default-messages.js.map +1 -1
  9. package/dist/index.d.ts +5 -3
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +4 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/interfaces/ui-config.d.ts +22 -0
  14. package/dist/interfaces/ui-config.d.ts.map +1 -1
  15. package/dist/state/auth-service.d.ts +5 -0
  16. package/dist/state/auth-service.d.ts.map +1 -1
  17. package/dist/state/auth-service.js +25 -2
  18. package/dist/state/auth-service.js.map +1 -1
  19. package/dist/state/otp-service.d.ts +69 -0
  20. package/dist/state/otp-service.d.ts.map +1 -0
  21. package/dist/state/otp-service.js +212 -0
  22. package/dist/state/otp-service.js.map +1 -0
  23. package/dist/types/field-wrapper.d.ts +2 -0
  24. package/dist/types/field-wrapper.d.ts.map +1 -1
  25. package/dist/types/field-wrapper.js +3 -2
  26. package/dist/types/field-wrapper.js.map +1 -1
  27. package/dist/types/type.otp.d.ts +2 -0
  28. package/dist/types/type.otp.d.ts.map +1 -1
  29. package/dist/types/type.otp.js +2 -2
  30. package/dist/types/type.otp.js.map +1 -1
  31. package/dist/utils/app-http.d.ts +12 -0
  32. package/dist/utils/app-http.d.ts.map +1 -1
  33. package/dist/utils/app-http.js +75 -1
  34. package/dist/utils/app-http.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/components/otp-modal.tsx +154 -0
  37. package/src/i18n/default-messages.ts +12 -0
  38. package/src/index.ts +31 -1
  39. package/src/interfaces/ui-config.ts +23 -0
  40. package/src/state/auth-service.ts +28 -2
  41. package/src/state/otp-service.ts +283 -0
  42. package/src/types/field-wrapper.tsx +5 -2
  43. package/src/types/type.otp.tsx +11 -2
  44. package/src/utils/app-http.ts +80 -1
@@ -0,0 +1,154 @@
1
+ // otp-modal.tsx
2
+ // One-time code dialog: TypeModal + TypeOtp. Render it once (page or layout) and open it with openOtpModal();
3
+ // the code is sent on open, "Resend code" works after config.http.otp.resendSeconds, and the form verifies the
4
+ // code (on Verify, or by itself once every box is filled). State and HTTP calls: state/otp-service.ts.
5
+ //
6
+ // <OtpModal />
7
+ // openOtpModal({ userId: email, title: t("profile.verifyEmail"), message: t("profile.verifyEmailText"),
8
+ // onVerified: handleEmailVerified });
9
+
10
+ import { ConstKeys, ConstValue, RegExp as UtilRegExp } from "dff-util";
11
+ import { useEffect } from "react";
12
+ import { useForm, useWatch, type RegisterOptions } from "react-hook-form";
13
+ import { useUi } from "../context/use-ui.ts";
14
+ import type { TranslateFunction } from "../interfaces/ui-context.ts";
15
+ import {
16
+ cancelOtpModal,
17
+ formatOtpCountdown,
18
+ handleOtpResend,
19
+ handleOtpVerify,
20
+ otpIsSendingSignal,
21
+ otpIsVerifyingSignal,
22
+ otpModalSignal,
23
+ otpResendSecondsSignal,
24
+ readOtpLength,
25
+ type OtpFormType,
26
+ } from "../state/otp-service.ts";
27
+ import { TypeButton } from "../types/type.button.tsx";
28
+ import { TypeModal } from "../types/type.modal.tsx";
29
+ import { TypeOtp } from "../types/type.otp.tsx";
30
+
31
+ /** id of the <form>: the Verify button in the modal footer points at it. */
32
+ export const OTP_FORM_ID = "shared-lib-web-otp-form";
33
+
34
+ const OTP_DEFAULT_VALUES: OtpFormType = { otp: ConstValue.EMPTY };
35
+
36
+ interface OtpModalDialogProps {
37
+ title: string;
38
+ message: string;
39
+ userId: string;
40
+ }
41
+
42
+ /** Required, digits only, exactly `length` characters. */
43
+ function buildOtpRules(length: number): RegisterOptions<OtpFormType, "otp"> {
44
+ return {
45
+ required: { value: true, message: ConstKeys.REQUIRED },
46
+ pattern: { value: UtilRegExp.DIGITS_ONLY, message: ConstKeys.FIELD_MUST_BE_NUMERIC },
47
+ minLength: { value: length, message: ConstKeys.MIN_LENGTH_REQUIRED },
48
+ };
49
+ }
50
+
51
+ /** "Resend in 2:05", "Resend code". */
52
+ function readResendLabel(seconds: number, t: TranslateFunction): string {
53
+ if (seconds <= 0) {
54
+ return t("ui.otpResend");
55
+ }
56
+ const time = formatOtpCountdown(seconds);
57
+ return t("ui.otpResendIn", { time: time });
58
+ }
59
+
60
+ /** Verifies by itself once every box is filled (for useEffect, bound with the current value). */
61
+ function submitWhenComplete(otpValue: string, length: number, submit: () => Promise<void>): void {
62
+ const isComplete = otpValue.length === length;
63
+ if (!isComplete || otpIsVerifyingSignal.peek()) {
64
+ return;
65
+ }
66
+ void submit();
67
+ }
68
+
69
+ /** The open dialog. A new form every time it opens (keyed by the user id). */
70
+ function OtpModalDialog(props: OtpModalDialogProps) {
71
+ const { title, message, userId } = props;
72
+ const { t } = useUi();
73
+ const length = readOtpLength();
74
+ const formOptions = { defaultValues: OTP_DEFAULT_VALUES };
75
+ const form = useForm<OtpFormType>(formOptions);
76
+ const onSubmit = form.handleSubmit(handleOtpVerify);
77
+ const watchOptions = { control: form.control, name: "otp" as const };
78
+ const watchedOtp = useWatch(watchOptions);
79
+ const otpValue = watchedOtp ?? ConstValue.EMPTY;
80
+ const autoSubmit = submitWhenComplete.bind(null, otpValue, length, onSubmit);
81
+ const autoSubmitDeps = [otpValue];
82
+ useEffect(autoSubmit, autoSubmitDeps);
83
+
84
+ const otpRules = buildOtpRules(length);
85
+ const isSending = otpIsSendingSignal.value;
86
+ const isVerifying = otpIsVerifyingSignal.value;
87
+ const resendSeconds = otpResendSecondsSignal.value;
88
+ const resendLabel = readResendLabel(resendSeconds, t);
89
+ const isVerifyDisabled = otpValue.length < length || isSending;
90
+
91
+ const footer = (
92
+ <>
93
+ <TypeButton action="ghost" label={t("ui.cancel")} onPress={cancelOtpModal} disabled={isVerifying} />
94
+ <TypeButton
95
+ type="submit"
96
+ form={OTP_FORM_ID}
97
+ icon="ShieldCheck"
98
+ label={t("ui.otpVerify")}
99
+ isLoading={isVerifying}
100
+ disabled={isVerifyDisabled}
101
+ />
102
+ </>
103
+ );
104
+
105
+ return (
106
+ <TypeModal isOpen title={title} onClose={cancelOtpModal} size="sm" footer={footer}>
107
+ <form id={OTP_FORM_ID} onSubmit={onSubmit} noValidate className="flex flex-col items-center gap-4 text-center">
108
+ <div className="space-y-1">
109
+ <p className="text-lg font-semibold break-all" dir="ltr">
110
+ {userId}
111
+ </p>
112
+ <p className="mx-auto max-w-xs text-sm leading-relaxed opacity-70">{message}</p>
113
+ </div>
114
+ <TypeOtp
115
+ control={form.control}
116
+ name="otp"
117
+ label={t("ui.otpCode")}
118
+ isLabelHidden
119
+ length={length}
120
+ rules={otpRules}
121
+ disabled={isVerifying}
122
+ />
123
+ <div className="flex flex-wrap items-center justify-center gap-1 text-sm">
124
+ <span className="opacity-70">{t("ui.otpNoCode")}</span>
125
+ <TypeButton
126
+ action="link"
127
+ size="sm"
128
+ label={resendLabel}
129
+ onPress={handleOtpResend}
130
+ isLoading={isSending}
131
+ disabled={resendSeconds > 0 || isVerifying}
132
+ />
133
+ </div>
134
+ </form>
135
+ </TypeModal>
136
+ );
137
+ }
138
+
139
+ /** The one-time code dialog. Shows nothing until openOtpModal() is called. */
140
+ export function OtpModal() {
141
+ useUi();
142
+ const state = otpModalSignal.value;
143
+ if (!state.isOpen) {
144
+ return null;
145
+ }
146
+ return (
147
+ <OtpModalDialog
148
+ key={state.userId}
149
+ title={state.title}
150
+ message={state.message}
151
+ userId={state.userId}
152
+ />
153
+ );
154
+ }
@@ -63,6 +63,18 @@ export const DEFAULT_UI_MESSAGES: LocaleMessages = {
63
63
  uploadTypeError: "\"{{name}}\" is not an allowed file type. Please upload {{types}}.",
64
64
  uploadSizeError: "\"{{name}}\" ({{size}}) is larger than the allowed {{max}}.",
65
65
  uploadTotalError: "Total size {{size}} is larger than the allowed {{max}}.",
66
+ otpTitle: "Verification code",
67
+ otpText: "Please enter the OTP sent to your registered id to verify your identity.",
68
+ otpCode: "OTP",
69
+ otpNoCode: "Didn't receive the code?",
70
+ otpResend: "Resend code",
71
+ otpResendIn: "Resend in {{time}}",
72
+ otpVerify: "Verify",
73
+ otpSent: "The code was sent.",
74
+ otpSendFailed: "Could not send the code. Please try again.",
75
+ otpVerified: "Verified.",
76
+ otpInvalid: "The code is not valid. Please try again.",
77
+ otpSessionMissing: "Please send a new code first.",
66
78
  },
67
79
  };
68
80
 
package/src/index.ts CHANGED
@@ -38,7 +38,7 @@ export type {
38
38
  ToastPosition,
39
39
  UiConfig,
40
40
  } from "./interfaces/ui-config.ts";
41
- export type { HttpConfig } from "./interfaces/ui-config.ts";
41
+ export type { HttpConfig, OtpConfig } from "./interfaces/ui-config.ts";
42
42
  export type {
43
43
  AuthUser,
44
44
  BranchOption,
@@ -197,6 +197,8 @@ export {
197
197
  redirectToLogoutUrl,
198
198
  isAuthenticatedSignal,
199
199
  readAccessToken,
200
+ readTokenKey,
201
+ refreshSessionToken,
200
202
  restoreSession,
201
203
  sessionTokenSignal,
202
204
  startSession,
@@ -212,6 +214,9 @@ export {
212
214
  toAbsoluteUrl,
213
215
  uploadToSignedUrl,
214
216
  clearSharedGetCache,
217
+ jwtRegenerateCall,
218
+ readRegenerateUrl,
219
+ ensureFreshToken,
215
220
  type HttpHeaders,
216
221
  type HttpParams,
217
222
  } from "./utils/app-http.ts";
@@ -353,6 +358,31 @@ export { PageLoader } from "./components/page-loader.tsx";
353
358
  export { TopProgress } from "./components/top-progress.tsx";
354
359
  export { ScrollToTop, scrollToTop, type ScrollToTopProps } from "./components/scroll-to-top.tsx";
355
360
  export { SettingsMenu, closeSettings, openSettings, type SettingsMenuProps } from "./components/settings-menu.tsx";
361
+ export { OTP_FORM_ID, OtpModal } from "./components/otp-modal.tsx";
362
+ export {
363
+ DEFAULT_OTP_LENGTH,
364
+ DEFAULT_OTP_RESEND_SECONDS,
365
+ cancelOtpModal,
366
+ closeOtpModal,
367
+ formatOtpCountdown,
368
+ handleOtpResend,
369
+ handleOtpVerify,
370
+ openOtpModal,
371
+ otpIsSendingSignal,
372
+ otpIsVerifyingSignal,
373
+ otpModalSignal,
374
+ otpResendSecondsSignal,
375
+ otpSendCall,
376
+ otpSessionSignal,
377
+ readOtpConfig,
378
+ readOtpLength,
379
+ stopOtpResendCountdown,
380
+ type OtpFormType,
381
+ type OtpModalState,
382
+ type OtpOpenOptions,
383
+ type OtpSession,
384
+ type OtpVerifiedResult,
385
+ } from "./state/otp-service.ts";
356
386
 
357
387
  // ---- Skeletons ----
358
388
  export { SkeletonArticle } from "./skeleton/skeleton-article.tsx";
@@ -217,6 +217,21 @@ export type PageMode = "query" | "path";
217
217
  /** Toast corner / edge. "end" is right in LTR and left in RTL. */
218
218
  export type ToastPosition = "top-start" | "top-center" | "top-end" | "bottom-start" | "bottom-center" | "bottom-end";
219
219
 
220
+ /**
221
+ * The one-time code (OTP) services used by OtpModal / openOtpModal. URLs or paths (a path gets the base URL):
222
+ * http: { otp: { sendUrl: `${MsUrl.sor}/otp-send`, verifyUrl: `${MsUrl.sor}/otp-verify`, resendSeconds: 180 } }
223
+ */
224
+ export interface OtpConfig {
225
+ /** POST { userid } -> { data: { message, oid, uid } } (or the object itself). */
226
+ sendUrl: string;
227
+ /** POST { otp, oid, uid } -> { data: { message, oid, uid } } (or the object itself). */
228
+ verifyUrl: string;
229
+ /** Seconds before "Resend code" works again. Default 180. */
230
+ resendSeconds?: number;
231
+ /** Number of characters of the code. Default 6. */
232
+ length?: number;
233
+ }
234
+
220
235
  /** Backend settings used by AppHttp and the session. */
221
236
  export interface HttpConfig {
222
237
  /** API base URL, for example "https://api.example.com/api" or "/api". window.env API_BASE_URL wins when set. */
@@ -231,6 +246,14 @@ export interface HttpConfig {
231
246
  loadUrl?: string;
232
247
  /** Show the top progress bar during requests. Default true. */
233
248
  showProgress?: boolean;
249
+ /**
250
+ * URL (or path) of the JWT regenerate service (GET, answers { token } or { data: { token } }), for example
251
+ * `${MsUrl.utils}/jwt-regenerate`. Before a request, when JwtValid(token) is false, AppHttp gets a new token
252
+ * (saved in sessionStorage); an error logs out (endSession -> logoutUrl). Not set: no regeneration.
253
+ */
254
+ regenerateUrl?: string;
255
+ /** One-time code services of OtpModal (send / verify). Not set: openOtpModal shows an error toast. */
256
+ otp?: OtpConfig;
234
257
  }
235
258
 
236
259
  /** The whole configuration of an app. */
@@ -6,6 +6,7 @@
6
6
  // isAuthenticatedSignal.value // true / false
7
7
  // endSession(); // log out (LANG, THEME ... are kept)
8
8
  // endSession([BRANCH_ID]); // log out, also keeps the listed AppStorage keys
9
+ // refreshSessionToken(newToken); // new token after a JWT regenerate (user stays; AppHttp calls it itself)
9
10
  //
10
11
  // Microfrontends: each one bundles its own copy of the library. startSession / endSession fire SESSION_EVENT, and
11
12
  // every other copy (startSessionSync, started by the provider) applies it: an auth MFE signs in -> the shell is signed in.
@@ -43,17 +44,18 @@ const LIBRARY_COPY_ID = String(randomNumber);
43
44
  /** What SESSION_EVENT carries. */
44
45
  interface SessionEventDetail {
45
46
  isSignedIn?: boolean;
47
+ isTokenRefresh?: boolean;
46
48
  copyId?: string;
47
49
  }
48
50
 
49
51
  let isSessionSyncStarted = false;
50
52
 
51
53
  /** Tells every other library copy on the page that the session started or ended. */
52
- function notifySessionChanged(isSignedIn: boolean): void {
54
+ function notifySessionChanged(isSignedIn: boolean, isTokenRefresh: boolean = false): void {
53
55
  if (typeof window === "undefined") {
54
56
  return;
55
57
  }
56
- const detail: SessionEventDetail = { isSignedIn: isSignedIn, copyId: LIBRARY_COPY_ID };
58
+ const detail: SessionEventDetail = { isSignedIn: isSignedIn, isTokenRefresh: isTokenRefresh, copyId: LIBRARY_COPY_ID };
57
59
  const eventInit = { detail: detail };
58
60
  const sessionEvent = new CustomEvent(SESSION_EVENT, eventInit);
59
61
  window.dispatchEvent(sessionEvent);
@@ -87,6 +89,26 @@ export function startSession(token: string, user: AuthUser | null, isRemembered:
87
89
  notifySessionChanged(true);
88
90
  }
89
91
 
92
+ /**
93
+ * Replaces the token after a JWT regenerate: user, branch and REMEMBER_ME stay, no menu / branch reload.
94
+ * Every other library copy on the page takes the new token too.
95
+ */
96
+ export function refreshSessionToken(token: string): void {
97
+ const tokenKey = readTokenKey();
98
+ AppStorage.setData(tokenKey, token);
99
+ sessionTokenSignal.value = token;
100
+ notifySessionChanged(true, true);
101
+ }
102
+
103
+ /** Another library copy refreshed the token: read it from AppStorage. */
104
+ function applyRefreshedToken(): void {
105
+ const tokenKey = readTokenKey();
106
+ const token = AppStorage.getData(tokenKey);
107
+ if (typeof token === "string" && token.length > 0) {
108
+ sessionTokenSignal.value = token;
109
+ }
110
+ }
111
+
90
112
  /** Reads a saved session (sessionStorage). Called by SharedWebUiProvider. */
91
113
  export function restoreSession(): void {
92
114
  restoreBranch();
@@ -139,6 +161,10 @@ export function handleSessionEvent(event: Event): void {
139
161
  if (!detail || isOwnEvent) {
140
162
  return;
141
163
  }
164
+ if (detail.isTokenRefresh) {
165
+ applyRefreshedToken();
166
+ return;
167
+ }
142
168
  if (detail.isSignedIn) {
143
169
  restoreSession();
144
170
  return;
@@ -0,0 +1,283 @@
1
+ // otp-service.ts
2
+ // State and HTTP calls of the one-time code dialog (components/otp-modal.tsx). The URLs come from config.http.otp:
3
+ //
4
+ // // config.ts
5
+ // http: { baseUrl, otp: { sendUrl: `${MsUrl.sor}/otp-send`, verifyUrl: `${MsUrl.sor}/otp-verify`, resendSeconds: 180 } }
6
+ //
7
+ // // page: render <OtpModal /> once, then open it (the code is sent on open)
8
+ // openOtpModal({ userId: email, title: t("profile.verifyEmail"), message: t("profile.verifyEmailText"),
9
+ // onVerified: handleEmailVerified });
10
+ // export function handleEmailVerified(result: OtpVerifiedResult): void { ... result.oid, result.uid, result.otp ... }
11
+ //
12
+ // Send: POST sendUrl { userid } -> { data: { message, oid, uid } }
13
+ // Verify: POST verifyUrl { otp, oid, uid } -> { data: { message, oid, uid } }
14
+ // The backend message is shown as a toast; a failed call shows the backend error (readErrorMessage).
15
+
16
+ import { signal } from "@preact/signals-react";
17
+ import { ConstValue } from "dff-util";
18
+ import { translate } from "../i18n/translator.ts";
19
+ import type { OtpConfig } from "../interfaces/ui-config.ts";
20
+ import { readAppConfig } from "../utils/app-config.ts";
21
+ import { AppHttp } from "../utils/app-http.ts";
22
+ import { readErrorMessage } from "../utils/error-util.ts";
23
+ import { ShowToast } from "./toast-service.ts";
24
+
25
+ /** Default number of characters of the code. */
26
+ export const DEFAULT_OTP_LENGTH = 6;
27
+
28
+ /** Default seconds before "Resend code" works again. */
29
+ export const DEFAULT_OTP_RESEND_SECONDS = 180;
30
+
31
+ const OTP_CONFIG_MISSING = "shared-lib-web: config.http.otp (sendUrl, verifyUrl) is missing.";
32
+
33
+ /** oid + uid of the code that was sent: the verify call needs them. */
34
+ export interface OtpSession {
35
+ oid: string;
36
+ uid: string;
37
+ }
38
+
39
+ /** What onVerified receives. */
40
+ export interface OtpVerifiedResult extends OtpSession {
41
+ otp: string;
42
+ }
43
+
44
+ /** The form of the dialog. */
45
+ export interface OtpFormType {
46
+ otp: string;
47
+ }
48
+
49
+ /** What openOtpModal needs. */
50
+ export interface OtpOpenOptions {
51
+ /** Sent as "userid" and shown in the dialog (email, mobile or user id). */
52
+ userId: string;
53
+ /** Heading (already translated). Default t("ui.otpTitle"). */
54
+ title?: string;
55
+ /** Text under the user id (already translated). Default t("ui.otpText"). */
56
+ message?: string;
57
+ /** Called after a successful verify (the dialog is closed by then). */
58
+ onVerified?: (result: OtpVerifiedResult) => void;
59
+ /** Called after Cancel, ✕, Escape or a backdrop click. */
60
+ onCancel?: () => void;
61
+ }
62
+
63
+ /** What the dialog shows. */
64
+ export interface OtpModalState {
65
+ isOpen: boolean;
66
+ title: string;
67
+ message: string;
68
+ userId: string;
69
+ }
70
+
71
+ /** The reply fields of the send / verify services. */
72
+ interface OtpReply {
73
+ message?: string;
74
+ oid?: string;
75
+ uid?: string;
76
+ }
77
+
78
+ type OtpCallbacks = Pick<OtpOpenOptions, "onVerified" | "onCancel">;
79
+
80
+ const CLOSED_OTP_MODAL: OtpModalState = {
81
+ isOpen: false,
82
+ title: ConstValue.EMPTY,
83
+ message: ConstValue.EMPTY,
84
+ userId: ConstValue.EMPTY,
85
+ };
86
+
87
+ /** The dialog: open, title and user id. */
88
+ export const otpModalSignal = signal<OtpModalState>(CLOSED_OTP_MODAL);
89
+
90
+ /** oid + uid of the sent code; null = no code sent yet. */
91
+ export const otpSessionSignal = signal<OtpSession | null>(null);
92
+
93
+ /** true while the send call runs. */
94
+ export const otpIsSendingSignal = signal(false);
95
+
96
+ /** true while the verify call runs. */
97
+ export const otpIsVerifyingSignal = signal(false);
98
+
99
+ /** Seconds left before "Resend code" works again (0 = now). */
100
+ export const otpResendSecondsSignal = signal(0);
101
+
102
+ let otpCallbacks: OtpCallbacks = {};
103
+
104
+ let resendTimer: ReturnType<typeof setInterval> | null = null;
105
+
106
+ /** config.http.otp, or an error when it is not set. */
107
+ export function readOtpConfig(): OtpConfig {
108
+ const config = readAppConfig();
109
+ const otpConfig = config?.http?.otp;
110
+ if (!otpConfig) {
111
+ throw new Error(OTP_CONFIG_MISSING);
112
+ }
113
+ return otpConfig;
114
+ }
115
+
116
+ /** Number of characters of the code: config.http.otp.length, default 6. */
117
+ export function readOtpLength(): number {
118
+ const config = readAppConfig();
119
+ return config?.http?.otp?.length ?? DEFAULT_OTP_LENGTH;
120
+ }
121
+
122
+ /** true for a plain object. */
123
+ function isRecord(value: unknown): value is Record<string, unknown> {
124
+ return typeof value === "object" && value !== null && !Array.isArray(value);
125
+ }
126
+
127
+ /** The reply fields from { data: { message, oid, uid } } or { message, oid, uid }. */
128
+ function readOtpReply(reply: unknown): OtpReply {
129
+ if (!isRecord(reply)) {
130
+ return {};
131
+ }
132
+ const source = isRecord(reply.data) ? reply.data : reply;
133
+ return source as OtpReply;
134
+ }
135
+
136
+ /** 125 -> "2:05". */
137
+ export function formatOtpCountdown(seconds: number): string {
138
+ const minutes = Math.floor(seconds / 60);
139
+ const rest = seconds % 60;
140
+ const restText = String(rest);
141
+ const paddedRest = restText.padStart(2, "0");
142
+ return `${minutes}:${paddedRest}`;
143
+ }
144
+
145
+ /** Stops the resend countdown (0 = resend works). */
146
+ export function stopOtpResendCountdown(): void {
147
+ if (resendTimer) {
148
+ clearInterval(resendTimer);
149
+ resendTimer = null;
150
+ }
151
+ otpResendSecondsSignal.value = 0;
152
+ }
153
+
154
+ /** One second of the resend countdown. */
155
+ function tickOtpResendCountdown(): void {
156
+ const nextSeconds = otpResendSecondsSignal.value - 1;
157
+ if (nextSeconds <= 0) {
158
+ stopOtpResendCountdown();
159
+ return;
160
+ }
161
+ otpResendSecondsSignal.value = nextSeconds;
162
+ }
163
+
164
+ /** Starts the resend countdown (one timer for the whole page). */
165
+ function startOtpResendCountdown(seconds: number): void {
166
+ stopOtpResendCountdown();
167
+ if (seconds <= 0) {
168
+ return;
169
+ }
170
+ otpResendSecondsSignal.value = seconds;
171
+ resendTimer = setInterval(tickOtpResendCountdown, 1000);
172
+ }
173
+
174
+ /** The backend message, else the translated fallback. */
175
+ function readReplyMessage(otpReply: OtpReply, fallbackKey: string): string {
176
+ const fallback = translate(fallbackKey);
177
+ return otpReply.message || fallback;
178
+ }
179
+
180
+ /** Shows the backend error of a failed call, else the translated fallback. */
181
+ function showOtpError(error: unknown, fallbackKey: string): void {
182
+ const fallback = translate(fallbackKey);
183
+ const message = readErrorMessage(error, fallback);
184
+ ShowToast(message, "error");
185
+ }
186
+
187
+ /** POST sendUrl { userid }: keeps oid + uid and starts the resend countdown. Returns true when sent. */
188
+ export async function otpSendCall(): Promise<boolean> {
189
+ const userId = otpModalSignal.value.userId;
190
+ if (otpIsSendingSignal.value || userId.length === 0) {
191
+ return false;
192
+ }
193
+ otpIsSendingSignal.value = true;
194
+ try {
195
+ const otpConfig = readOtpConfig();
196
+ const body = { userid: userId };
197
+ const reply = await AppHttp.Post(otpConfig.sendUrl, body);
198
+ const isStillOpen = otpModalSignal.value.isOpen && otpModalSignal.value.userId === userId;
199
+ if (!isStillOpen) {
200
+ return false;
201
+ }
202
+ const otpReply = readOtpReply(reply);
203
+ otpSessionSignal.value = { oid: otpReply.oid ?? ConstValue.EMPTY, uid: otpReply.uid ?? ConstValue.EMPTY };
204
+ const message = readReplyMessage(otpReply, "ui.otpSent");
205
+ ShowToast(message, "success");
206
+ const resendSeconds = otpConfig.resendSeconds ?? DEFAULT_OTP_RESEND_SECONDS;
207
+ startOtpResendCountdown(resendSeconds);
208
+ return true;
209
+ } catch (error: unknown) {
210
+ showOtpError(error, "ui.otpSendFailed");
211
+ return false;
212
+ } finally {
213
+ otpIsSendingSignal.value = false;
214
+ }
215
+ }
216
+
217
+ /** "Resend code" button: sends a new code once the countdown is over. */
218
+ export function handleOtpResend(): void {
219
+ if (otpResendSecondsSignal.value > 0) {
220
+ return;
221
+ }
222
+ void otpSendCall();
223
+ }
224
+
225
+ /** POST verifyUrl { otp, oid, uid }: closes the dialog and calls onVerified. For form.handleSubmit. */
226
+ export async function handleOtpVerify(values: OtpFormType): Promise<void> {
227
+ const session = otpSessionSignal.value;
228
+ if (otpIsVerifyingSignal.value) {
229
+ return;
230
+ }
231
+ if (!session) {
232
+ const message = translate("ui.otpSessionMissing");
233
+ ShowToast(message, "error");
234
+ return;
235
+ }
236
+ otpIsVerifyingSignal.value = true;
237
+ try {
238
+ const otpConfig = readOtpConfig();
239
+ const body = { otp: values.otp, oid: session.oid, uid: session.uid };
240
+ const reply = await AppHttp.Post(otpConfig.verifyUrl, body);
241
+ const otpReply = readOtpReply(reply);
242
+ const message = readReplyMessage(otpReply, "ui.otpVerified");
243
+ ShowToast(message, "success");
244
+ const result: OtpVerifiedResult = {
245
+ oid: otpReply.oid || session.oid,
246
+ uid: otpReply.uid || session.uid,
247
+ otp: values.otp,
248
+ };
249
+ const onVerified = otpCallbacks.onVerified;
250
+ closeOtpModal();
251
+ onVerified?.(result);
252
+ } catch (error: unknown) {
253
+ showOtpError(error, "ui.otpInvalid");
254
+ } finally {
255
+ otpIsVerifyingSignal.value = false;
256
+ }
257
+ }
258
+
259
+ /** Opens the dialog for a user id and sends the code. */
260
+ export function openOtpModal(options: OtpOpenOptions): void {
261
+ stopOtpResendCountdown();
262
+ otpCallbacks = { onVerified: options.onVerified, onCancel: options.onCancel };
263
+ otpSessionSignal.value = null;
264
+ const title = options.title ?? translate("ui.otpTitle");
265
+ const message = options.message ?? translate("ui.otpText");
266
+ otpModalSignal.value = { isOpen: true, title: title, message: message, userId: options.userId };
267
+ void otpSendCall();
268
+ }
269
+
270
+ /** Closes the dialog without calling onCancel (also used after a successful verify). */
271
+ export function closeOtpModal(): void {
272
+ stopOtpResendCountdown();
273
+ otpCallbacks = {};
274
+ otpSessionSignal.value = null;
275
+ otpModalSignal.value = CLOSED_OTP_MODAL;
276
+ }
277
+
278
+ /** Cancel, ✕, Escape or a backdrop click: closes the dialog and calls onCancel. */
279
+ export function cancelOtpModal(): void {
280
+ const onCancel = otpCallbacks.onCancel;
281
+ closeOtpModal();
282
+ onCancel?.();
283
+ }
@@ -10,6 +10,8 @@ export interface FieldWrapperProps {
10
10
  errorText?: string;
11
11
  hint?: string;
12
12
  className?: string;
13
+ /** Keep the label for screen readers only (not shown). Default false. */
14
+ isLabelHidden?: boolean;
13
15
  children?: ReactNode;
14
16
  }
15
17
 
@@ -19,16 +21,17 @@ export function readMessageId(inputId: string): string {
19
21
  }
20
22
 
21
23
  export function FieldWrapper(props: FieldWrapperProps) {
22
- const { inputId, label, errorText, hint, className, children } = props;
24
+ const { inputId, label, errorText, hint, className, isLabelHidden = false, children } = props;
23
25
  const messageId = readMessageId(inputId);
24
26
  const messageText = errorText ?? hint;
25
27
  const messageClassName = errorText ? "label text-error" : "label";
26
28
  const classList = ["fieldset", className];
27
29
  const wrapperClassName = joinClassNames(classList);
30
+ const labelClassName = isLabelHidden ? "sr-only" : "fieldset-legend";
28
31
 
29
32
  return (
30
33
  <fieldset className={wrapperClassName}>
31
- <label className="fieldset-legend" htmlFor={inputId}>
34
+ <label className={labelClassName} htmlFor={inputId}>
32
35
  {label}
33
36
  </label>
34
37
  {children}
@@ -18,6 +18,8 @@ import type { TypeFieldProps } from "./field-props.ts";
18
18
  export interface TypeOtpProps<TFieldValues extends FieldValues> extends TypeFieldProps<TFieldValues> {
19
19
  /** Number of characters. Default 6. */
20
20
  length?: number;
21
+ /** Keep the label for screen readers only (not shown). Default false. */
22
+ isLabelHidden?: boolean;
21
23
  }
22
24
 
23
25
  /** Builds the boxes that show one character each. The box at the cursor is highlighted. */
@@ -43,7 +45,7 @@ function buildOtpBoxes(value: string, length: number, hasError: boolean): ReactE
43
45
  }
44
46
 
45
47
  export function TypeOtp<TFieldValues extends FieldValues>(props: TypeOtpProps<TFieldValues>) {
46
- const { control, name, label, rules, error, hint, disabled, className, length = 6 } = props;
48
+ const { control, name, label, rules, error, hint, disabled, className, length = 6, isLabelHidden = false } = props;
47
49
  const { t } = useUi();
48
50
  const inputId = useId();
49
51
  const controllerOptions = { control: control, name: name, rules: rules, disabled: disabled };
@@ -57,7 +59,14 @@ export function TypeOtp<TFieldValues extends FieldValues>(props: TypeOtpProps<TF
57
59
  const boxes = buildOtpBoxes(value, length, hasError);
58
60
 
59
61
  return (
60
- <FieldWrapper inputId={inputId} label={label} errorText={errorText} hint={hint} className={className}>
62
+ <FieldWrapper
63
+ inputId={inputId}
64
+ label={label}
65
+ errorText={errorText}
66
+ hint={hint}
67
+ className={className}
68
+ isLabelHidden={isLabelHidden}
69
+ >
61
70
  <div className="relative flex w-fit gap-2" dir="ltr">
62
71
  <input
63
72
  id={inputId}