@djangocfg/layouts 1.2.39 → 1.2.41

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.
@@ -1,333 +0,0 @@
1
- /**
2
- * ValidationErrorContext - Global Zod validation error tracking
3
- *
4
- * Automatically captures all Zod validation errors from API client
5
- * using browser CustomEvent API and provides centralized state management.
6
- *
7
- * Features:
8
- * - Automatic error capture via window.addEventListener
9
- * - Toast notifications for user feedback
10
- * - Error history with timestamps
11
- * - Configurable error limits
12
- * - React Context API for component access
13
- *
14
- * @example
15
- * ```tsx
16
- * import { useValidationErrors } from '@djangocfg/layouts';
17
- *
18
- * function MyComponent() {
19
- * const { errors, clearErrors, clearError } = useValidationErrors();
20
- *
21
- * return (
22
- * <div>
23
- * <h2>Recent Validation Errors ({errors.length})</h2>
24
- * {errors.map((error) => (
25
- * <div key={error.id}>
26
- * <strong>{error.operation}</strong>
27
- * <p>{error.timestamp.toLocaleString()}</p>
28
- * <button onClick={() => clearError(error.id)}>Clear</button>
29
- * </div>
30
- * ))}
31
- * </div>
32
- * );
33
- * }
34
- * ```
35
- */
36
-
37
- 'use client';
38
-
39
- import React, { createContext, useContext, useCallback, useEffect, useState, ReactNode } from 'react';
40
- import type { ZodError } from 'zod';
41
- import { toast } from '@djangocfg/ui';
42
- import { createValidationErrorToast } from './ValidationErrorToast';
43
-
44
- /**
45
- * Validation error detail from CustomEvent
46
- */
47
- export interface ValidationErrorDetail {
48
- /** Operation/function name that failed validation */
49
- operation: string;
50
- /** API endpoint path */
51
- path: string;
52
- /** HTTP method */
53
- method: string;
54
- /** Zod validation error */
55
- error: ZodError;
56
- /** Raw response data that failed validation */
57
- response: any;
58
- /** Timestamp of the error */
59
- timestamp: Date;
60
- }
61
-
62
- /**
63
- * Stored validation error with unique ID
64
- */
65
- export interface StoredValidationError extends ValidationErrorDetail {
66
- /** Unique identifier for this error instance */
67
- id: string;
68
- }
69
-
70
- /**
71
- * Configuration for ValidationErrorProvider
72
- */
73
- export interface ValidationErrorConfig {
74
- /**
75
- * Maximum number of errors to keep in history
76
- * @default 50
77
- */
78
- maxErrors?: number;
79
-
80
- /**
81
- * Enable toast notifications on validation errors
82
- * @default true
83
- */
84
- enableToast?: boolean;
85
-
86
- /**
87
- * Toast notification settings
88
- */
89
- toastSettings?: {
90
- /** Show operation name in toast */
91
- showOperation?: boolean;
92
- /** Show endpoint path in toast */
93
- showPath?: boolean;
94
- /** Show error count in toast */
95
- showErrorCount?: boolean;
96
- /** Toast duration in milliseconds (0 = no auto-dismiss) */
97
- duration?: number;
98
- };
99
-
100
- /**
101
- * Custom error handler (called before toast)
102
- * Return false to prevent default toast notification
103
- */
104
- onError?: (error: ValidationErrorDetail) => boolean | void;
105
- }
106
-
107
- /**
108
- * Context value
109
- */
110
- export interface ValidationErrorContextValue {
111
- /** Array of validation errors */
112
- errors: StoredValidationError[];
113
-
114
- /** Clear all errors */
115
- clearErrors: () => void;
116
-
117
- /** Clear specific error by ID */
118
- clearError: (id: string) => void;
119
-
120
- /** Get error count */
121
- errorCount: number;
122
-
123
- /** Get latest error */
124
- latestError: StoredValidationError | null;
125
-
126
- /** Configuration */
127
- config: Required<ValidationErrorConfig>;
128
- }
129
-
130
- const ValidationErrorContext = createContext<ValidationErrorContextValue | undefined>(undefined);
131
-
132
- /**
133
- * Default configuration
134
- */
135
- const defaultConfig: Required<ValidationErrorConfig> = {
136
- maxErrors: 50,
137
- enableToast: true,
138
- toastSettings: {
139
- showOperation: true,
140
- showPath: true,
141
- showErrorCount: true,
142
- duration: 8000, // 8 seconds
143
- },
144
- onError: () => true,
145
- };
146
-
147
- /**
148
- * Generate unique ID for error
149
- */
150
- let errorIdCounter = 0;
151
- function generateErrorId(): string {
152
- return `validation-error-${Date.now()}-${++errorIdCounter}`;
153
- }
154
-
155
- /**
156
- * Format Zod error issues for display
157
- */
158
- function formatZodIssues(error: ZodError): string {
159
- const issues = error.issues.slice(0, 3); // Show max 3 issues
160
- const formatted = issues.map((issue) => {
161
- const path = issue.path.join('.') || 'root';
162
- return `${path}: ${issue.message}`;
163
- });
164
-
165
- if (error.issues.length > 3) {
166
- formatted.push(`... and ${error.issues.length - 3} more`);
167
- }
168
-
169
- return formatted.join(', ');
170
- }
171
-
172
- export interface ValidationErrorProviderProps {
173
- children: ReactNode;
174
- config?: Partial<ValidationErrorConfig>;
175
- }
176
-
177
- /**
178
- * ValidationErrorProvider Component
179
- *
180
- * Wraps application and provides validation error tracking.
181
- * Automatically listens to 'zod-validation-error' CustomEvents
182
- * from the API client.
183
- */
184
- export function ValidationErrorProvider({ children, config: userConfig }: ValidationErrorProviderProps) {
185
- const [errors, setErrors] = useState<StoredValidationError[]>([]);
186
-
187
- // Merge user config with defaults
188
- const config: Required<ValidationErrorConfig> = {
189
- ...defaultConfig,
190
- ...userConfig,
191
- toastSettings: {
192
- ...defaultConfig.toastSettings,
193
- ...userConfig?.toastSettings,
194
- },
195
- };
196
-
197
- /**
198
- * Clear all errors
199
- */
200
- const clearErrors = useCallback(() => {
201
- setErrors([]);
202
- }, []);
203
-
204
- /**
205
- * Clear specific error
206
- */
207
- const clearError = useCallback((id: string) => {
208
- setErrors((prev) => prev.filter((error) => error.id !== id));
209
- }, []);
210
-
211
- /**
212
- * Handle validation error event
213
- */
214
- const handleValidationError = useCallback(
215
- (event: Event) => {
216
- if (!(event instanceof CustomEvent)) return;
217
-
218
- const detail = event.detail as ValidationErrorDetail;
219
-
220
- // Create stored error with ID
221
- const storedError: StoredValidationError = {
222
- ...detail,
223
- id: generateErrorId(),
224
- };
225
-
226
- // Add to errors array (limited by maxErrors)
227
- setErrors((prev) => {
228
- const updated = [storedError, ...prev];
229
- return updated.slice(0, config.maxErrors);
230
- });
231
-
232
- // Call custom error handler
233
- const shouldShowToast = config.onError?.(detail) !== false;
234
-
235
- // Show toast notification with copy button
236
- if (config.enableToast && shouldShowToast) {
237
- const { showOperation, showPath, showErrorCount } = config.toastSettings;
238
-
239
- // Create toast with custom copy action button
240
- const toastOptions = createValidationErrorToast(detail, {
241
- config: {
242
- showOperation,
243
- showPath,
244
- showErrorCount,
245
- maxIssuesInDescription: 3,
246
- titlePrefix: '❌ Validation Error',
247
- },
248
- duration: config.toastSettings.duration,
249
- onCopySuccess: () => {
250
- // Show success feedback when error details are copied
251
- toast({
252
- title: '✅ Copied!',
253
- description: 'Error details copied to clipboard',
254
- duration: 2000,
255
- });
256
- },
257
- onCopyError: (error) => {
258
- // Show error feedback if copy fails
259
- toast({
260
- title: '❌ Copy failed',
261
- description: 'Could not copy error details',
262
- variant: 'destructive',
263
- duration: 2000,
264
- });
265
- },
266
- });
267
-
268
- toast(toastOptions);
269
- }
270
- },
271
- [config]
272
- );
273
-
274
- /**
275
- * Setup event listener
276
- */
277
- useEffect(() => {
278
- // Only run in browser
279
- if (typeof window === 'undefined') return;
280
-
281
- window.addEventListener('zod-validation-error', handleValidationError);
282
-
283
- return () => {
284
- window.removeEventListener('zod-validation-error', handleValidationError);
285
- };
286
- }, [handleValidationError]);
287
-
288
- const value: ValidationErrorContextValue = {
289
- errors,
290
- clearErrors,
291
- clearError,
292
- errorCount: errors.length,
293
- latestError: errors[0] || null,
294
- config,
295
- };
296
-
297
- return (
298
- <ValidationErrorContext.Provider value={value}>
299
- {children}
300
- </ValidationErrorContext.Provider>
301
- );
302
- }
303
-
304
- /**
305
- * useValidationErrors Hook
306
- *
307
- * Access validation errors from any component
308
- *
309
- * @example
310
- * ```tsx
311
- * function ErrorPanel() {
312
- * const { errors, clearErrors } = useValidationErrors();
313
- *
314
- * if (errors.length === 0) return null;
315
- *
316
- * return (
317
- * <div>
318
- * <h3>Validation Errors ({errors.length})</h3>
319
- * <button onClick={clearErrors}>Clear All</button>
320
- * </div>
321
- * );
322
- * }
323
- * ```
324
- */
325
- export function useValidationErrors(): ValidationErrorContextValue {
326
- const context = useContext(ValidationErrorContext);
327
-
328
- if (context === undefined) {
329
- throw new Error('useValidationErrors must be used within ValidationErrorProvider');
330
- }
331
-
332
- return context;
333
- }
@@ -1,181 +0,0 @@
1
- /**
2
- * ValidationErrorToast Component
3
- *
4
- * Custom toast for validation errors with copy button
5
- * Formats Zod validation errors and provides one-click copy functionality
6
- */
7
-
8
- 'use client';
9
-
10
- import React from 'react';
11
- import { ToastAction } from '@djangocfg/ui';
12
- import type { ZodError } from 'zod';
13
- import { ValidationErrorButtons } from './ValidationErrorButtons';
14
-
15
- export interface ValidationErrorDetail {
16
- operation: string;
17
- path: string;
18
- method: string;
19
- error: ZodError;
20
- response: any;
21
- timestamp: Date;
22
- }
23
-
24
- export interface ValidationErrorToastConfig {
25
- /** Show operation name in title */
26
- showOperation?: boolean;
27
- /** Show API path in description */
28
- showPath?: boolean;
29
- /** Show error count in description */
30
- showErrorCount?: boolean;
31
- /** Maximum number of issues to show in description */
32
- maxIssuesInDescription?: number;
33
- /** Custom title prefix */
34
- titlePrefix?: string;
35
- }
36
-
37
- const defaultConfig: ValidationErrorToastConfig = {
38
- showOperation: true,
39
- showPath: true,
40
- showErrorCount: true,
41
- maxIssuesInDescription: 3,
42
- titlePrefix: '❌ Validation Error',
43
- };
44
-
45
- /**
46
- * Format Zod error issues for display in toast description
47
- */
48
- export function formatZodIssuesForToast(
49
- error: ZodError,
50
- maxIssues: number = 3
51
- ): string {
52
- const issues = error.issues.slice(0, maxIssues);
53
- const formatted = issues.map((issue) => {
54
- const path = issue.path.join('.') || 'root';
55
- return `${path}: ${issue.message}`;
56
- });
57
-
58
- if (error.issues.length > maxIssues) {
59
- formatted.push(`... and ${error.issues.length - maxIssues} more`);
60
- }
61
-
62
- return formatted.join(', ');
63
- }
64
-
65
- /**
66
- * Format full error details for copying to clipboard
67
- * Includes all error information in structured JSON format
68
- */
69
- export function formatErrorForClipboard(detail: ValidationErrorDetail): string {
70
- const errorData = {
71
- timestamp: detail.timestamp.toISOString(),
72
- operation: detail.operation,
73
- endpoint: {
74
- method: detail.method,
75
- path: detail.path,
76
- },
77
- validation_errors: detail.error.issues.map((issue) => ({
78
- path: issue.path.join('.') || 'root',
79
- message: issue.message,
80
- code: issue.code,
81
- ...(('expected' in issue) && { expected: issue.expected }),
82
- ...(('received' in issue) && { received: issue.received }),
83
- ...(('minimum' in issue) && { minimum: issue.minimum }),
84
- ...(('maximum' in issue) && { maximum: issue.maximum }),
85
- })),
86
- response: detail.response,
87
- total_errors: detail.error.issues.length,
88
- };
89
-
90
- return JSON.stringify(errorData, null, 2);
91
- }
92
-
93
- /**
94
- * Build toast title from validation error
95
- */
96
- export function buildToastTitle(
97
- detail: ValidationErrorDetail,
98
- config: ValidationErrorToastConfig = defaultConfig
99
- ): string {
100
- const titleParts: string[] = [config.titlePrefix || '❌ Validation Error'];
101
-
102
- if (config.showOperation) {
103
- titleParts.push(`in ${detail.operation}`);
104
- }
105
-
106
- return titleParts.join(' ');
107
- }
108
-
109
- /**
110
- * Build toast description from validation error
111
- */
112
- export function buildToastDescription(
113
- detail: ValidationErrorDetail,
114
- config: ValidationErrorToastConfig = defaultConfig
115
- ): string {
116
- const descriptionParts: string[] = [];
117
-
118
- // Add HTTP method and path
119
- if (config.showPath) {
120
- descriptionParts.push(`${detail.method} ${detail.path}`);
121
- }
122
-
123
- // Add error count
124
- if (config.showErrorCount) {
125
- const count = detail.error.issues.length;
126
- const plural = count === 1 ? 'error' : 'errors';
127
- descriptionParts.push(`${count} ${plural}`);
128
- }
129
-
130
- // Add formatted error messages
131
- descriptionParts.push(
132
- formatZodIssuesForToast(
133
- detail.error,
134
- config.maxIssuesInDescription
135
- )
136
- );
137
-
138
- return descriptionParts.join(' • ');
139
- }
140
-
141
- /**
142
- * Create complete toast options for validation error
143
- *
144
- * Usage:
145
- * ```typescript
146
- * const { toast } = useToast();
147
- *
148
- * const toastOptions = createValidationErrorToast(errorDetail, {
149
- * onCopySuccess: () => toast({ title: '✅ Copied!' }),
150
- * onCopyError: () => toast({ title: '❌ Copy failed', variant: 'destructive' }),
151
- * });
152
- *
153
- * toast(toastOptions);
154
- * ```
155
- */
156
- export function createValidationErrorToast(
157
- detail: ValidationErrorDetail,
158
- options?: {
159
- config?: Partial<ValidationErrorToastConfig>;
160
- duration?: number;
161
- onCopySuccess?: () => void;
162
- onCopyError?: (error: Error) => void;
163
- }
164
- ) {
165
- const config: ValidationErrorToastConfig = {
166
- ...defaultConfig,
167
- ...options?.config,
168
- };
169
-
170
- return {
171
- title: buildToastTitle(detail, config),
172
- description: (
173
- <div className="flex flex-col gap-2">
174
- <div>{buildToastDescription(detail, config)}</div>
175
- <ValidationErrorButtons detail={detail} />
176
- </div>
177
- ),
178
- variant: 'destructive' as const,
179
- duration: options?.duration,
180
- };
181
- }