@salesforce/webapp-template-app-react-sample-b2x-experimental 1.79.2 → 1.80.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.
Files changed (44) hide show
  1. package/dist/CHANGELOG.md +8 -0
  2. package/dist/force-app/main/default/classes/WebAppAuthUtils.cls +68 -0
  3. package/dist/force-app/main/default/classes/WebAppAuthUtils.cls-meta.xml +5 -0
  4. package/dist/force-app/main/default/classes/WebAppChangePassword.cls +77 -0
  5. package/dist/force-app/main/default/classes/WebAppChangePassword.cls-meta.xml +5 -0
  6. package/dist/force-app/main/default/classes/WebAppForgotPassword.cls +71 -0
  7. package/dist/force-app/main/default/classes/WebAppForgotPassword.cls-meta.xml +5 -0
  8. package/dist/force-app/main/default/classes/WebAppLogin.cls +105 -0
  9. package/dist/force-app/main/default/classes/WebAppLogin.cls-meta.xml +5 -0
  10. package/dist/force-app/main/default/classes/WebAppRegistration.cls +162 -0
  11. package/dist/force-app/main/default/classes/WebAppRegistration.cls-meta.xml +5 -0
  12. package/dist/force-app/main/default/webapplications/appreactsampleb2x/package.json +3 -3
  13. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/api/leadApi.ts +15 -6
  14. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/app.tsx +4 -1
  15. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/appLayout.tsx +155 -88
  16. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/api/userProfileApi.ts +81 -0
  17. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/authHelpers.ts +73 -0
  18. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/authenticationConfig.ts +61 -0
  19. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/context/AuthContext.tsx +95 -0
  20. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/footers/footer-link.tsx +36 -0
  21. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/forms/auth-form.tsx +81 -0
  22. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/forms/submit-button.tsx +49 -0
  23. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/hooks/form.tsx +120 -0
  24. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/hooks/useCountdownTimer.ts +266 -0
  25. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/hooks/useRetryWithBackoff.ts +109 -0
  26. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/layout/card-skeleton.tsx +38 -0
  27. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/layout/centered-page-layout.tsx +87 -0
  28. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/layouts/AuthAppLayout.tsx +12 -0
  29. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/layouts/authenticationRouteLayout.tsx +21 -0
  30. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/layouts/privateRouteLayout.tsx +36 -0
  31. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/pages/ChangePassword.tsx +107 -0
  32. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/pages/ForgotPassword.tsx +73 -0
  33. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/pages/Login.tsx +97 -0
  34. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/pages/Profile.tsx +139 -0
  35. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/pages/Register.tsx +133 -0
  36. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/pages/ResetPassword.tsx +107 -0
  37. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/sessionTimeout/SessionTimeoutValidator.tsx +616 -0
  38. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/sessionTimeout/sessionTimeService.ts +161 -0
  39. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/sessionTimeout/sessionTimeoutConfig.ts +77 -0
  40. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/features/authentication/utils/helpers.ts +121 -0
  41. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/pages/Contact.tsx +201 -114
  42. package/dist/force-app/main/default/webapplications/appreactsampleb2x/src/routes.tsx +67 -13
  43. package/dist/package.json +1 -1
  44. package/package.json +1 -1
