@kumix/ui 0.1.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/hooks.js ADDED
@@ -0,0 +1,1409 @@
1
+ "use client";
2
+ import { n as useCopyToClipboard, t as useIsMobile } from "./use-is-mobile-Dln4-L1O.js";
3
+ import * as React$1 from "react";
4
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
5
+ import { META_THEME_COLORS, THEME_MODES } from "@kumix/utils";
6
+ import { useTheme } from "next-themes";
7
+ //#region src/hooks/use-body-classes.ts
8
+ /**
9
+ * Body class management hook for React components.
10
+ */
11
+ /**
12
+ * Adds classes to `document.body` while the component is mounted.
13
+ * Shared classes are reference-counted, so one component unmounting does not
14
+ * remove a class that another mounted component still owns.
15
+ *
16
+ * @param className - Space-separated string of CSS class names to apply to body
17
+ *
18
+ * @example
19
+ * ```tsx
20
+ * // Single class
21
+ * useBodyClasses('dark-theme');
22
+ *
23
+ * // Multiple classes
24
+ * useBodyClasses('modal-open overflow-hidden');
25
+ *
26
+ * // Conditional classes
27
+ * useBodyClasses(isModalOpen ? 'modal-open' : '');
28
+ * ```
29
+ */
30
+ const useBodyClasses = (className) => {
31
+ useEffect(() => {
32
+ if (!className.trim()) return;
33
+ const classList = className.split(/\s+/).filter(Boolean);
34
+ classList.forEach((cls) => {
35
+ const count = bodyClassCounts.get(cls) ?? 0;
36
+ bodyClassCounts.set(cls, count + 1);
37
+ if (count === 0) document.body.classList.add(cls);
38
+ });
39
+ return () => {
40
+ classList.forEach((cls) => {
41
+ const nextCount = (bodyClassCounts.get(cls) ?? 1) - 1;
42
+ if (nextCount <= 0) {
43
+ bodyClassCounts.delete(cls);
44
+ document.body.classList.remove(cls);
45
+ return;
46
+ }
47
+ bodyClassCounts.set(cls, nextCount);
48
+ });
49
+ };
50
+ }, [className]);
51
+ };
52
+ const bodyClassCounts = /* @__PURE__ */ new Map();
53
+ //#endregion
54
+ //#region src/hooks/use-file-upload.ts
55
+ /**
56
+ * File upload functionality hook for React components
57
+ * Provides comprehensive file upload capabilities with drag & drop support
58
+ * Includes validation, preview generation, and state management
59
+ */
60
+ const EMPTY_INITIAL_FILES = [];
61
+ /**
62
+ * Hook for comprehensive file upload functionality with drag & drop support
63
+ *
64
+ * Features:
65
+ * - Single and multiple file upload support
66
+ * - Drag and drop functionality
67
+ * - File validation (size, type, count)
68
+ * - Preview generation for images
69
+ * - Error handling and state management
70
+ * - Duplicate file detection
71
+ * - Memory cleanup for object URLs
72
+ *
73
+ * @param options - Configuration options for the file upload hook
74
+ * @returns Tuple containing current state and available actions
75
+ *
76
+ * @example
77
+ * ```tsx
78
+ * const [state, actions] = useFileUpload({
79
+ * maxFiles: 5,
80
+ * maxSize: 10 * 1024 * 1024, // 10MB
81
+ * accept: 'image/*',
82
+ * multiple: true,
83
+ * onFilesChange: (files) => console.log('Files changed:', files),
84
+ * onFilesAdded: (newFiles) => console.log('New files added:', newFiles)
85
+ * });
86
+ *
87
+ * return (
88
+ * <div
89
+ * onDragEnter={actions.handleDragEnter}
90
+ * onDragLeave={actions.handleDragLeave}
91
+ * onDragOver={actions.handleDragOver}
92
+ * onDrop={actions.handleDrop}
93
+ * >
94
+ * <input {...actions.getInputProps()} />
95
+ * <button onClick={actions.openFileDialog}>
96
+ * Upload Files
97
+ * </button>
98
+ * {state.files.map(file => (
99
+ * <div key={file.id}>
100
+ * {file.file.name}
101
+ * <button onClick={() => actions.removeFile(file.id)}>
102
+ * Remove
103
+ * </button>
104
+ * </div>
105
+ * ))}
106
+ * </div>
107
+ * );
108
+ * ```
109
+ */
110
+ const useFileUpload = (options = {}) => {
111
+ const { maxFiles = Number.POSITIVE_INFINITY, maxSize = Number.POSITIVE_INFINITY, accept = "*", multiple = false, initialFiles = EMPTY_INITIAL_FILES, onFilesChange, onFilesAdded, onError } = options;
112
+ /** Current state of the file upload component */
113
+ const [state, setState] = useState({
114
+ files: initialFiles.map((file) => ({
115
+ file,
116
+ id: file.id,
117
+ preview: file.url
118
+ })),
119
+ isDragging: false,
120
+ errors: []
121
+ });
122
+ /** Reference to the hidden file input element */
123
+ const inputRef = useRef(null);
124
+ const filesRef = useRef([]);
125
+ useEffect(() => {
126
+ filesRef.current = state.files;
127
+ }, [state.files]);
128
+ useEffect(() => {
129
+ setState((prev) => ({
130
+ ...prev,
131
+ files: initialFiles.map((file) => ({
132
+ file,
133
+ id: file.id,
134
+ preview: file.url
135
+ })),
136
+ errors: []
137
+ }));
138
+ }, [initialFiles]);
139
+ useEffect(() => {
140
+ return () => {
141
+ filesRef.current.forEach((file) => {
142
+ if (file.preview && file.file instanceof File && file.file.type.startsWith("image/")) URL.revokeObjectURL(file.preview);
143
+ });
144
+ };
145
+ }, []);
146
+ /**
147
+ * Validate a file against the configured constraints
148
+ *
149
+ * @param file - The file to validate (File object or FileMetadata)
150
+ * @returns Error message if validation fails, null if valid
151
+ */
152
+ const validateFile = useCallback((file) => {
153
+ if (file.size > maxSize) return `File "${file.name}" exceeds the maximum size of ${formatBytes(maxSize)}.`;
154
+ if (accept !== "*") {
155
+ const acceptedTypes = accept.split(",").map((type) => type.trim());
156
+ const fileType = file instanceof File ? file.type || "" : file.type;
157
+ const fileExtension = `.${file.name.split(".").pop()}`;
158
+ if (!acceptedTypes.some((type) => {
159
+ if (type.startsWith(".")) return fileExtension.toLowerCase() === type.toLowerCase();
160
+ if (type.endsWith("/*")) {
161
+ const baseType = type.split("/")[0];
162
+ return fileType.startsWith(`${baseType}/`);
163
+ }
164
+ return fileType === type;
165
+ })) return `File "${file.name}" is not an accepted file type.`;
166
+ }
167
+ return null;
168
+ }, [accept, maxSize]);
169
+ /**
170
+ * Create a preview URL for a file
171
+ *
172
+ * @param file - The file to create a preview for
173
+ * @returns Preview URL string or undefined
174
+ */
175
+ const createPreview = useCallback((file) => {
176
+ if (file instanceof File) {
177
+ if (file.type.startsWith("image/")) return URL.createObjectURL(file);
178
+ return;
179
+ }
180
+ return file.url;
181
+ }, []);
182
+ /**
183
+ * Generate a unique identifier for a file
184
+ *
185
+ * @param file - The file to generate an ID for
186
+ * @returns Unique identifier string
187
+ */
188
+ const generateUniqueId = useCallback((file) => {
189
+ if (file instanceof File) return `${file.name}-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
190
+ return file.id;
191
+ }, []);
192
+ /**
193
+ * Clear all files from the upload state
194
+ * Also cleans up object URLs to prevent memory leaks
195
+ */
196
+ const clearFiles = useCallback(() => {
197
+ setState((prev) => {
198
+ for (const file of prev.files) if (file.preview && file.file instanceof File && file.file.type.startsWith("image/")) URL.revokeObjectURL(file.preview);
199
+ if (inputRef.current) inputRef.current.value = "";
200
+ const newState = {
201
+ ...prev,
202
+ files: [],
203
+ errors: []
204
+ };
205
+ onFilesChange?.(newState.files);
206
+ return newState;
207
+ });
208
+ }, [onFilesChange]);
209
+ /**
210
+ * Add new files to the upload state
211
+ * Handles validation, duplicate detection, and state updates
212
+ *
213
+ * @param newFiles - FileList or array of File objects to add
214
+ */
215
+ const addFiles = useCallback((newFiles) => {
216
+ if (!newFiles || newFiles.length === 0) return;
217
+ const newFilesArray = Array.from(newFiles);
218
+ const errors = [];
219
+ const validFiles = [];
220
+ for (const file of newFilesArray) {
221
+ const error = validateFile(file);
222
+ if (error) errors.push(error);
223
+ else validFiles.push({
224
+ file,
225
+ id: generateUniqueId(file),
226
+ preview: createPreview(file)
227
+ });
228
+ }
229
+ setState((prev) => {
230
+ const baseFiles = multiple ? prev.files : [];
231
+ const dedupedFiles = multiple ? validFiles.filter((file) => !baseFiles.some((existingFile) => existingFile.file.name === file.file.name && existingFile.file.size === file.file.size)) : validFiles;
232
+ if (multiple && maxFiles !== Number.POSITIVE_INFINITY && baseFiles.length + dedupedFiles.length > maxFiles) {
233
+ const nextErrors = [`You can only upload a maximum of ${maxFiles} files.`];
234
+ onError?.(nextErrors);
235
+ return {
236
+ ...prev,
237
+ errors: nextErrors
238
+ };
239
+ }
240
+ if (!multiple) prev.files.forEach((file) => {
241
+ if (file.preview && file.file instanceof File && file.file.type.startsWith("image/")) URL.revokeObjectURL(file.preview);
242
+ });
243
+ const nextFiles = !multiple ? dedupedFiles : [...baseFiles, ...dedupedFiles];
244
+ if (dedupedFiles.length > 0) {
245
+ onFilesAdded?.(dedupedFiles);
246
+ onFilesChange?.(nextFiles);
247
+ }
248
+ if (errors.length > 0) onError?.(errors);
249
+ return {
250
+ ...prev,
251
+ files: nextFiles,
252
+ errors
253
+ };
254
+ });
255
+ if (inputRef.current) inputRef.current.value = "";
256
+ }, [
257
+ maxFiles,
258
+ multiple,
259
+ validateFile,
260
+ createPreview,
261
+ generateUniqueId,
262
+ onFilesChange,
263
+ onFilesAdded,
264
+ onError
265
+ ]);
266
+ /**
267
+ * Remove a specific file from the upload state
268
+ * Also cleans up object URLs to prevent memory leaks
269
+ *
270
+ * @param id - The unique identifier of the file to remove
271
+ */
272
+ const removeFile = useCallback((id) => {
273
+ setState((prev) => {
274
+ const fileToRemove = prev.files.find((file) => file.id === id);
275
+ if (fileToRemove?.preview && fileToRemove.file instanceof File && fileToRemove.file.type.startsWith("image/")) URL.revokeObjectURL(fileToRemove.preview);
276
+ const newFiles = prev.files.filter((file) => file.id !== id);
277
+ onFilesChange?.(newFiles);
278
+ return {
279
+ ...prev,
280
+ files: newFiles,
281
+ errors: []
282
+ };
283
+ });
284
+ }, [onFilesChange]);
285
+ /**
286
+ * Clear all error messages from the state
287
+ */
288
+ const clearErrors = useCallback(() => {
289
+ setState((prev) => ({
290
+ ...prev,
291
+ errors: []
292
+ }));
293
+ }, []);
294
+ /**
295
+ * Handle drag enter event for the drop zone
296
+ * Sets the dragging state to true
297
+ *
298
+ * @param e - The drag event
299
+ */
300
+ const handleDragEnter = useCallback((e) => {
301
+ e.preventDefault();
302
+ e.stopPropagation();
303
+ setState((prev) => ({
304
+ ...prev,
305
+ isDragging: true
306
+ }));
307
+ }, []);
308
+ /**
309
+ * Handle drag leave event for the drop zone
310
+ * Sets the dragging state to false when leaving the drop zone
311
+ *
312
+ * @param e - The drag event
313
+ */
314
+ const handleDragLeave = useCallback((e) => {
315
+ e.preventDefault();
316
+ e.stopPropagation();
317
+ if (e.currentTarget.contains(e.relatedTarget)) return;
318
+ setState((prev) => ({
319
+ ...prev,
320
+ isDragging: false
321
+ }));
322
+ }, []);
323
+ /**
324
+ * Handle drag over event for the drop zone
325
+ * Prevents default behavior to allow dropping
326
+ *
327
+ * @param e - The drag event
328
+ */
329
+ const handleDragOver = useCallback((e) => {
330
+ e.preventDefault();
331
+ e.stopPropagation();
332
+ }, []);
333
+ /**
334
+ * Handle drop event for the drop zone
335
+ * Processes dropped files and adds them to the upload state
336
+ *
337
+ * @param e - The drag event containing the dropped files
338
+ */
339
+ const handleDrop = useCallback((e) => {
340
+ e.preventDefault();
341
+ e.stopPropagation();
342
+ setState((prev) => ({
343
+ ...prev,
344
+ isDragging: false
345
+ }));
346
+ if (inputRef.current?.disabled) return;
347
+ if (e.dataTransfer.files && e.dataTransfer.files.length > 0) if (!multiple) {
348
+ const file = e.dataTransfer.files[0];
349
+ addFiles([file]);
350
+ } else addFiles(e.dataTransfer.files);
351
+ }, [addFiles, multiple]);
352
+ /**
353
+ * Handle file input change event
354
+ * Processes selected files from the file input
355
+ *
356
+ * @param e - The change event from the file input
357
+ */
358
+ const handleFileChange = useCallback((e) => {
359
+ if (e.target.files && e.target.files.length > 0) addFiles(e.target.files);
360
+ }, [addFiles]);
361
+ return [state, {
362
+ addFiles,
363
+ removeFile,
364
+ clearFiles,
365
+ clearErrors,
366
+ handleDragEnter,
367
+ handleDragLeave,
368
+ handleDragOver,
369
+ handleDrop,
370
+ handleFileChange,
371
+ openFileDialog: useCallback(() => {
372
+ if (inputRef.current) inputRef.current.click();
373
+ }, []),
374
+ getInputProps: useCallback((props = {}) => {
375
+ return {
376
+ ...props,
377
+ type: "file",
378
+ onChange: handleFileChange,
379
+ accept: props.accept || accept,
380
+ multiple: props.multiple !== void 0 ? props.multiple : multiple,
381
+ ref: inputRef
382
+ };
383
+ }, [
384
+ accept,
385
+ multiple,
386
+ handleFileChange
387
+ ])
388
+ }];
389
+ };
390
+ /**
391
+ * Helper function to format bytes to human-readable format
392
+ *
393
+ * @param bytes - The number of bytes to format
394
+ * @param decimals - Number of decimal places to show (default: 2)
395
+ * @returns Formatted string with appropriate unit (e.g., "1.5 MB")
396
+ *
397
+ * @example
398
+ * ```tsx
399
+ * formatBytes(1024); // "1 KB"
400
+ * formatBytes(1536, 1); // "1.5 KB"
401
+ * formatBytes(1048576); // "1 MB"
402
+ * ```
403
+ */
404
+ const formatBytes = (bytes, decimals = 2) => {
405
+ if (bytes === 0) return "0 Bytes";
406
+ const k = 1024;
407
+ const dm = decimals < 0 ? 0 : decimals;
408
+ const sizes = [
409
+ "Bytes",
410
+ "KB",
411
+ "MB",
412
+ "GB",
413
+ "TB",
414
+ "PB",
415
+ "EB",
416
+ "ZB",
417
+ "YB"
418
+ ];
419
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
420
+ return `${Number.parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
421
+ };
422
+ //#endregion
423
+ //#region src/hooks/use-hydrated.ts
424
+ /**
425
+ * Hydration state hook for React components
426
+ * Returns a boolean indicating whether the component is running on the client
427
+ * with SSR-safe behavior to prevent hydration mismatches.
428
+ *
429
+ * This hook leverages `useSyncExternalStore` to provide a stable value between
430
+ * server and client renders: `false` during SSR, `true` after client hydration.
431
+ * The external store does not emit updates because the hydration state is static
432
+ * for the lifetime of the component.
433
+ */
434
+ /**
435
+ * Hook that indicates whether code is executing on the client after hydration
436
+ *
437
+ * Features:
438
+ * - SSR-safe: returns `false` on the server to avoid hydration mismatches
439
+ * - Client-stable: returns `true` after hydration and remains stable
440
+ * - Minimal overhead: uses a no-op external store subscription
441
+ *
442
+ * @returns Boolean indicating hydration state (`true` on client, `false` on server)
443
+ *
444
+ * @example
445
+ * ```tsx
446
+ * // Conditionally render client-only components safely
447
+ * function ClientOnly() {
448
+ * const hydrated = useHydrated();
449
+ * if (!hydrated) return null;
450
+ * return <InteractiveChart />;
451
+ * }
452
+ * ```
453
+ *
454
+ * @since 1.0.0
455
+ */
456
+ function useHydrated() {
457
+ return useSyncExternalStore(subscribe, () => true, () => false);
458
+ }
459
+ /**
460
+ * External store subscription used by `useHydrated`
461
+ * No updates are dispatched because hydration state is static.
462
+ * Returns an unsubscribe function for API conformity.
463
+ */
464
+ function subscribe() {
465
+ return () => {};
466
+ }
467
+ //#endregion
468
+ //#region src/hooks/use-intersection-observer.ts
469
+ /**
470
+ * Intersection observer hook for React components
471
+ * Efficiently observes visibility of DOM elements using a shared IntersectionObserver instance.
472
+ * Ideal for lazy loading, infinite scrolling, and animating elements when they enter the viewport.
473
+ */
474
+ /**
475
+ * A shared intersection observer to manage multiple targets with a single observer instance.
476
+ * Optimized for high-density lists (like the patterns grid).
477
+ */
478
+ var SharedObserver = class {
479
+ observer = null;
480
+ callbacks = /* @__PURE__ */ new Map();
481
+ options;
482
+ constructor(options) {
483
+ this.options = options;
484
+ }
485
+ getObserver() {
486
+ if (!this.observer) this.observer = new IntersectionObserver((entries) => {
487
+ entries.forEach((entry) => {
488
+ const callback = this.callbacks.get(entry.target);
489
+ if (callback) callback(entry.isIntersecting);
490
+ });
491
+ }, this.options);
492
+ return this.observer;
493
+ }
494
+ observe(element, callback) {
495
+ this.callbacks.set(element, callback);
496
+ this.getObserver().observe(element);
497
+ }
498
+ unobserve(element) {
499
+ this.callbacks.delete(element);
500
+ this.observer?.unobserve(element);
501
+ }
502
+ get size() {
503
+ return this.callbacks.size;
504
+ }
505
+ disconnect() {
506
+ this.observer?.disconnect();
507
+ this.callbacks.clear();
508
+ this.observer = null;
509
+ }
510
+ };
511
+ const observers = /* @__PURE__ */ new Map();
512
+ const rootIds = /* @__PURE__ */ new WeakMap();
513
+ let rootId = 0;
514
+ function getRootKey(root) {
515
+ if (!root) return "null";
516
+ if (!rootIds.has(root)) rootIds.set(root, ++rootId);
517
+ return rootIds.get(root);
518
+ }
519
+ /**
520
+ * Get or create a shared `IntersectionObserver` instance based on the provided options.
521
+ *
522
+ * Using a shared observer reduces the number of underlying `IntersectionObserver`
523
+ * instances created by the browser, which is especially beneficial for pages
524
+ * with many observed elements.
525
+ *
526
+ * @param options - Intersection observer configuration (threshold, root, rootMargin)
527
+ * @returns A shared `SharedObserver` instance for the given options
528
+ */
529
+ function getSharedObserver(options) {
530
+ const threshold = Array.isArray(options.threshold) ? options.threshold.join(",") : options.threshold ?? 0;
531
+ const key = `${getRootKey(options.root)}|${options.rootMargin ?? "0px"}|${threshold}`;
532
+ if (!observers.has(key)) observers.set(key, new SharedObserver(options));
533
+ return {
534
+ key,
535
+ observer: observers.get(key)
536
+ };
537
+ }
538
+ /**
539
+ * React hook that tracks whether a DOM element is currently intersecting the viewport.
540
+ *
541
+ * Features:
542
+ * - Uses a shared `IntersectionObserver` instance for better performance.
543
+ * - Supports custom `threshold`, `root`, and `rootMargin` options.
544
+ * - Optional `freezeOnceVisible` flag to stop observing after first intersection.
545
+ *
546
+ * @param elementRef - React ref pointing to the DOM element to observe.
547
+ * @param options - Optional observer configuration and behavior flags.
548
+ * @param options.threshold - Intersection threshold(s) for triggering visibility changes.
549
+ * @param options.root - Scrollable ancestor element to use as the viewport (defaults to browser viewport).
550
+ * @param options.rootMargin - Margin around the root, expressed in CSS units (e.g. `"0px 0px -20% 0px"`).
551
+ * @param options.freezeOnceVisible - When `true`, stops observing after the element first becomes visible.
552
+ *
553
+ * @returns `true` when the element is intersecting based on the given options, otherwise `false`.
554
+ *
555
+ * @example
556
+ * ```tsx
557
+ * const ref = React.useRef<HTMLDivElement | null>(null);
558
+ * const isVisible = useIntersectionObserver(ref, {
559
+ * threshold: 0.2,
560
+ * rootMargin: "0px 0px -10% 0px",
561
+ * freezeOnceVisible: true,
562
+ * });
563
+ *
564
+ * return (
565
+ * <div ref={ref} className={isVisible ? "animate-in" : "opacity-0"}>
566
+ * I will animate when I enter the viewport.
567
+ * </div>
568
+ * );
569
+ * ```
570
+ */
571
+ function useIntersectionObserver(elementRef, { threshold = 0, root = null, rootMargin = "0%", freezeOnceVisible = false } = {}) {
572
+ const [isIntersecting, setIntersecting] = React$1.useState(false);
573
+ const frozen = React$1.useRef(false);
574
+ React$1.useEffect(() => {
575
+ const element = elementRef?.current;
576
+ if (!element || freezeOnceVisible && frozen.current) return;
577
+ if (typeof IntersectionObserver === "undefined") return;
578
+ const { key, observer } = getSharedObserver({
579
+ threshold,
580
+ root,
581
+ rootMargin
582
+ });
583
+ observer.observe(element, (intersecting) => {
584
+ setIntersecting(intersecting);
585
+ if (intersecting && freezeOnceVisible) {
586
+ frozen.current = true;
587
+ observer.unobserve(element);
588
+ }
589
+ });
590
+ return () => {
591
+ observer.unobserve(element);
592
+ if (observer.size === 0) {
593
+ observer.disconnect();
594
+ observers.delete(key);
595
+ }
596
+ };
597
+ }, [
598
+ elementRef,
599
+ threshold,
600
+ root,
601
+ rootMargin,
602
+ freezeOnceVisible
603
+ ]);
604
+ return isIntersecting;
605
+ }
606
+ //#endregion
607
+ //#region src/hooks/use-is-mac.ts
608
+ /**
609
+ * Platform detection hook for React components
610
+ * Determines whether the current user agent is running on a macOS device.
611
+ * Useful for rendering platform-specific keyboard shortcuts or UI variations.
612
+ */
613
+ /**
614
+ * React hook that returns whether the current browser reports a macOS platform.
615
+ * It prefers `navigator.userAgentData.platform` when available and falls back
616
+ * to `navigator.userAgent`.
617
+ *
618
+ * @returns `true` if the current platform is macOS, otherwise `false`.
619
+ *
620
+ * @example
621
+ * ```tsx
622
+ * const isMac = useIsMac();
623
+ *
624
+ * return (
625
+ * <kbd>
626
+ * {isMac ? "⌘" : "Ctrl"} + K
627
+ * </kbd>
628
+ * );
629
+ * ```
630
+ */
631
+ function useIsMac() {
632
+ const [isMac, setIsMac] = useState(false);
633
+ useEffect(() => {
634
+ const platform = navigator.userAgentData?.platform ?? navigator.userAgent ?? "";
635
+ setIsMac(platform.toUpperCase().includes("MAC"));
636
+ }, []);
637
+ return isMac;
638
+ }
639
+ //#endregion
640
+ //#region src/hooks/use-media-query.ts
641
+ /**
642
+ * Media query hook for responsive React components
643
+ * Provides real-time tracking of CSS media query matches
644
+ * with SSR-safe implementation and automatic cleanup
645
+ */
646
+ /**
647
+ * Helper function to safely check media query matches
648
+ * Prevents SSR hydration issues by checking for window availability
649
+ *
650
+ * @param query - CSS media query string to evaluate
651
+ * @returns Boolean indicating if the media query matches
652
+ */
653
+ const getMatches = (query) => {
654
+ if (typeof window !== "undefined") return window.matchMedia(query).matches;
655
+ return false;
656
+ };
657
+ /**
658
+ * Hook for tracking CSS media query matches in React components
659
+ *
660
+ * Features:
661
+ * - Real-time updates when media query state changes
662
+ * - SSR-safe implementation
663
+ * - Automatic event listener cleanup
664
+ * - Supports all standard CSS media queries
665
+ *
666
+ * @param query - CSS media query string (e.g., '(min-width: 768px)')
667
+ * @returns Boolean indicating whether the media query currently matches
668
+ *
669
+ * @example
670
+ * ```tsx
671
+ * // Basic responsive behavior
672
+ * const isMobile = useMediaQuery('(max-width: 768px)');
673
+ * const isTablet = useMediaQuery('(min-width: 769px) and (max-width: 1024px)');
674
+ * const isDesktop = useMediaQuery('(min-width: 1025px)');
675
+ *
676
+ * // Dark mode preference
677
+ * const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
678
+ *
679
+ * // Reduced motion preference
680
+ * const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');
681
+ *
682
+ * return (
683
+ * <div>
684
+ * {isMobile && <MobileLayout />}
685
+ * {isTablet && <TabletLayout />}
686
+ * {isDesktop && <DesktopLayout />}
687
+ * </div>
688
+ * );
689
+ * ```
690
+ */
691
+ const useMediaQuery = (query) => {
692
+ /** State to track current media query match status */
693
+ const [matches, setMatches] = useState(false);
694
+ useEffect(() => {
695
+ /**
696
+ * Handler function to update matches state when media query changes
697
+ */
698
+ function handleChange() {
699
+ setMatches(getMatches(query));
700
+ }
701
+ const matchMedia = window.matchMedia(query);
702
+ handleChange();
703
+ matchMedia.addEventListener("change", handleChange);
704
+ return () => {
705
+ matchMedia.removeEventListener("change", handleChange);
706
+ };
707
+ }, [query]);
708
+ return matches;
709
+ };
710
+ //#endregion
711
+ //#region src/hooks/use-menu.ts
712
+ /**
713
+ * Menu navigation utilities hook for dashboard layouts
714
+ * Provides comprehensive menu state management and navigation helpers
715
+ * Handles active states, breadcrumbs, and hierarchical menu structures
716
+ */
717
+ /**
718
+ * Hook for managing menu navigation state and utilities
719
+ *
720
+ * This hook provides comprehensive menu management functionality including:
721
+ * - Active state detection for menu items and paths
722
+ * - Hierarchical menu navigation support
723
+ * - Breadcrumb generation for current navigation path
724
+ * - Child menu extraction at specific levels
725
+ * - Support for nested menu structures
726
+ *
727
+ * @param pathname - Current pathname from router or location
728
+ * @returns Object containing menu utility functions
729
+ *
730
+ * @example
731
+ * ```tsx
732
+ * const { isActive, getBreadcrumb, getCurrentItem } = useMenu(pathname);
733
+ *
734
+ * // Check if path is active
735
+ * const isHomeActive = isActive('/dashboard');
736
+ *
737
+ * // Get breadcrumb for current path
738
+ * const breadcrumb = getBreadcrumb(menuItems);
739
+ *
740
+ * // Get current active menu item
741
+ * const currentItem = getCurrentItem(menuItems);
742
+ * ```
743
+ */
744
+ const useMenu = (pathname) => {
745
+ /**
746
+ * Check if a specific path matches the current pathname
747
+ * Handles root path ('/') as exact match, others as prefix match
748
+ *
749
+ * @param path - The path to check against current pathname
750
+ * @returns True if the path is currently active
751
+ */
752
+ const isActive = (path) => {
753
+ if (path && path === "/") return path === pathname;
754
+ else return !!path && pathname.startsWith(path);
755
+ };
756
+ /**
757
+ * Recursively check if any child menu item is currently active
758
+ * Traverses through nested menu structures to find active children
759
+ *
760
+ * @param children - Array of child menu items to check
761
+ * @returns True if any child or nested child is active
762
+ */
763
+ const hasActiveChild = (children) => {
764
+ if (!children || !Array.isArray(children)) return false;
765
+ return children.some((child) => child.path && isActive(child.path) || child.children && hasActiveChild(child.children));
766
+ };
767
+ /**
768
+ * Check if a menu item is active (either directly or through its children)
769
+ * Combines direct path matching with child activity detection
770
+ *
771
+ * @param item - The menu item to check for activity
772
+ * @returns True if the item or any of its children are active
773
+ */
774
+ const isItemActive = (item) => {
775
+ return (item.path ? isActive(item.path) : false) || (item.children ? hasActiveChild(item.children) : false);
776
+ };
777
+ /**
778
+ * Find and return the currently active menu item from the menu configuration
779
+ * Recursively searches through menu hierarchy to find the most specific active item
780
+ * Prioritizes deeper nested items over parent items when both are active
781
+ *
782
+ * @param items - Array of menu items to search through
783
+ * @returns The currently active menu item, or undefined if none found
784
+ */
785
+ const getCurrentItem = (items) => {
786
+ for (const item of items) {
787
+ if (item.path && isActive(item.path)) {
788
+ if (item.children && item.children.length > 0) return getCurrentItem(item.children) || item;
789
+ return item;
790
+ }
791
+ if (item.children && item.children.length > 0) {
792
+ const childMatch = getCurrentItem(item.children);
793
+ if (childMatch) return childMatch;
794
+ }
795
+ }
796
+ };
797
+ /**
798
+ * Generate breadcrumb trail for the current active path
799
+ * Creates an array of menu items representing the navigation path from root to current item
800
+ * Useful for displaying navigation breadcrumbs in the UI
801
+ *
802
+ * @param items - Array of menu items to generate breadcrumb from
803
+ * @returns Array of menu items representing the breadcrumb trail
804
+ */
805
+ const getBreadcrumb = (items) => {
806
+ const findBreadcrumb = (nodes, breadcrumb = []) => {
807
+ for (const item of nodes) {
808
+ const currentBreadcrumb = [...breadcrumb, item];
809
+ if (item.children && item.children.length > 0) {
810
+ const childBreadcrumb = findBreadcrumb(item.children, currentBreadcrumb);
811
+ if (childBreadcrumb.length > currentBreadcrumb.length) return childBreadcrumb;
812
+ }
813
+ if (item.path && isActive(item.path)) return currentBreadcrumb;
814
+ }
815
+ return breadcrumb;
816
+ };
817
+ const breadcrumb = findBreadcrumb(items);
818
+ return breadcrumb.length > 0 ? breadcrumb : [];
819
+ };
820
+ /**
821
+ * Get child menu items at a specific hierarchical level for the current active path
822
+ * Traverses the menu structure to find children at the specified depth level
823
+ * Useful for displaying sub-navigation menus at different levels
824
+ *
825
+ * @param items - Array of menu items to search through
826
+ * @param level - The hierarchical level to get children from (0-based)
827
+ * @returns Array of child menu items at the specified level, or null if none found
828
+ */
829
+ const getChildren = (items, level) => {
830
+ const hasActiveChildAtLevel = (items) => {
831
+ for (const item of items) if (item.path && (item.path === pathname || item.path !== "/" && item.path !== "" && pathname.startsWith(item.path)) || item.children && hasActiveChildAtLevel(item.children)) return true;
832
+ return false;
833
+ };
834
+ const findChildren = (items, targetLevel, currentLevel = 0) => {
835
+ for (const item of items) if (item.children) {
836
+ if (targetLevel === currentLevel && hasActiveChildAtLevel(item.children)) return item.children;
837
+ const children = findChildren(item.children, targetLevel, currentLevel + 1);
838
+ if (children) return children;
839
+ } else if (targetLevel === currentLevel && item.path && (item.path === pathname || item.path !== "/" && item.path !== "" && pathname.startsWith(item.path))) return items;
840
+ return null;
841
+ };
842
+ return findChildren(items, level);
843
+ };
844
+ return {
845
+ isActive,
846
+ hasActiveChild,
847
+ isItemActive,
848
+ getCurrentItem,
849
+ getBreadcrumb,
850
+ getChildren
851
+ };
852
+ };
853
+ //#endregion
854
+ //#region src/hooks/use-meta-color.ts
855
+ /**
856
+ * Meta theme color management hook for React components.
857
+ */
858
+ /**
859
+ * Calculates and applies the HTML `theme-color` meta tag from `next-themes`.
860
+ * The returned setter can be used for temporary manual overrides.
861
+ *
862
+ * @param defaultColors - Optional custom color configuration (defaults to META_THEME_COLORS)
863
+ * @returns Object containing current meta color and setter function.
864
+ *
865
+ * @example
866
+ * ```tsx
867
+ * // Basic usage with default colors (supports light, dark, and system)
868
+ * function App() {
869
+ * const { metaColor, setMetaColor } = useMetaColor();
870
+ *
871
+ * // metaColor automatically updates based on theme (light/dark/system)
872
+ * useEffect(() => {
873
+ * console.log('Current meta color:', metaColor);
874
+ * }, [metaColor]);
875
+ *
876
+ * return <div>App content</div>;
877
+ * }
878
+ *
879
+ * // Custom colors with system theme support
880
+ * function CustomThemeApp() {
881
+ * const customColors = {
882
+ * light: '#f0f0f0',
883
+ * dark: '#1a1a1a',
884
+ * system: 'auto' // Will resolve to light or dark based on OS preference
885
+ * };
886
+ * const { metaColor } = useMetaColor(customColors);
887
+ *
888
+ * return <div style={{ backgroundColor: metaColor }}>Custom themed app</div>;
889
+ * }
890
+ *
891
+ * // Manual meta color override for special pages
892
+ * function SpecialPage() {
893
+ * const { setMetaColor } = useMetaColor();
894
+ *
895
+ * useEffect(() => {
896
+ * // Override meta color for this page
897
+ * setMetaColor('#ff0000');
898
+ *
899
+ * // Cleanup: reset to theme color when leaving page
900
+ * return () => {
901
+ * setMetaColor(''); // This will revert to theme-based color
902
+ * };
903
+ * }, [setMetaColor]);
904
+ *
905
+ * return <div>Special page with red theme color</div>;
906
+ * }
907
+ *
908
+ * // Integration with theme switcher
909
+ * function ThemeAwareComponent() {
910
+ * const { theme, setTheme } = useTheme();
911
+ * const { metaColor } = useMetaColor();
912
+ *
913
+ * return (
914
+ * <div>
915
+ * <p>Current theme: {theme}</p>
916
+ * <p>Meta color: {metaColor}</p>
917
+ * <button onClick={() => setTheme('light')}>Light</button>
918
+ * <button onClick={() => setTheme('dark')}>Dark</button>
919
+ * <button onClick={() => setTheme('system')}>System</button>
920
+ * </div>
921
+ * );
922
+ * }
923
+ * ```
924
+ */
925
+ function useMetaColor(defaultColors) {
926
+ /** Get resolved theme from next-themes */
927
+ const { resolvedTheme } = useTheme();
928
+ /**
929
+ * Helper function to detect system dark mode preference
930
+ */
931
+ const isSystemDarkMode = React$1.useCallback(() => {
932
+ if (typeof window === "undefined") return false;
933
+ return window.matchMedia("(prefers-color-scheme: dark)").matches;
934
+ }, []);
935
+ /**
936
+ * Get effective theme mode (resolves 'system' to actual preference)
937
+ */
938
+ const getEffectiveTheme = React$1.useCallback((theme) => {
939
+ if (theme === THEME_MODES.SYSTEM) return isSystemDarkMode() ? THEME_MODES.DARK : THEME_MODES.LIGHT;
940
+ return theme;
941
+ }, [isSystemDarkMode]);
942
+ /**
943
+ * Calculate appropriate meta color based on current theme
944
+ * Handles light, dark, and system themes properly
945
+ * Memoized to prevent unnecessary recalculations
946
+ */
947
+ const metaColor = React$1.useMemo(() => {
948
+ const colorsToUse = defaultColors ?? META_THEME_COLORS;
949
+ const effectiveTheme = getEffectiveTheme(resolvedTheme);
950
+ if (effectiveTheme === THEME_MODES.DARK) return colorsToUse[THEME_MODES.DARK];
951
+ else if (effectiveTheme === THEME_MODES.LIGHT) return colorsToUse[THEME_MODES.LIGHT];
952
+ return colorsToUse[THEME_MODES.LIGHT];
953
+ }, [
954
+ resolvedTheme,
955
+ defaultColors,
956
+ getEffectiveTheme
957
+ ]);
958
+ /**
959
+ * Manually set meta theme color in the document
960
+ * Useful for temporary color overrides or custom scenarios
961
+ *
962
+ * @param color - Hex color string to set as meta theme color
963
+ */
964
+ const setMetaColor = React$1.useCallback((color) => {
965
+ const metaTag = document.querySelector("meta[name=\"theme-color\"]");
966
+ if (metaTag) metaTag.setAttribute("content", color);
967
+ else {
968
+ const newMetaTag = document.createElement("meta");
969
+ newMetaTag.name = "theme-color";
970
+ newMetaTag.content = color;
971
+ document.head.appendChild(newMetaTag);
972
+ }
973
+ }, []);
974
+ React$1.useEffect(() => {
975
+ setMetaColor(metaColor);
976
+ }, [metaColor, setMetaColor]);
977
+ return {
978
+ /** Current meta theme color based on resolved theme */
979
+ metaColor,
980
+ /** Function to manually set meta theme color */
981
+ setMetaColor
982
+ };
983
+ }
984
+ //#endregion
985
+ //#region src/hooks/use-mutation-observer.ts
986
+ /**
987
+ * DOM Mutation Observer hook for React components
988
+ * Provides a React-friendly interface for observing DOM changes
989
+ * with automatic cleanup and ref integration
990
+ */
991
+ /**
992
+ * Default options for MutationObserver
993
+ * Observes all types of mutations by default
994
+ */
995
+ const DEFAULT_OPTIONS = {
996
+ /** Watch for attribute changes */
997
+ attributes: true,
998
+ /** Watch for text content changes */
999
+ characterData: true,
1000
+ /** Watch for child element additions/removals */
1001
+ childList: true,
1002
+ /** Watch for changes in descendant elements */
1003
+ subtree: true
1004
+ };
1005
+ /**
1006
+ * Hook to observe DOM mutations on a referenced element
1007
+ *
1008
+ * This hook provides a React-friendly way to use the MutationObserver API.
1009
+ * It automatically handles observer creation, cleanup, and ref management.
1010
+ * Useful for detecting DOM changes that occur outside of React's control.
1011
+ *
1012
+ * Features:
1013
+ * - Automatic observer lifecycle management
1014
+ * - Configurable observation options
1015
+ * - Ref-based element targeting
1016
+ * - Automatic cleanup on unmount
1017
+ *
1018
+ * @param ref - React ref pointing to the element to observe
1019
+ * @param callback - Function called when mutations are detected
1020
+ * @param options - MutationObserver configuration options
1021
+ *
1022
+ * @example
1023
+ * ```tsx
1024
+ * function DynamicContent() {
1025
+ * const contentRef = useRef<HTMLDivElement>(null);
1026
+ *
1027
+ * // Watch for any changes to the content div
1028
+ * useMutationObserver(
1029
+ * contentRef,
1030
+ * (mutations) => {
1031
+ * mutations.forEach((mutation) => {
1032
+ * console.log('DOM changed:', mutation.type);
1033
+ * });
1034
+ * }
1035
+ * );
1036
+ *
1037
+ * return <div ref={contentRef}>Dynamic content here</div>;
1038
+ * }
1039
+ *
1040
+ * // Watch only for attribute changes
1041
+ * function AttributeWatcher() {
1042
+ * const elementRef = useRef<HTMLElement>(null);
1043
+ *
1044
+ * useMutationObserver(
1045
+ * elementRef,
1046
+ * (mutations) => {
1047
+ * mutations.forEach((mutation) => {
1048
+ * if (mutation.type === 'attributes') {
1049
+ * console.log('Attribute changed:', mutation.attributeName);
1050
+ * }
1051
+ * });
1052
+ * },
1053
+ * { attributes: true, childList: false, subtree: false }
1054
+ * );
1055
+ *
1056
+ * return <div ref={elementRef}>Watched element</div>;
1057
+ * }
1058
+ * ```
1059
+ */
1060
+ const useMutationObserver = (ref, callback, options = DEFAULT_OPTIONS) => {
1061
+ React$1.useEffect(() => {
1062
+ if (ref.current) {
1063
+ const observer = new MutationObserver(callback);
1064
+ observer.observe(ref.current, options);
1065
+ return () => {
1066
+ observer.disconnect();
1067
+ };
1068
+ }
1069
+ }, [
1070
+ ref,
1071
+ callback,
1072
+ options
1073
+ ]);
1074
+ };
1075
+ //#endregion
1076
+ //#region src/hooks/use-remove-ga-params.ts
1077
+ /**
1078
+ * Google Analytics linker parameter cleanup hook for React
1079
+ * Safely removes the GA `_gl` query parameter from the URL after GA initialization.
1080
+ */
1081
+ /**
1082
+ * Hook to remove the Google Analytics `_gl` query parameter from the current URL.
1083
+ *
1084
+ * GA's cross-domain linker temporarily appends `_gl` to URLs for attribution.
1085
+ * Removing it *too early* can break attribution, so this hook waits briefly
1086
+ * (≈2 seconds) to allow GA to read it, then strips the param using
1087
+ * `history.replaceState` without causing a page reload or React re-render.
1088
+ *
1089
+ * Behavior:
1090
+ * - Runs once on mount.
1091
+ * - If `_gl` is present, schedules its removal after ~2000ms.
1092
+ * - Uses `window.history.replaceState` to avoid navigation/re-render.
1093
+ *
1094
+ * @example
1095
+ * ```tsx
1096
+ * // app/layout.tsx or a top-level client component
1097
+ * import { useRemoveGAParams } from '@/hooks/use-remove-ga-params';
1098
+ *
1099
+ * export default function RootLayout({ children }: { children: React.ReactNode }) {
1100
+ * useRemoveGAParams();
1101
+ * return <>{children}</>;
1102
+ * }
1103
+ * ```
1104
+ */
1105
+ function useRemoveGAParams() {
1106
+ useEffect(() => {
1107
+ if (new URL(window.location.href).searchParams.has("_gl")) {
1108
+ const timer = setTimeout(() => {
1109
+ const url = new URL(window.location.href);
1110
+ url.searchParams.delete("_gl");
1111
+ window.history.replaceState({}, "", url.toString());
1112
+ }, 2e3);
1113
+ return () => clearTimeout(timer);
1114
+ }
1115
+ }, []);
1116
+ }
1117
+ //#endregion
1118
+ //#region src/hooks/use-scroll-position.ts
1119
+ /**
1120
+ * Scroll position tracking hook for React components
1121
+ * Monitors scroll position of window or specific elements
1122
+ * with real-time updates and automatic cleanup
1123
+ */
1124
+ /**
1125
+ * Hook to track scroll position of window or specific elements
1126
+ *
1127
+ * This hook provides real-time tracking of scroll position with support
1128
+ * for both window scrolling and element-specific scrolling. It automatically
1129
+ * handles event listener management and cleanup.
1130
+ *
1131
+ * Features:
1132
+ * - Real-time scroll position tracking
1133
+ * - Support for window and element scrolling
1134
+ * - Automatic event listener cleanup
1135
+ * - SSR-safe implementation
1136
+ * - Performance optimized
1137
+ *
1138
+ * @param options - Configuration options for the hook
1139
+ * @returns Current scroll position in pixels
1140
+ *
1141
+ * @example
1142
+ * ```tsx
1143
+ * // Track window scroll position
1144
+ * function ScrollIndicator() {
1145
+ * const scrollPosition = useScrollPosition();
1146
+ *
1147
+ * return (
1148
+ * <div className="scroll-indicator">
1149
+ * Scrolled: {scrollPosition}px
1150
+ * </div>
1151
+ * );
1152
+ * }
1153
+ *
1154
+ * // Track specific element scroll position
1155
+ * function ScrollableContent() {
1156
+ * const contentRef = useRef<HTMLDivElement>(null);
1157
+ * const scrollPosition = useScrollPosition({ targetRef: contentRef });
1158
+ *
1159
+ * return (
1160
+ * <div
1161
+ * ref={contentRef}
1162
+ * className="h-96 overflow-y-auto"
1163
+ * >
1164
+ * <div className="h-[1000px]">
1165
+ * <p>Scroll position: {scrollPosition}px</p>
1166
+ * <p>Long content here...</p>
1167
+ * </div>
1168
+ * </div>
1169
+ * );
1170
+ * }
1171
+ *
1172
+ * // Show/hide header based on scroll
1173
+ * function StickyHeader() {
1174
+ * const scrollPosition = useScrollPosition();
1175
+ * const isVisible = scrollPosition < 100;
1176
+ *
1177
+ * return (
1178
+ * <header className={`transition-transform ${
1179
+ * isVisible ? 'translate-y-0' : '-translate-y-full'
1180
+ * }`}>
1181
+ * Header content
1182
+ * </header>
1183
+ * );
1184
+ * }
1185
+ * ```
1186
+ */
1187
+ const useScrollPosition = ({ targetRef } = {}) => {
1188
+ /** State to track current scroll position */
1189
+ const [scrollPosition, setScrollPosition] = useState(0);
1190
+ useEffect(() => {
1191
+ const target = targetRef?.current || document;
1192
+ const scrollable = target === document ? window : target;
1193
+ /**
1194
+ * Update scroll position state
1195
+ * Handles both window and element scrolling
1196
+ */
1197
+ const updatePosition = () => {
1198
+ const scrollY = target === document ? window.scrollY || window.pageYOffset : target.scrollTop;
1199
+ setScrollPosition(scrollY);
1200
+ };
1201
+ scrollable.addEventListener("scroll", updatePosition, { passive: true });
1202
+ updatePosition();
1203
+ return () => {
1204
+ scrollable.removeEventListener("scroll", updatePosition);
1205
+ };
1206
+ }, [targetRef]);
1207
+ return scrollPosition;
1208
+ };
1209
+ //#endregion
1210
+ //#region src/hooks/use-slider-input.ts
1211
+ /**
1212
+ * Dual slider input management hook for React components
1213
+ * Provides synchronized state management between range slider and number inputs
1214
+ * with validation and boundary enforcement
1215
+ */
1216
+ /**
1217
+ * Hook for managing dual slider input with synchronized state
1218
+ *
1219
+ * This hook provides state management for components that need both
1220
+ * a range slider and corresponding number inputs. It handles synchronization
1221
+ * between the two input types, validation, and boundary enforcement.
1222
+ *
1223
+ * Features:
1224
+ * - Synchronized slider and input values
1225
+ * - Automatic validation and boundary enforcement
1226
+ * - Prevents invalid range configurations (min > max)
1227
+ * - Optimized with useCallback for performance
1228
+ *
1229
+ * @param props - Configuration options for the hook
1230
+ * @returns Object containing state and handlers for slider and inputs
1231
+ *
1232
+ * @example
1233
+ * ```tsx
1234
+ * function PriceRangeFilter() {
1235
+ * const {
1236
+ * sliderValues,
1237
+ * inputValues,
1238
+ * handleSliderChange,
1239
+ * handleInputChange,
1240
+ * validateAndUpdateValue
1241
+ * } = useSliderInput({
1242
+ * minValue: 0,
1243
+ * maxValue: 1000,
1244
+ * initialValue: [100, 500]
1245
+ * });
1246
+ *
1247
+ * return (
1248
+ * <div className="price-range">
1249
+ * <div className="inputs">
1250
+ * <input
1251
+ * type="number"
1252
+ * value={inputValues[0]}
1253
+ * onChange={(e) => handleInputChange(e, 0)}
1254
+ * onBlur={() => validateAndUpdateValue(inputValues[0], 0)}
1255
+ * placeholder="Min price"
1256
+ * />
1257
+ * <input
1258
+ * type="number"
1259
+ * value={inputValues[1]}
1260
+ * onChange={(e) => handleInputChange(e, 1)}
1261
+ * onBlur={() => validateAndUpdateValue(inputValues[1], 1)}
1262
+ * placeholder="Max price"
1263
+ * />
1264
+ * </div>
1265
+ *
1266
+ * <Slider
1267
+ * value={sliderValues}
1268
+ * onValueChange={handleSliderChange}
1269
+ * min={0}
1270
+ * max={1000}
1271
+ * step={10}
1272
+ * />
1273
+ * </div>
1274
+ * );
1275
+ * }
1276
+ * ```
1277
+ */
1278
+ function useSliderInput({ minValue, maxValue, initialValue }) {
1279
+ /** State for slider component values */
1280
+ const [sliderValues, setSliderValues] = useState(initialValue);
1281
+ /** State for input field values (may temporarily differ from slider) */
1282
+ const [inputValues, setInputValues] = useState(initialValue);
1283
+ return {
1284
+ /** Function to manually set slider values */
1285
+ setSliderValues,
1286
+ /** Function to manually set input values */
1287
+ setInputValues,
1288
+ /** Current slider values [min, max] */
1289
+ sliderValues,
1290
+ /** Current input values [min, max] */
1291
+ inputValues,
1292
+ /** Handler for slider value changes */
1293
+ handleSliderChange: useCallback((values) => {
1294
+ setSliderValues(values);
1295
+ setInputValues(values);
1296
+ }, []),
1297
+ /** Handler for input field changes */
1298
+ handleInputChange: useCallback((e, index) => {
1299
+ const newValue = parseFloat(e.target.value);
1300
+ if (!Number.isNaN(newValue)) {
1301
+ const updatedInputs = [...inputValues];
1302
+ updatedInputs[index] = newValue;
1303
+ setInputValues(updatedInputs);
1304
+ }
1305
+ }, [inputValues]),
1306
+ /** Function to validate and update values from inputs */
1307
+ validateAndUpdateValue: useCallback((value, index) => {
1308
+ const updatedSlider = [...sliderValues];
1309
+ if (index === 0) updatedSlider[0] = Math.max(minValue, Math.min(value, sliderValues[1]));
1310
+ else updatedSlider[1] = Math.min(maxValue, Math.max(value, sliderValues[0]));
1311
+ setSliderValues(updatedSlider);
1312
+ setInputValues(updatedSlider);
1313
+ }, [
1314
+ sliderValues,
1315
+ minValue,
1316
+ maxValue
1317
+ ])
1318
+ };
1319
+ }
1320
+ //#endregion
1321
+ //#region src/hooks/use-viewport.ts
1322
+ /**
1323
+ * Viewport dimensions tracking hook for React components
1324
+ * Provides real-time viewport width and height with automatic updates
1325
+ * on window resize events with SSR-safe implementation
1326
+ */
1327
+ /**
1328
+ * Hook to track viewport dimensions with real-time updates
1329
+ *
1330
+ * This hook provides the current viewport dimensions and automatically
1331
+ * updates when the window is resized. It's useful for responsive layouts,
1332
+ * conditional rendering based on screen size, and dynamic calculations.
1333
+ *
1334
+ * Features:
1335
+ * - Real-time viewport dimension tracking
1336
+ * - Automatic updates on window resize
1337
+ * - Performance optimized with passive event listeners
1338
+ * - SSR-safe implementation
1339
+ * - Returns both width and height
1340
+ *
1341
+ * @returns Tuple containing [width, height] in pixels
1342
+ *
1343
+ * @example
1344
+ * ```tsx
1345
+ * // Basic usage
1346
+ * function ResponsiveComponent() {
1347
+ * const [width, height] = useViewport();
1348
+ *
1349
+ * return (
1350
+ * <div>
1351
+ * <p>Viewport: {width}x{height}</p>
1352
+ * {width > 768 ? <DesktopLayout /> : <MobileLayout />}
1353
+ * </div>
1354
+ * );
1355
+ * }
1356
+ *
1357
+ * // Destructured usage
1358
+ * function ViewportInfo() {
1359
+ * const [width, height] = useViewport();
1360
+ * const aspectRatio = (width / height).toFixed(2);
1361
+ *
1362
+ * return (
1363
+ * <div className="viewport-info">
1364
+ * <p>Width: {width}px</p>
1365
+ * <p>Height: {height}px</p>
1366
+ * <p>Aspect Ratio: {aspectRatio}</p>
1367
+ * </div>
1368
+ * );
1369
+ * }
1370
+ *
1371
+ * // Conditional rendering based on viewport
1372
+ * function AdaptiveGrid() {
1373
+ * const [width] = useViewport();
1374
+ * const columns = width > 1200 ? 4 : width > 768 ? 3 : width > 480 ? 2 : 1;
1375
+ *
1376
+ * return (
1377
+ * <div className={`grid grid-cols-${columns} gap-4`}>
1378
+ * {items.map(item => <GridItem key={item.id} {...item} />)}
1379
+ * </div>
1380
+ * );
1381
+ * }
1382
+ * ```
1383
+ */
1384
+ const useViewport = () => {
1385
+ /**
1386
+ * State to track viewport dimensions
1387
+ * Initialized with current window dimensions or fallback for SSR
1388
+ */
1389
+ const [dimensions, setDimensions] = useState([0, 0]);
1390
+ useEffect(() => {
1391
+ /**
1392
+ * Handle window resize events
1393
+ * Updates dimensions state with current viewport size
1394
+ */
1395
+ const handleResize = () => {
1396
+ setDimensions([window.innerWidth, window.innerHeight]);
1397
+ };
1398
+ handleResize();
1399
+ window.addEventListener("resize", handleResize, { passive: true });
1400
+ return () => {
1401
+ window.removeEventListener("resize", handleResize);
1402
+ };
1403
+ }, []);
1404
+ return dimensions;
1405
+ };
1406
+ //#endregion
1407
+ export { formatBytes, useBodyClasses, useCopyToClipboard, useFileUpload, useHydrated, useIntersectionObserver, useIsMac, useIsMobile, useMediaQuery, useMenu, useMetaColor, useMutationObserver, useRemoveGAParams, useScrollPosition, useSliderInput, useViewport };
1408
+
1409
+ //# sourceMappingURL=hooks.js.map