@@ -0,0 +1,81 @@
1
+ import { FieldGroup } from "../../../components/ui/field";
2
+ import { StatusAlert } from "../../../components/alerts/status-alert";
3
+ import { FooterLink } from "../footers/footer-link";
4
+ import { SubmitButton } from "./submit-button";
5
+ import { CardLayout } from "../../../components/layouts/card-layout";
6
+ import { useFormContext } from "../hooks/form";
7
+ import { useId } from "react";
8
+
9
+ /**
10
+ * [Dev Note] A wrapper component that enforces consistent layout (Card) and error/success alert positioning
11
+ * for all authentication forms.
12
+ */
13
+ interface AuthFormProps extends Omit<React.ComponentProps<"form">, "onSubmit"> {
14
+ title: string;
15
+ description: string;
16
+ error?: React.ReactNode;
17
+ success?: React.ReactNode;
18
+ submit: {
19
+ text: string;
20
+ loadingText?: string;
21
+ disabled?: boolean;
22
+ };
23
+ footer?: {
24
+ text?: string;
25
+ link: string;
26
+ linkText: string;
27
+ };
28
+ }
29
+
30
+ /**
31
+ * [Dev Note] Standardized Authentication Layout:
32
+ * Wraps the specific logic of Login/Register forms with a consistent visual frame (Card),
33
+ * title, and error alert placement. Extends form element props for flexibility.
34
+ * This ensures all auth-related pages look and behave similarly.
35
+ */
36
+ export function AuthForm({
37
+ id: providedId,
38
+ title,
39
+ description,
40
+ error,
41
+ success,
42
+ children,
43
+ submit,
44
+ footer,
45
+ ...props
46
+ }: AuthFormProps) {
47
+ const form = useFormContext();
48
+ const generatedId = useId();
49
+ const id = providedId ?? generatedId;
50
+
51
+ return (
52
+ <CardLayout title={title} description={description}>
53
+ <div className="space-y-6">
54
+ {/* [Dev Note] Global form error alert (e.g. "Invalid Credentials") */}
55
+ {error && <StatusAlert variant="error">{error}</StatusAlert>}
56
+ {success && <StatusAlert variant="success">{success}</StatusAlert>}
57
+
58
+ <form
59
+ id={id}
60
+ onSubmit={(e) => {
61
+ e.preventDefault();
62
+ e.stopPropagation();
63
+ form.handleSubmit();
64
+ }}
65
+ {...props}
66
+ >
67
+ <FieldGroup>{children}</FieldGroup>
68
+ <SubmitButton
69
+ form={id}
70
+ label={submit.text}
71
+ loadingLabel={submit.loadingText}
72
+ disabled={submit.disabled}
73
+ className="mt-6"
74
+ />
75
+ </form>
76
+ {/* [Dev Note] Navigation links (e.g. "Forgot Password?") */}
77
+ {footer && <FooterLink text={footer.text} to={footer.link} linkText={footer.linkText} />}
78
+ </div>
79
+ </CardLayout>
80
+ );
81
+ }
@@ -0,0 +1,49 @@
1
+ import { Button } from "../../../components/ui/button";
2
+ import { Spinner } from "../../../components/ui/spinner";
3
+ import { cn } from "../../../lib/utils";
4
+ import { useFormContext } from "../hooks/form";
5
+
6
+ interface SubmitButtonProps extends Omit<React.ComponentProps<typeof Button>, "type"> {
7
+ /** Button text when not submitting */
8
+ label: string;
9
+ /** Button text while submitting */
10
+ loadingLabel?: string;
11
+ /** Form id to associate with (for buttons outside form element) */
12
+ form?: string;
13
+ }
14
+
15
+ const isSubmittingSelector = (state: { isSubmitting: boolean }) => state.isSubmitting;
16
+
17
+ /**
18
+ * Submit button that subscribes to form submission state.
19
+ * UX Best Practice:
20
+ * 1. Disables interaction immediately upon click (via isLoading) to prevent
21
+ * accidental double-submissions.
22
+ * 2. Provides immediate visual feedback (Spinner).
23
+ */
24
+ export function SubmitButton({
25
+ label,
26
+ loadingLabel = "Submitting…",
27
+ className,
28
+ form: formId,
29
+ disabled,
30
+ ...props
31
+ }: SubmitButtonProps) {
32
+ const form = useFormContext();
33
+ return (
34
+ <form.Subscribe selector={isSubmittingSelector}>
35
+ {(isSubmitting: boolean) => (
36
+ <Button
37
+ type="submit"
38
+ form={formId}
39
+ className={cn("w-full", className)}
40
+ disabled={isSubmitting || disabled}
41
+ {...props}
42
+ >
43
+ {isSubmitting && <Spinner className="mr-2" aria-hidden="true" />}
44
+ {isSubmitting ? loadingLabel : label}
45
+ </Button>
46
+ )}
47
+ </form.Subscribe>
48
+ );
49
+ }
@@ -0,0 +1,120 @@
1
+ import { useId } from "react";
2
+ import { createFormHookContexts, createFormHook } from "@tanstack/react-form";
3
+ import {
4
+ Field,
5
+ FieldDescription,
6
+ FieldError,
7
+ FieldLabel,
8
+ } from "../../../components/ui/field";
9
+ import { Input } from "../../../components/ui/input";
10
+ import { cn } from "../../../lib/utils";
11
+ import { AUTH_PLACEHOLDERS } from "../authenticationConfig";
12
+
13
+ // Create form hook contexts
14
+ export const { fieldContext, formContext, useFieldContext, useFormContext } =
15
+ createFormHookContexts();
16
+
17
+ // ============================================================================
18
+ // Field Components
19
+ // ============================================================================
20
+
21
+ interface TextFieldProps extends Omit<
22
+ React.ComponentProps<typeof Input>,
23
+ "name" | "value" | "onBlur" | "onChange" | "aria-invalid"
24
+ > {
25
+ label: string;
26
+ labelAction?: React.ReactNode;
27
+ description?: React.ReactNode;
28
+ }
29
+
30
+ function TextField({
31
+ label,
32
+ id: providedId,
33
+ labelAction,
34
+ description,
35
+ type = "text",
36
+ ...props
37
+ }: TextFieldProps) {
38
+ const field = useFieldContext<string>();
39
+ const generatedId = useId();
40
+ const id = providedId ?? generatedId;
41
+ const descriptionId = `${id}-description`;
42
+ const errorId = `${id}-error`;
43
+ const isInvalid = field.state.meta.isTouched && field.state.meta.errors.length > 0;
44
+
45
+ // Deduplicate errors by message
46
+ const errors = field.state.meta.errors;
47
+ const uniqueErrors = [...new Map(errors.map((item: any) => [item["message"], item])).values()];
48
+
49
+ return (
50
+ <Field data-invalid={isInvalid}>
51
+ <div className="flex items-center">
52
+ <FieldLabel htmlFor={id}>{label}</FieldLabel>
53
+ {labelAction && <div className="ml-auto">{labelAction}</div>}
54
+ </div>
55
+ {description && <FieldDescription id={descriptionId}>{description}</FieldDescription>}
56
+ <Input
57
+ id={id}
58
+ name={field.name as string}
59
+ type={type}
60
+ value={field.state.value ?? ""}
61
+ onBlur={field.handleBlur}
62
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => field.handleChange(e.target.value)}
63
+ aria-invalid={isInvalid}
64
+ aria-describedby={cn(description && descriptionId, isInvalid && errorId)}
65
+ {...props}
66
+ />
67
+ {isInvalid && uniqueErrors.length > 0 && <FieldError errors={uniqueErrors} />}
68
+ </Field>
69
+ );
70
+ }
71
+
72
+ /** Password field with preset type and autocomplete */
73
+ function PasswordField({
74
+ label,
75
+ autoComplete = "current-password",
76
+ placeholder = AUTH_PLACEHOLDERS.PASSWORD,
77
+ ...props
78
+ }: Omit<TextFieldProps, "type">) {
79
+ return (
80
+ <TextField
81
+ label={label}
82
+ type="password"
83
+ autoComplete={autoComplete}
84
+ placeholder={placeholder}
85
+ {...props}
86
+ />
87
+ );
88
+ }
89
+
90
+ /** Email field with preset type and autocomplete */
91
+ function EmailField({
92
+ label,
93
+ placeholder = AUTH_PLACEHOLDERS.EMAIL,
94
+ ...props
95
+ }: Omit<TextFieldProps, "type">) {
96
+ return (
97
+ <TextField
98
+ label={label}
99
+ type="email"
100
+ autoComplete="username"
101
+ placeholder={placeholder}
102
+ {...props}
103
+ />
104
+ );
105
+ }
106
+
107
+ // ============================================================================
108
+ // Create Form Hook
109
+ // ============================================================================
110
+
111
+ export const { useAppForm } = createFormHook({
112
+ fieldContext,
113
+ formContext,
114
+ fieldComponents: {
115
+ TextField,
116
+ PasswordField,
117
+ EmailField,
118
+ },
119
+ formComponents: {},
120
+ });
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Custom hook for countdown timer with accessibility features
3
+ */
4
+
5
+ import { useState, useEffect, useRef, useCallback } from "react";
6
+
7
+ /**
8
+ * Accessibility configuration for countdown timer
9
+ */
10
+ export interface CountdownTimerA11yConfig {
11
+ /** Announce time remaining at these specific second marks */
12
+ ANNOUNCE_AT_SECONDS: readonly number[];
13
+ /** Announce every N seconds (after initial period) */
14
+ ANNOUNCE_INTERVAL_SECONDS: number;
15
+ /** Minimum elapsed time before starting interval announcements */
16
+ MIN_ELAPSED_FOR_INTERVAL: number;
17
+ }
18
+
19
+ /**
20
+ * Return value from useCountdownTimer hook
21
+ */
22
+ export interface CountdownTimerResult {
23
+ /** Current time remaining in seconds */
24
+ displayTime: number;
25
+ /** Formatted time string (MM:SS) */
26
+ formattedTime: string;
27
+ /** ISO 8601 duration string (e.g., PT2M15S) */
28
+ isoTime: string;
29
+ /** Accessibility announcement text for screen readers */
30
+ accessibilityAnnouncement: string;
31
+ /** Start the countdown timer */
32
+ start: () => void;
33
+ /** Stop the countdown timer */
34
+ stop: () => void;
35
+ /** Reset the countdown timer to initial time */
36
+ reset: () => void;
37
+ }
38
+
39
+ /**
40
+ * Configuration for countdown timer hook
41
+ */
42
+ export interface CountdownTimerConfig {
43
+ /** Initial time in seconds */
44
+ initialTime: number;
45
+ /** Callback when countdown reaches 0 */
46
+ onExpire: () => void;
47
+ /** Optional accessibility configuration */
48
+ a11yConfig?: CountdownTimerA11yConfig;
49
+ }
50
+
51
+ /**
52
+ * Default accessibility configuration
53
+ */
54
+ const DEFAULT_A11Y_CONFIG: CountdownTimerA11yConfig = {
55
+ ANNOUNCE_AT_SECONDS: [5, 1],
56
+ ANNOUNCE_INTERVAL_SECONDS: 10,
57
+ MIN_ELAPSED_FOR_INTERVAL: 10,
58
+ };
59
+
60
+ /**
61
+ * Format time remaining as MM:SS string
62
+ * Uses Intl.NumberFormat for zero-padding and internationalization
63
+ *
64
+ * @param seconds - Total seconds remaining
65
+ * @returns Formatted time string (e.g., "05:23")
66
+ */
67
+ function formatTimeRemaining(seconds: number): string {
68
+ const minutes = Math.floor(seconds / 60);
69
+ const secs = seconds % 60;
70
+
71
+ // Use Intl.NumberFormat for zero-padding with internationalization
72
+ const formatter = new Intl.NumberFormat(navigator.language, {
73
+ minimumIntegerDigits: 2,
74
+ useGrouping: false,
75
+ });
76
+
77
+ return `${formatter.format(minutes)}:${formatter.format(secs)}`;
78
+ }
79
+
80
+ /**
81
+ * Format time remaining as ISO 8601 duration for ARIA
82
+ * Used in datetime attribute of <time> element
83
+ *
84
+ * @param seconds - Total seconds remaining
85
+ * @returns ISO 8601 duration string (e.g., "PT2M15S")
86
+ */
87
+ function formatISODuration(seconds: number): string {
88
+ const minutes = Math.floor(seconds / 60);
89
+ const secs = seconds % 60;
90
+ return `PT${minutes}M${secs}S`;
91
+ }
92
+
93
+ /**
94
+ * Format time remaining for screen reader announcement
95
+ * Uses Intl.DurationFormat if available, falls back to manual formatting
96
+ *
97
+ * @param seconds - Total seconds remaining
98
+ * @returns Formatted announcement text (e.g., "2 minutes 15 seconds")
99
+ */
100
+ function formatAccessibilityAnnouncement(seconds: number): string {
101
+ const minutes = Math.floor(seconds / 60);
102
+ const secs = seconds % 60;
103
+
104
+ // Try using Intl.DurationFormat (newer API, may not be available in all browsers)
105
+ if (typeof Intl !== "undefined" && "DurationFormat" in Intl) {
106
+ try {
107
+ // @ts-expect-error - DurationFormat is not yet in TypeScript lib
108
+ const formatter = new Intl.DurationFormat(navigator.language, { style: "long" });
109
+ return formatter.format({ minutes, seconds: secs });
110
+ } catch (e) {
111
+ // Fallback to manual formatting
112
+ }
113
+ }
114
+
115
+ // Manual fallback
116
+ const parts: string[] = [];
117
+ if (minutes > 0) {
118
+ parts.push(`${minutes} ${minutes === 1 ? "minute" : "minutes"}`);
119
+ }
120
+ if (secs > 0 || minutes === 0) {
121
+ parts.push(`${secs} ${secs === 1 ? "second" : "seconds"}`);
122
+ }
123
+ return parts.join(" ");
124
+ }
125
+
126
+ /**
127
+ * Determine if an accessibility announcement should be made at this time
128
+ *
129
+ * @param currentTime - Current countdown time in seconds
130
+ * @param initialTime - Initial countdown time in seconds
131
+ * @param config - Accessibility configuration
132
+ * @returns True if announcement should be made
133
+ */
134
+ function shouldAnnounce(
135
+ currentTime: number,
136
+ initialTime: number,
137
+ config: CountdownTimerA11yConfig,
138
+ ): boolean {
139
+ // Announce at specific second marks (5s, 1s)
140
+ if (config.ANNOUNCE_AT_SECONDS.includes(currentTime)) {
141
+ return true;
142
+ }
143
+
144
+ // Calculate elapsed time
145
+ const elapsed = initialTime - currentTime;
146
+
147
+ // Announce every N seconds after minimum elapsed time
148
+ if (elapsed >= config.MIN_ELAPSED_FOR_INTERVAL) {
149
+ return currentTime % config.ANNOUNCE_INTERVAL_SECONDS === 0;
150
+ }
151
+
152
+ return false;
153
+ }
154
+
155
+ /**
156
+ * Custom hook for countdown timer with accessibility
157
+ * Decrements from initial time to 0, provides formatted output for display and ARIA
158
+ *
159
+ * @param config - Timer configuration
160
+ * @returns Timer state and control functions
161
+ *
162
+ * @example
163
+ * const timer = useCountdownTimer({
164
+ * initialTime: 300, // 5 minutes
165
+ * onExpire: () => handleLogout()
166
+ * });
167
+ *
168
+ * timer.start(); // Begin countdown
169
+ *
170
+ * <time dateTime={timer.isoTime} role="timer">
171
+ * {timer.formattedTime}
172
+ * </time>
173
+ * <div role="status" aria-live="polite" className="sr-only">
174
+ * {timer.accessibilityAnnouncement}
175
+ * </div>
176
+ */
177
+ export function useCountdownTimer({
178
+ initialTime,
179
+ onExpire,
180
+ a11yConfig = DEFAULT_A11Y_CONFIG,
181
+ }: CountdownTimerConfig): CountdownTimerResult {
182
+ const [displayTime, setDisplayTime] = useState(initialTime);
183
+ const [accessibilityAnnouncement, setAccessibilityAnnouncement] = useState("");
184
+ const [isActive, setIsActive] = useState(false);
185
+
186
+ // Use refs to avoid stale closure issues
187
+ const initialTimeRef = useRef(initialTime);
188
+ const onExpireRef = useRef(onExpire);
189
+ const a11yConfigRef = useRef(a11yConfig);
190
+ const endTimeRef = useRef<number>(0);
191
+ const previousTimeRef = useRef<number>(initialTime);
192
+
193
+ // Update refs when props change
194
+ useEffect(() => {
195
+ initialTimeRef.current = initialTime;
196
+ }, [initialTime]);
197
+
198
+ useEffect(() => {
199
+ onExpireRef.current = onExpire;
200
+ }, [onExpire]);
201
+
202
+ useEffect(() => {
203
+ a11yConfigRef.current = a11yConfig;
204
+ }, [a11yConfig]);
205
+
206
+ // Countdown effect using Date.now() for accuracy
207
+ useEffect(() => {
208
+ if (!isActive) return;
209
+
210
+ // Set the target end time when timer starts
211
+ endTimeRef.current = Date.now() + initialTimeRef.current * 1000;
212
+ previousTimeRef.current = initialTimeRef.current;
213
+
214
+ const intervalId = setInterval(() => {
215
+ const now = Date.now();
216
+ const remainingMs = endTimeRef.current - now;
217
+ const newTime = Math.max(0, Math.ceil(remainingMs / 1000));
218
+
219
+ setDisplayTime(newTime);
220
+
221
+ // Check if we should make an accessibility announcement
222
+ // Only announce when the second value changes
223
+ if (
224
+ newTime !== previousTimeRef.current &&
225
+ shouldAnnounce(newTime, initialTimeRef.current, a11yConfigRef.current)
226
+ ) {
227
+ setAccessibilityAnnouncement(formatAccessibilityAnnouncement(newTime));
228
+ }
229
+ previousTimeRef.current = newTime;
230
+
231
+ // Check if countdown expired
232
+ if (newTime <= 0) {
233
+ clearInterval(intervalId);
234
+ setIsActive(false);
235
+ onExpireRef.current();
236
+ }
237
+ }, 100); // Check more frequently for smoother updates
238
+
239
+ return () => clearInterval(intervalId);
240
+ }, [isActive]);
241
+
242
+ // Control functions
243
+ const start = useCallback(() => {
244
+ setIsActive(true);
245
+ }, []);
246
+
247
+ const stop = useCallback(() => {
248
+ setIsActive(false);
249
+ }, []);
250
+
251
+ const reset = useCallback(() => {
252
+ setDisplayTime(initialTimeRef.current);
253
+ setIsActive(false);
254
+ setAccessibilityAnnouncement("");
255
+ }, []);
256
+
257
+ return {
258
+ displayTime,
259
+ formattedTime: formatTimeRemaining(displayTime),
260
+ isoTime: formatISODuration(displayTime),
261
+ accessibilityAnnouncement,
262
+ start,
263
+ stop,
264
+ reset,
265
+ };
266
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Custom hook for retry logic with exponential backoff
3
+ */
4
+
5
+ import { useState, useCallback } from "react";
6
+
7
+ export interface UseRetryWithBackoffOptions {
8
+ /** Initial delay in milliseconds */
9
+ initialDelay: number;
10
+ /** Maximum number of retry attempts */
11
+ maxAttempts: number;
12
+ /** Maximum delay in milliseconds */
13
+ maxDelay: number;
14
+ }
15
+
16
+ export interface UseRetryWithBackoffResult {
17
+ /** Current number of retry attempts */
18
+ retryAttempts: number;
19
+ /** Current retry delay in milliseconds */
20
+ currentRetryDelay: number;
21
+ /** Whether max retry attempts have been reached */
22
+ maxRetriesReached: boolean;
23
+ /** Schedule a retry with exponential backoff, returns timeout ID for cancellation */
24
+ scheduleRetry: (callback: () => void) => ReturnType<typeof setTimeout> | undefined;
25
+ /** Reset retry state after successful operation */
26
+ resetRetry: () => void;
27
+ }
28
+
29
+ /**
30
+ * Hook for managing retry logic with exponential backoff
31
+ *
32
+ * @param options - Configuration for retry behavior
33
+ * @returns Retry state and control functions
34
+ *
35
+ * @example
36
+ * const retry = useRetryWithBackoff({
37
+ * initialDelay: 2000,
38
+ * maxAttempts: 10,
39
+ * maxDelay: 1800000
40
+ * });
41
+ *
42
+ * async function fetchData() {
43
+ * try {
44
+ * const data = await apiCall();
45
+ * retry.resetRetry();
46
+ * return data;
47
+ * } catch (error) {
48
+ * if (retry.maxRetriesReached) {
49
+ * console.error('Max retries reached');
50
+ * return;
51
+ * }
52
+ * retry.scheduleRetry(() => fetchData());
53
+ * }
54
+ * }
55
+ */
56
+ export function useRetryWithBackoff(
57
+ options: UseRetryWithBackoffOptions,
58
+ ): UseRetryWithBackoffResult {
59
+ const { initialDelay, maxAttempts, maxDelay } = options;
60
+
61
+ const [retryAttempts, setRetryAttempts] = useState<number>(0);
62
+ const [currentRetryDelay, setCurrentRetryDelay] = useState<number>(initialDelay);
63
+
64
+ const maxRetriesReached = retryAttempts >= maxAttempts;
65
+
66
+ /**
67
+ * Reset retry state after successful operation
68
+ */
69
+ const resetRetry = useCallback(() => {
70
+ setRetryAttempts(0);
71
+ setCurrentRetryDelay(initialDelay);
72
+ }, [initialDelay]);
73
+
74
+ /**
75
+ * Schedule a retry with exponential backoff
76
+ * Returns the timeout ID which can be used to cancel the retry if needed
77
+ */
78
+ const scheduleRetry = useCallback(
79
+ (callback: () => void) => {
80
+ if (retryAttempts >= maxAttempts) {
81
+ console.error("[useRetryWithBackoff] Max retry attempts reached");
82
+ return undefined;
83
+ }
84
+
85
+ console.warn(
86
+ `[useRetryWithBackoff] Retry attempt ${retryAttempts + 1}/${maxAttempts} in ${currentRetryDelay}ms`,
87
+ );
88
+
89
+ const timeoutId = setTimeout(() => {
90
+ callback();
91
+ }, currentRetryDelay);
92
+
93
+ setRetryAttempts((prev) => prev + 1);
94
+ // Double the delay for next retry, capped at maxDelay
95
+ setCurrentRetryDelay((prev) => Math.min(prev * 2, maxDelay));
96
+
97
+ return timeoutId;
98
+ },
99
+ [retryAttempts, currentRetryDelay, maxAttempts, maxDelay],
100
+ );
101
+
102
+ return {
103
+ retryAttempts,
104
+ currentRetryDelay,
105
+ maxRetriesReached,
106
+ scheduleRetry,
107
+ resetRetry,
108
+ };
109
+ }
@@ -0,0 +1,38 @@
1
+ import { CenteredPageLayout } from "./centered-page-layout";
2
+ import { Card, CardContent, CardHeader } from "../../../components/ui/card";
3
+ import { Skeleton } from "../../../components/ui/skeleton";
4
+
5
+ interface CardSkeletonProps {
6
+ /**
7
+ * Maximum width of the content container.
8
+ * @default "sm"
9
+ */
10
+ contentMaxWidth?: "sm" | "md" | "lg";
11
+ /**
12
+ * Accessible label for screen readers.
13
+ * @default "Loading…"
14
+ */
15
+ loadingText?: string;
16
+ }
17
+
18
+ /**
19
+ * Full-page loading indicator with skeleton card placeholder.
20
+ */
21
+ export function CardSkeleton({ contentMaxWidth, loadingText = "Loading…" }: CardSkeletonProps) {
22
+ return (
23
+ <CenteredPageLayout contentMaxWidth={contentMaxWidth}>
24
+ <div role="status" aria-live="polite">
25
+ <Card className="w-full">
26
+ <CardHeader>
27
+ <Skeleton className="h-4 w-2/3" />
28
+ <Skeleton className="h-4 w-1/2" />
29
+ </CardHeader>
30
+ <CardContent>
31
+ <Skeleton className="aspect-video w-full" />
32
+ </CardContent>
33
+ </Card>
34
+ <span className="sr-only">{loadingText}</span>
35
+ </div>
36
+ </CenteredPageLayout>
37
+ );
38
+ }