@alessiofrittoli/react-hooks 3.4.0 → 3.6.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/README.md +804 -650
- package/dist/index.d.mts +165 -1
- package/dist/index.d.ts +165 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +10 -10
package/dist/index.d.mts
CHANGED
|
@@ -115,6 +115,60 @@ interface UseDarkModeOptions {
|
|
|
115
115
|
*/
|
|
116
116
|
declare const useDarkMode: (options?: UseDarkModeOptions) => UseDarkModeOutput;
|
|
117
117
|
|
|
118
|
+
/**
|
|
119
|
+
* Handle Document visibility changes.
|
|
120
|
+
*
|
|
121
|
+
* @param isVisible Indicates whether the Document is visible or not.
|
|
122
|
+
*/
|
|
123
|
+
type VisibilityChangeHandler = (isVisible: boolean) => void;
|
|
124
|
+
interface UseDocumentVisibilityOptions {
|
|
125
|
+
/**
|
|
126
|
+
* Whether to update React state about Document visibility state or not.
|
|
127
|
+
*
|
|
128
|
+
* @default true
|
|
129
|
+
*/
|
|
130
|
+
updateState?: boolean;
|
|
131
|
+
/**
|
|
132
|
+
* A custom callback executed when Document visiblity sate changes.
|
|
133
|
+
*
|
|
134
|
+
*/
|
|
135
|
+
onVisibilityChange?: VisibilityChangeHandler;
|
|
136
|
+
}
|
|
137
|
+
interface StateDisabledUseDocumentVisibilityOptions extends UseDocumentVisibilityOptions {
|
|
138
|
+
/**
|
|
139
|
+
* React state updates will be disabled.
|
|
140
|
+
*
|
|
141
|
+
* @default true
|
|
142
|
+
*/
|
|
143
|
+
updateState: false;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Track the visibility state of the Document (i.e., whether the page is visible or hidden).
|
|
147
|
+
*
|
|
148
|
+
* @param options (Optional) Configuration options for the hook.
|
|
149
|
+
* @param options.updateState If `true` (default), the hook manages and returns the visibility state. If `false`, the hook does not manage state and only calls `onVisibilityChange`.
|
|
150
|
+
* @param options.onVisibilityChange Optional callback invoked whenever the Document's visibility changes. Receives the new visibility state as a boolean.
|
|
151
|
+
*
|
|
152
|
+
* @remarks
|
|
153
|
+
* - Uses the Page Visibility API (`document.hidden` and `visibilitychange` event).
|
|
154
|
+
* - The hook will not trigger re-renders on visibility changes since `updateState` has been set to `false`.
|
|
155
|
+
*/
|
|
156
|
+
declare function useDocumentVisibility(otpions: StateDisabledUseDocumentVisibilityOptions): void;
|
|
157
|
+
/**
|
|
158
|
+
* Track the visibility state of the Document (i.e., whether the page is visible or hidden).
|
|
159
|
+
*
|
|
160
|
+
* @param options (Optional) Configuration options for the hook.
|
|
161
|
+
* @param options.updateState The hook will manage and return the visibility state.
|
|
162
|
+
* @param options.onVisibilityChange Optional callback invoked whenever the Document's visibility changes. Receives the new visibility state as a boolean.
|
|
163
|
+
*
|
|
164
|
+
* @returns Returns `true` if the Document is visible, `false` otherwise.
|
|
165
|
+
*
|
|
166
|
+
* @remarks
|
|
167
|
+
* - Uses the Page Visibility API (`document.hidden` and `visibilitychange` event).
|
|
168
|
+
* - The hook will trigger re-renders on visibility changes since `updateState` is `true` by default.
|
|
169
|
+
*/
|
|
170
|
+
declare function useDocumentVisibility(otpions?: UseDocumentVisibilityOptions): boolean;
|
|
171
|
+
|
|
118
172
|
/**
|
|
119
173
|
* Specifies characteristics about the event listener.
|
|
120
174
|
*
|
|
@@ -510,6 +564,23 @@ declare function useEventListener<T extends Record<string, Event>, K extends key
|
|
|
510
564
|
*/
|
|
511
565
|
declare const useIsPortrait: () => boolean;
|
|
512
566
|
|
|
567
|
+
/**
|
|
568
|
+
* Detects if the current device supports touch events.
|
|
569
|
+
*
|
|
570
|
+
* @returns A boolean indicating whether the device is a touch device or not.
|
|
571
|
+
*
|
|
572
|
+
* @example
|
|
573
|
+
*
|
|
574
|
+
* ```ts
|
|
575
|
+
* const isTouch = useIsTouchDevice()
|
|
576
|
+
*
|
|
577
|
+
* if ( isTouch ) {
|
|
578
|
+
* // Enable touch-specific UI
|
|
579
|
+
* }
|
|
580
|
+
* ```
|
|
581
|
+
*/
|
|
582
|
+
declare const useIsTouchDevice: () => boolean;
|
|
583
|
+
|
|
513
584
|
type OnChangeHandler = (matches: boolean) => void;
|
|
514
585
|
interface CommonOptions {
|
|
515
586
|
/**
|
|
@@ -525,12 +596,18 @@ interface UseMediaQueryOptions extends CommonOptions {
|
|
|
525
596
|
*
|
|
526
597
|
*/
|
|
527
598
|
updateState: false;
|
|
599
|
+
/**
|
|
600
|
+
* A custom callback that will be invoked on initial page load and when the given `query` change event get dispatched.
|
|
601
|
+
*
|
|
602
|
+
* @param matches Whether the document currently matches the media query list.
|
|
603
|
+
*/
|
|
528
604
|
onChange: OnChangeHandler;
|
|
529
605
|
}
|
|
530
606
|
interface UseMediaQueryStateOptions extends CommonOptions {
|
|
531
607
|
/**
|
|
532
608
|
* Indicates whether the hook will dispatch a React state update when the given `query` change event get dispatched.
|
|
533
609
|
*
|
|
610
|
+
* @default true
|
|
534
611
|
*/
|
|
535
612
|
updateState?: true;
|
|
536
613
|
}
|
|
@@ -555,6 +632,93 @@ declare function useMediaQuery(query: string, options?: UseMediaQueryStateOption
|
|
|
555
632
|
*/
|
|
556
633
|
declare function useMediaQuery(query: string, options?: UseMediaQueryOptions): void;
|
|
557
634
|
|
|
635
|
+
/**
|
|
636
|
+
* Defines a callback executed when a screen Wake Lock request fails.
|
|
637
|
+
*
|
|
638
|
+
* @param error The `DOMException` thrown by [`WakeLock.request()`](https://developer.mozilla.org/en-US/docs/Web/API/WakeLock/request).
|
|
639
|
+
*/
|
|
640
|
+
type OnWakeLockRequestError = (error: DOMException) => void;
|
|
641
|
+
interface UseWakeLockOptions {
|
|
642
|
+
/**
|
|
643
|
+
* Indicates whether to request the screen Wake Lock on mount.
|
|
644
|
+
*
|
|
645
|
+
* @default true
|
|
646
|
+
*/
|
|
647
|
+
onMount?: boolean;
|
|
648
|
+
/**
|
|
649
|
+
* A custom callback executed when a screen Wake Lock request fails.
|
|
650
|
+
*
|
|
651
|
+
* @param error The `DOMException` thrown by [`WakeLock.request()`](https://developer.mozilla.org/en-US/docs/Web/API/WakeLock/request).
|
|
652
|
+
*/
|
|
653
|
+
onError?: OnWakeLockRequestError;
|
|
654
|
+
}
|
|
655
|
+
interface UseWakeLockBase {
|
|
656
|
+
/**
|
|
657
|
+
* Manually request the Wake Lock.
|
|
658
|
+
*
|
|
659
|
+
*/
|
|
660
|
+
requestWakeLock: () => Promise<void>;
|
|
661
|
+
/**
|
|
662
|
+
* Manually release the Wake Lock.
|
|
663
|
+
*
|
|
664
|
+
*/
|
|
665
|
+
releaseWakeLock: () => Promise<void>;
|
|
666
|
+
}
|
|
667
|
+
type UseWakeLock = UseWakeLockBase & ({
|
|
668
|
+
/**
|
|
669
|
+
* The **`WakeLockSentinel`** interface of the Screen Wake Lock API can be used to monitor the status of the platform screen wake lock, and manually release the lock when needed.
|
|
670
|
+
* Available only in secure contexts.
|
|
671
|
+
*
|
|
672
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WakeLockSentinel)
|
|
673
|
+
*/
|
|
674
|
+
wakeLock: WakeLockSentinel;
|
|
675
|
+
/**
|
|
676
|
+
* Indicates whether the Wake Lock is enabled.
|
|
677
|
+
*
|
|
678
|
+
*/
|
|
679
|
+
enabled: true;
|
|
680
|
+
} | {
|
|
681
|
+
/**
|
|
682
|
+
* The **`WakeLockSentinel`** interface of the Screen Wake Lock API returned by the `WakeLock` instance once has been enabled.
|
|
683
|
+
* Available only in secure contexts.
|
|
684
|
+
*
|
|
685
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WakeLockSentinel)
|
|
686
|
+
*/
|
|
687
|
+
wakeLock: null;
|
|
688
|
+
/**
|
|
689
|
+
* Indicates whether the Wake Lock is enabled.
|
|
690
|
+
*
|
|
691
|
+
*/
|
|
692
|
+
enabled: false;
|
|
693
|
+
});
|
|
694
|
+
/**
|
|
695
|
+
* React hook to manage the Screen Wake Lock API.
|
|
696
|
+
*
|
|
697
|
+
* This hook allows you to request and release a screen wake lock, preventing the device from dimming or locking the screen.
|
|
698
|
+
* It automatically handles wake lock requests based on document visibility and user interaction.
|
|
699
|
+
*
|
|
700
|
+
* @param options An object defining hook options. See {@link UseWakeLockOptions} for more info.
|
|
701
|
+
* @returns An object returning The current `WakeLockSentinel` instance or `null` if not enabled and utility functions. See {@link UseWakeLock} for more info.
|
|
702
|
+
*
|
|
703
|
+
* @example
|
|
704
|
+
* ```tsx
|
|
705
|
+
* const { enabled, requestWakeLock, releaseWakeLock } = useWakeLock()
|
|
706
|
+
*
|
|
707
|
+
* if ( ! enabled ) {
|
|
708
|
+
* // Request wake lock on button click
|
|
709
|
+
* <button onClick={ requestWakeLock }>Enable Wake Lock</button>
|
|
710
|
+
* }
|
|
711
|
+
*
|
|
712
|
+
* if ( enabled ) {
|
|
713
|
+
* // Release wake lock on button click
|
|
714
|
+
* <button onClick={ releaseWakeLock }>Disable Wake Lock</button>
|
|
715
|
+
* }
|
|
716
|
+
* ```
|
|
717
|
+
*
|
|
718
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API
|
|
719
|
+
*/
|
|
720
|
+
declare const useWakeLock: (options?: UseWakeLockOptions) => UseWakeLock;
|
|
721
|
+
|
|
558
722
|
type SetFocusTrap = (target?: HTMLElement) => void;
|
|
559
723
|
type RestoreFocusTrap = () => void;
|
|
560
724
|
/**
|
|
@@ -1359,4 +1523,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
|
|
|
1359
1523
|
*/
|
|
1360
1524
|
declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
|
|
1361
1525
|
|
|
1362
|
-
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type ValidateValueHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect };
|
|
1526
|
+
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type OnWakeLockRequestError, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateDisabledUseDocumentVisibilityOptions, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseDocumentVisibilityOptions, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type UseWakeLock, type UseWakeLockBase, type UseWakeLockOptions, type ValidateValueHandler, type VisibilityChangeHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useDocumentVisibility, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useIsTouchDevice, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect, useWakeLock };
|
package/dist/index.d.ts
CHANGED
|
@@ -115,6 +115,60 @@ interface UseDarkModeOptions {
|
|
|
115
115
|
*/
|
|
116
116
|
declare const useDarkMode: (options?: UseDarkModeOptions) => UseDarkModeOutput;
|
|
117
117
|
|
|
118
|
+
/**
|
|
119
|
+
* Handle Document visibility changes.
|
|
120
|
+
*
|
|
121
|
+
* @param isVisible Indicates whether the Document is visible or not.
|
|
122
|
+
*/
|
|
123
|
+
type VisibilityChangeHandler = (isVisible: boolean) => void;
|
|
124
|
+
interface UseDocumentVisibilityOptions {
|
|
125
|
+
/**
|
|
126
|
+
* Whether to update React state about Document visibility state or not.
|
|
127
|
+
*
|
|
128
|
+
* @default true
|
|
129
|
+
*/
|
|
130
|
+
updateState?: boolean;
|
|
131
|
+
/**
|
|
132
|
+
* A custom callback executed when Document visiblity sate changes.
|
|
133
|
+
*
|
|
134
|
+
*/
|
|
135
|
+
onVisibilityChange?: VisibilityChangeHandler;
|
|
136
|
+
}
|
|
137
|
+
interface StateDisabledUseDocumentVisibilityOptions extends UseDocumentVisibilityOptions {
|
|
138
|
+
/**
|
|
139
|
+
* React state updates will be disabled.
|
|
140
|
+
*
|
|
141
|
+
* @default true
|
|
142
|
+
*/
|
|
143
|
+
updateState: false;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Track the visibility state of the Document (i.e., whether the page is visible or hidden).
|
|
147
|
+
*
|
|
148
|
+
* @param options (Optional) Configuration options for the hook.
|
|
149
|
+
* @param options.updateState If `true` (default), the hook manages and returns the visibility state. If `false`, the hook does not manage state and only calls `onVisibilityChange`.
|
|
150
|
+
* @param options.onVisibilityChange Optional callback invoked whenever the Document's visibility changes. Receives the new visibility state as a boolean.
|
|
151
|
+
*
|
|
152
|
+
* @remarks
|
|
153
|
+
* - Uses the Page Visibility API (`document.hidden` and `visibilitychange` event).
|
|
154
|
+
* - The hook will not trigger re-renders on visibility changes since `updateState` has been set to `false`.
|
|
155
|
+
*/
|
|
156
|
+
declare function useDocumentVisibility(otpions: StateDisabledUseDocumentVisibilityOptions): void;
|
|
157
|
+
/**
|
|
158
|
+
* Track the visibility state of the Document (i.e., whether the page is visible or hidden).
|
|
159
|
+
*
|
|
160
|
+
* @param options (Optional) Configuration options for the hook.
|
|
161
|
+
* @param options.updateState The hook will manage and return the visibility state.
|
|
162
|
+
* @param options.onVisibilityChange Optional callback invoked whenever the Document's visibility changes. Receives the new visibility state as a boolean.
|
|
163
|
+
*
|
|
164
|
+
* @returns Returns `true` if the Document is visible, `false` otherwise.
|
|
165
|
+
*
|
|
166
|
+
* @remarks
|
|
167
|
+
* - Uses the Page Visibility API (`document.hidden` and `visibilitychange` event).
|
|
168
|
+
* - The hook will trigger re-renders on visibility changes since `updateState` is `true` by default.
|
|
169
|
+
*/
|
|
170
|
+
declare function useDocumentVisibility(otpions?: UseDocumentVisibilityOptions): boolean;
|
|
171
|
+
|
|
118
172
|
/**
|
|
119
173
|
* Specifies characteristics about the event listener.
|
|
120
174
|
*
|
|
@@ -510,6 +564,23 @@ declare function useEventListener<T extends Record<string, Event>, K extends key
|
|
|
510
564
|
*/
|
|
511
565
|
declare const useIsPortrait: () => boolean;
|
|
512
566
|
|
|
567
|
+
/**
|
|
568
|
+
* Detects if the current device supports touch events.
|
|
569
|
+
*
|
|
570
|
+
* @returns A boolean indicating whether the device is a touch device or not.
|
|
571
|
+
*
|
|
572
|
+
* @example
|
|
573
|
+
*
|
|
574
|
+
* ```ts
|
|
575
|
+
* const isTouch = useIsTouchDevice()
|
|
576
|
+
*
|
|
577
|
+
* if ( isTouch ) {
|
|
578
|
+
* // Enable touch-specific UI
|
|
579
|
+
* }
|
|
580
|
+
* ```
|
|
581
|
+
*/
|
|
582
|
+
declare const useIsTouchDevice: () => boolean;
|
|
583
|
+
|
|
513
584
|
type OnChangeHandler = (matches: boolean) => void;
|
|
514
585
|
interface CommonOptions {
|
|
515
586
|
/**
|
|
@@ -525,12 +596,18 @@ interface UseMediaQueryOptions extends CommonOptions {
|
|
|
525
596
|
*
|
|
526
597
|
*/
|
|
527
598
|
updateState: false;
|
|
599
|
+
/**
|
|
600
|
+
* A custom callback that will be invoked on initial page load and when the given `query` change event get dispatched.
|
|
601
|
+
*
|
|
602
|
+
* @param matches Whether the document currently matches the media query list.
|
|
603
|
+
*/
|
|
528
604
|
onChange: OnChangeHandler;
|
|
529
605
|
}
|
|
530
606
|
interface UseMediaQueryStateOptions extends CommonOptions {
|
|
531
607
|
/**
|
|
532
608
|
* Indicates whether the hook will dispatch a React state update when the given `query` change event get dispatched.
|
|
533
609
|
*
|
|
610
|
+
* @default true
|
|
534
611
|
*/
|
|
535
612
|
updateState?: true;
|
|
536
613
|
}
|
|
@@ -555,6 +632,93 @@ declare function useMediaQuery(query: string, options?: UseMediaQueryStateOption
|
|
|
555
632
|
*/
|
|
556
633
|
declare function useMediaQuery(query: string, options?: UseMediaQueryOptions): void;
|
|
557
634
|
|
|
635
|
+
/**
|
|
636
|
+
* Defines a callback executed when a screen Wake Lock request fails.
|
|
637
|
+
*
|
|
638
|
+
* @param error The `DOMException` thrown by [`WakeLock.request()`](https://developer.mozilla.org/en-US/docs/Web/API/WakeLock/request).
|
|
639
|
+
*/
|
|
640
|
+
type OnWakeLockRequestError = (error: DOMException) => void;
|
|
641
|
+
interface UseWakeLockOptions {
|
|
642
|
+
/**
|
|
643
|
+
* Indicates whether to request the screen Wake Lock on mount.
|
|
644
|
+
*
|
|
645
|
+
* @default true
|
|
646
|
+
*/
|
|
647
|
+
onMount?: boolean;
|
|
648
|
+
/**
|
|
649
|
+
* A custom callback executed when a screen Wake Lock request fails.
|
|
650
|
+
*
|
|
651
|
+
* @param error The `DOMException` thrown by [`WakeLock.request()`](https://developer.mozilla.org/en-US/docs/Web/API/WakeLock/request).
|
|
652
|
+
*/
|
|
653
|
+
onError?: OnWakeLockRequestError;
|
|
654
|
+
}
|
|
655
|
+
interface UseWakeLockBase {
|
|
656
|
+
/**
|
|
657
|
+
* Manually request the Wake Lock.
|
|
658
|
+
*
|
|
659
|
+
*/
|
|
660
|
+
requestWakeLock: () => Promise<void>;
|
|
661
|
+
/**
|
|
662
|
+
* Manually release the Wake Lock.
|
|
663
|
+
*
|
|
664
|
+
*/
|
|
665
|
+
releaseWakeLock: () => Promise<void>;
|
|
666
|
+
}
|
|
667
|
+
type UseWakeLock = UseWakeLockBase & ({
|
|
668
|
+
/**
|
|
669
|
+
* The **`WakeLockSentinel`** interface of the Screen Wake Lock API can be used to monitor the status of the platform screen wake lock, and manually release the lock when needed.
|
|
670
|
+
* Available only in secure contexts.
|
|
671
|
+
*
|
|
672
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WakeLockSentinel)
|
|
673
|
+
*/
|
|
674
|
+
wakeLock: WakeLockSentinel;
|
|
675
|
+
/**
|
|
676
|
+
* Indicates whether the Wake Lock is enabled.
|
|
677
|
+
*
|
|
678
|
+
*/
|
|
679
|
+
enabled: true;
|
|
680
|
+
} | {
|
|
681
|
+
/**
|
|
682
|
+
* The **`WakeLockSentinel`** interface of the Screen Wake Lock API returned by the `WakeLock` instance once has been enabled.
|
|
683
|
+
* Available only in secure contexts.
|
|
684
|
+
*
|
|
685
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WakeLockSentinel)
|
|
686
|
+
*/
|
|
687
|
+
wakeLock: null;
|
|
688
|
+
/**
|
|
689
|
+
* Indicates whether the Wake Lock is enabled.
|
|
690
|
+
*
|
|
691
|
+
*/
|
|
692
|
+
enabled: false;
|
|
693
|
+
});
|
|
694
|
+
/**
|
|
695
|
+
* React hook to manage the Screen Wake Lock API.
|
|
696
|
+
*
|
|
697
|
+
* This hook allows you to request and release a screen wake lock, preventing the device from dimming or locking the screen.
|
|
698
|
+
* It automatically handles wake lock requests based on document visibility and user interaction.
|
|
699
|
+
*
|
|
700
|
+
* @param options An object defining hook options. See {@link UseWakeLockOptions} for more info.
|
|
701
|
+
* @returns An object returning The current `WakeLockSentinel` instance or `null` if not enabled and utility functions. See {@link UseWakeLock} for more info.
|
|
702
|
+
*
|
|
703
|
+
* @example
|
|
704
|
+
* ```tsx
|
|
705
|
+
* const { enabled, requestWakeLock, releaseWakeLock } = useWakeLock()
|
|
706
|
+
*
|
|
707
|
+
* if ( ! enabled ) {
|
|
708
|
+
* // Request wake lock on button click
|
|
709
|
+
* <button onClick={ requestWakeLock }>Enable Wake Lock</button>
|
|
710
|
+
* }
|
|
711
|
+
*
|
|
712
|
+
* if ( enabled ) {
|
|
713
|
+
* // Release wake lock on button click
|
|
714
|
+
* <button onClick={ releaseWakeLock }>Disable Wake Lock</button>
|
|
715
|
+
* }
|
|
716
|
+
* ```
|
|
717
|
+
*
|
|
718
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API
|
|
719
|
+
*/
|
|
720
|
+
declare const useWakeLock: (options?: UseWakeLockOptions) => UseWakeLock;
|
|
721
|
+
|
|
558
722
|
type SetFocusTrap = (target?: HTMLElement) => void;
|
|
559
723
|
type RestoreFocusTrap = () => void;
|
|
560
724
|
/**
|
|
@@ -1359,4 +1523,4 @@ declare function useTimeout<T extends readonly unknown[]>(callback: TimerHandler
|
|
|
1359
1523
|
*/
|
|
1360
1524
|
declare const useLightTimeout: <T extends readonly unknown[]>(callback: TimerHandler<T>, options?: BasicTimerOptions<T>) => void;
|
|
1361
1525
|
|
|
1362
|
-
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type ValidateValueHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect };
|
|
1526
|
+
export { type AddEventListenerOptions, type BasicTimerOptions, type ChangeHandler, type CommonListenerOptions, type Connection, type CustomEventListenerOptions, type DocumentEventListener, type DocumentListenerOptions, type ElementEventListener, type ElementListenerOptions, type GroupSelectHandler, type InputState, type InputType, type IntersectionState, type IsSelectedHandler, type ListenerOptions, type MarginType, type MarginValue, type MediaQueryChangeListener, type MediaQueryEventListener, type MediaQueryListenerOptions, type OnChangeHandler, type OnIntersectHandler, type OnIntersectStateHandler, type OnWakeLockRequestError, type ParseValueHandler, type ResetSelectionHandler, type SelectAllHandler, type SelectHandler, type SetSelectionHandler, type StartTimer, type StateDisabledUseDocumentVisibilityOptions, type StateTimerOptions, type StateTimerReturnType, type StopTimer, type TimerHandler, type TimerId, type TimerOptions, type TimerReturnType, type UseConnectionReturnType, type UseDarkModeOptions, type UseDarkModeOutput, type UseDocumentVisibilityOptions, type UseInViewOptions, type UseInViewReturnType, type UseInputOptions, type UseInputOutput, type UseIntervalWhenVisibleReturnType, type UseIntervalWhenVisibleStateReturnType, type UseMediaQueryOptions, type UseMediaQueryStateOptions, type UseSelectionReturnType, type UseWakeLock, type UseWakeLockBase, type UseWakeLockOptions, type ValidateValueHandler, type VisibilityChangeHandler, type WindowEventListener, type WindowListenerOptions, getState, useConnection, useDarkMode, useDebounce, useDeferCallback, useDocumentVisibility, useEffectOnce, useEventListener, useFocusTrap, useInView, useInput, useInterval, useIntervalWhenVisible, useIsClient, useIsFirstRender, useIsPortrait, useIsTouchDevice, useLightInterval, useLightTimeout, useLocalStorage, useMediaQuery, usePagination, useScrollBlock, useSelection, useSessionStorage, useStorage, useTimeout, useUpdateEffect, useWakeLock };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _react = require('react');var _LocalStorage = require('@alessiofrittoli/web-utils/storage/LocalStorage');var _SessionStorage = require('@alessiofrittoli/web-utils/storage/SessionStorage');var H=(e,t,n="local")=>{let r=_react.useCallback.call(void 0, ()=>_nullishCoalesce((n==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).get(e), () => (t)),[n,e,t]),[s,u]=_react.useState.call(void 0, t),i=_react.useCallback.call(void 0, o=>{u(c=>{let l=o instanceof Function?o(c):o;return(typeof window<"u"&&n==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).set(e,l),l})},[n,e]);return _react.useEffect.call(void 0, ()=>{u(r())},[r]),[s,i]};var $=(e,t)=>H(e,t,"local");var Ye=(e,t)=>H(e,t,"session");var j=e=>e?"online":"offline",rt= exports.useConnection =()=>{let[e,t]=_react.useState.call(void 0, j(!0)),n=e==="online",r=e==="offline",s=_react.useCallback.call(void 0, ()=>t(j(navigator.onLine)),[]);return P(["online","offline"],{listener:s,onLoad:s}),{connection:e,isOnline:n,isOffline:r}};var h=()=>{let e=_react.useRef.call(void 0, !0);return e.current?(e.current=!1,!0):e.current};var I=(e,t)=>{let n=h();_react.useEffect.call(void 0, ()=>{if(!n)return e()},t)};var _webutils = require('@alessiofrittoli/web-utils');var R=e=>typeof e=="string"?_webutils.isEmpty.call(void 0, e):!e,C={value:"",isTouched:!1,isValid:!0},B=(e,t)=>{switch(t.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:t.value};case"BLUR":return{...e,value:e.value,isTouched:!R(_nullishCoalesce(e.value, () => ("")))};case"RESET":return C}};var xt=(e={})=>{let{inputRef:t}=e,{initialValue:n}=e,{touchTimeout:r=600}=e,{validate:s,parse:u}=e,{onChange:i}=e,[o,c]=_react.useReducer.call(void 0, B,{...C,value:n}),l=_react.useMemo.call(void 0, ()=>u?u(o.value):o.value,[o.value,u]),a=_react.useMemo.call(void 0, ()=>typeof s=="function"?s(l):!0,[l,s]),{isTouched:p}=o,d=R(l),f=!a&&p||!!n&&!a;I(()=>{let T=setTimeout(()=>{R(l)||c({type:"TOUCHED"})},r);return()=>clearTimeout(T)},[l,r]);let y=_react.useCallback.call(void 0, T=>{let{target:x}=T,{type:v}=x,M=v==="checkbox"?x.checked:x.value;c({type:"CHANGE",value:M}),_optionalChain([i, 'optionalCall', _2 => _2(u?u(M):M)])},[i,u]),S=_react.useCallback.call(void 0, ()=>{c({type:"BLUR"})},[]),O=_react.useCallback.call(void 0, ()=>{c({type:"TOUCHED"})},[]),E=_react.useCallback.call(void 0, T=>{c({type:"CHANGE",value:T})},[]),g=_react.useCallback.call(void 0, ()=>{_optionalChain([t, 'optionalAccess', _3 => _3.current, 'optionalAccess', _4 => _4.focus, 'call', _5 => _5()])},[t]),V=_react.useCallback.call(void 0, ()=>{c({type:"RESET"})},[]);return{value:l,isTouched:p,isValid:a,isEmpty:d,hasError:f,changeHandler:y,blurHandler:S,setValue:E,submit:O,focus:g,reset:V}};var bt=(e,t)=>_react.useCallback.call(void 0, _webutils.deferCallback.call(void 0, e),t);var Lt=e=>{let t=h();_react.useEffect.call(void 0, ()=>{if(t)return e()},[])};var G=()=>{let[e,t]=_react.useState.call(void 0, !1);return _react.useEffect.call(void 0, ()=>t(!0),[]),e};var _helpers = require('@alessiofrittoli/math-utils/helpers');var At=(e={})=>_react.useMemo.call(void 0, ()=>_helpers.paginate.call(void 0, e),[e]);var $t=(e,t=[])=>{let[n,r]=_react.useState.call(void 0, t),s=n.length>0,u=a=>n.includes(a),i=_react.useCallback.call(void 0, a=>r(p=>{let d=new Set(p);return d.has(a)?d.delete(a):d.add(a),Array.from(d.values())}),[]),o=_react.useCallback.call(void 0, a=>{r(p=>{if(p.length===0)return[a];let d=[...e],f=d.indexOf(p.at(0)),y=d.indexOf(a);if(f>y){let S=[...d].reverse(),O=S.indexOf(p.at(0)),E=S.indexOf(a);return S.slice(O,E+1)}return d.slice(f,y+1)})},[e]),c=_react.useCallback.call(void 0, ()=>{r(e)},[e]),l=_react.useCallback.call(void 0, a=>r(a?t:[]),[t]);return{selection:n,hasSelection:s,isSelected:u,setSelection:r,select:i,groupSelect:o,selectAll:c,resetSelection:l}};var _browserapi = require('@alessiofrittoli/web-utils/browser-api');function k(e,t={}){let{updateState:n=!0,onChange:r}=t,[s,u]=_react.useState.call(void 0, _browserapi.getMediaMatches.call(void 0, e)),i=_react.useCallback.call(void 0, ()=>{let o=_browserapi.getMediaMatches.call(void 0, e);n&&u(o),_optionalChain([r, 'optionalCall', _6 => _6(o)])},[e,n,r]);if(_react.useEffect.call(void 0, ()=>{let o=window.matchMedia(e),{matches:c}=o;return n&&u(c),_optionalChain([r, 'optionalCall', _7 => _7(c)]),o.addEventListener("change",i),()=>{o.removeEventListener("change",i)}},[e,n,r,i]),!!n)return s}var Yt=(e={})=>{let t=G(),n=k("(prefers-color-scheme: dark)"),{initial:r=n,docClassNames:s=[]}=e,[u,i]=$("dark-mode",r),o=_nullishCoalesce(u, () => (n)),[c,l]=s,a=_react.useRef.call(void 0, {light:"",dark:""});return I(()=>{i(n)},[n,i]),_react.useEffect.call(void 0, ()=>{c&&document.documentElement.classList.toggle(c,o),l&&document.documentElement.classList.toggle(l,!o)},[o,c,l]),_react.useEffect.call(void 0, ()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(p=>{let d=p.getAttribute("media"),f=p.getAttribute("content");if(f){if(!d||d==="(prefers-color-scheme: light)"){a.current.light=f;return}a.current.dark=f}})},[]),I(()=>{let p=a.current.dark,d=a.current.light;u&&!p||!u&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(f=>{f.setAttribute("content",u?p:d)})},[u]),{isDarkMode:t?o:!1,isDarkOS:t?n:!1,toggleDarkMode:_react.useCallback.call(void 0, ()=>i(p=>!p),[i]),enableDarkMode:_react.useCallback.call(void 0, ()=>i(!0),[i]),disableDarkMode:_react.useCallback.call(void 0, ()=>i(!1),[i])}};function P(e,t){let{target:n,query:r,options:s,listener:u,onLoad:i,onCleanUp:o}=t;_react.useEffect.call(void 0, ()=>{let c=Array.isArray(e)?e:[e],l=_nullishCoalesce((r?window.matchMedia(r):n&&"current"in n?n.current:n), () => (window));if(l.addEventListener)return _optionalChain([i, 'optionalCall', _8 => _8()]),c.map(a=>{l.addEventListener(a,u,s)}),()=>{c.map(a=>{l.removeEventListener(a,u,s)}),_optionalChain([o, 'optionalCall', _9 => _9()])}},[e,n,r,s,u,i,o])}var _device = require('@alessiofrittoli/web-utils/device');var an=()=>k(_device.portraitMediaQuery);var He=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),pn= exports.useFocusTrap =e=>{let t=_react.useMemo.call(void 0, ()=>_optionalChain([e, 'optionalAccess', _10 => _10.current]),[e]),[n,r]=_react.useState.call(void 0, !1),s=_react.useRef.call(void 0, null),u=_react.useCallback.call(void 0, o=>{s.current=document.activeElement;let c=o||t||!1;if(c)return r(c)},[t]),i=_react.useCallback.call(void 0, ()=>{_optionalChain([s, 'access', _11 => _11.current, 'optionalAccess', _12 => _12.focus, 'call', _13 => _13()]),r(!1)},[]);return _react.useEffect.call(void 0, ()=>{if(!n)return;let o=c=>{if(c.key!=="Tab")return;let l=Array.from(n.querySelectorAll(He)),a=l.at(0),p=l.at(-1);if(!c.shiftKey){document.activeElement===p&&(c.preventDefault(),_optionalChain([a, 'optionalAccess', _14 => _14.focus, 'call', _15 => _15()]));return}document.activeElement===a&&(c.preventDefault(),_optionalChain([p, 'optionalAccess', _16 => _16.focus, 'call', _17 => _17()]))};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[n]),[u,i]};var Tn=(e,t={})=>{let{initial:n=!1,once:r,amount:s,margin:u,root:i,enable:o=!0}=t,{onEnter:c,onExit:l,onIntersect:a}=t,p=_react.useRef.call(void 0, !0),[d,f]=_react.useState.call(void 0, n),[y,S]=_react.useState.call(void 0, o),O=_react.useRef.call(void 0, null),E=_react.useRef.call(void 0, !1),g=_react.useMemo.call(void 0, ()=>{if(!y||typeof IntersectionObserver>"u")return;let V=s==="all"?1:s==="some"?.5:s;try{return new IntersectionObserver(async([T],x)=>{if(!T)return;let v=T.isIntersecting;try{if(E.current=!v&&!!O.current,v&&c&&await c({entry:T,observer:x}),E.current&&l&&await l({entry:T,observer:x}),a&&(v||!v&&O.current!=null)){let M={isEntering:v,isExiting:E.current};await a({entry:T,observer:x,...M})}if(O.current=v,!p.current)return;f(v)}catch(M){console.error(M)}v&&r&&x.disconnect()},{root:i||void 0,rootMargin:u,threshold:V})}catch(T){console.error(T)}},[i,u,s,r,y,c,l,a]);return _react.useEffect.call(void 0, ()=>{if(p.current=!0,!(!y||!e.current||!g))return g.observe(e.current),()=>{p.current=!1,g.disconnect()}},[e,g,y]),{inView:d,enabled:y,observer:g,isExiting:E.current,setInView:f,setEnabled:S}};var _dom = require('@alessiofrittoli/web-utils/dom');var Sn=e=>{let t=_react.useMemo.call(void 0, ()=>_optionalChain([e, 'optionalAccess', _18 => _18.current]),[e]),n=_react.useCallback.call(void 0, ()=>_dom.blockScroll.call(void 0, t||void 0),[t]),r=_react.useCallback.call(void 0, ()=>_dom.restoreScroll.call(void 0, t||void 0),[t]);return[n,r]};var Y=(e,t={})=>{let{delay:n=1,args:r}=t;_react.useEffect.call(void 0, ()=>{let s=setTimeout(e,n,...r||[]);return()=>clearTimeout(s)},[n,r,e])};var Rn=(e,t=500)=>{let[n,r]=_react.useState.call(void 0, e),s=_react.useMemo.call(void 0, ()=>[e],[e]);return Y(r,{delay:t,args:s}),n};function Z(e,t={}){let{delay:n=1,args:r,autoplay:s=!0,runOnStart:u=!1,updateState:i=!1}=t,o=_react.useRef.call(void 0, void 0),[c,l]=_react.useState.call(void 0, s),a=_react.useCallback.call(void 0, ()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),p=_react.useCallback.call(void 0, ()=>{let f=a();return u&&(r?e(...r):e()),o.current=setInterval(e,n,...r||[]),!f&&i&&l(!0),o.current},[n,r,i,u,e,a]),d=_react.useCallback.call(void 0, ()=>{a()&&i&&l(!1)},[i,a]);return _react.useEffect.call(void 0, ()=>{if(s)return p(),d},[s,p,d]),i?{isActive:c,start:p,stop:d}:{start:p,stop:d}}var Un=(e,t={})=>{let{delay:n=1,args:r}=t;_react.useEffect.call(void 0, ()=>{let s=setInterval(e,n,...r||[]);return()=>clearInterval(s)},[n,r,e])};function Fn(e,t={}){let{autoplay:n=!0}=t,r=Z(e,{autoplay:!1,...t}),{start:s,stop:u}=r,i=_react.useCallback.call(void 0, ()=>document.hidden?u():s(),[s,u]),o=_react.useCallback.call(void 0, ()=>{if(document.addEventListener("visibilitychange",i),!document.hidden)return s()},[s,i]),c=_react.useCallback.call(void 0, ()=>{u(),document.removeEventListener("visibilitychange",i)},[u,i]);return _react.useEffect.call(void 0, ()=>{if(n)return o(),c},[n,o,c]),{...r,start:o,stop:c}}function Bn(e,t={}){let{delay:n=1,args:r,autoplay:s=!0,runOnStart:u=!1,updateState:i=!1}=t,o=_react.useRef.call(void 0, void 0),[c,l]=_react.useState.call(void 0, s),a=_react.useCallback.call(void 0, ()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),p=_react.useCallback.call(void 0, ()=>{let f=a();return u&&(r?e(...r):e()),o.current=setTimeout(()=>{if(o.current=void 0,i&&l(!1),r)return e(...r);e()},n),!f&&i&&l(!0),o.current},[n,r,i,u,e,a]),d=_react.useCallback.call(void 0, ()=>{a()&&i&&l(!1)},[i,a]);return _react.useEffect.call(void 0, ()=>{if(s)return p(),d},[s,p,d]),i?{isActive:c,start:p,stop:d}:{start:p,stop:d}}exports.getState = j; exports.useConnection = rt; exports.useDarkMode = Yt; exports.useDebounce = Rn; exports.useDeferCallback = bt; exports.useEffectOnce = Lt; exports.useEventListener = P; exports.useFocusTrap = pn; exports.useInView = Tn; exports.useInput = xt; exports.useInterval = Z; exports.useIntervalWhenVisible = Fn; exports.useIsClient = G; exports.useIsFirstRender = h; exports.useIsPortrait = an; exports.useLightInterval = Un; exports.useLightTimeout = Y; exports.useLocalStorage = $; exports.useMediaQuery = k; exports.usePagination = At; exports.useScrollBlock = Sn; exports.useSelection = $t; exports.useSessionStorage = Ye; exports.useStorage = H; exports.useTimeout = Bn; exports.useUpdateEffect = I;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _react = require('react');var _LocalStorage = require('@alessiofrittoli/web-utils/storage/LocalStorage');var _SessionStorage = require('@alessiofrittoli/web-utils/storage/SessionStorage');var I=(e,n,r="local")=>{let t=_react.useCallback.call(void 0, ()=>_nullishCoalesce((r==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).get(e), () => (n)),[r,e,n]),[i,a]=_react.useState.call(void 0, n),s=_react.useCallback.call(void 0, o=>{a(c=>{let p=o instanceof Function?o(c):o;return(typeof window<"u"&&r==="local"?_LocalStorage.LocalStorage:_SessionStorage.SessionStorage).set(e,p),p})},[r,e]);return _react.useEffect.call(void 0, ()=>{a(t())},[t]),[i,s]};var $=(e,n)=>I(e,n,"local");var at=(e,n)=>I(e,n,"session");var j=e=>e?"online":"offline",dt= exports.useConnection =()=>{let[e,n]=_react.useState.call(void 0, j(!0)),r=e==="online",t=e==="offline",i=_react.useCallback.call(void 0, ()=>n(j(navigator.onLine)),[]);return B(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:r,isOffline:t}};var V=()=>{let e=_react.useRef.call(void 0, !0);return e.current?(e.current=!1,!0):e.current};var L=(e,n)=>{let r=V();_react.useEffect.call(void 0, ()=>{if(!r)return e()},n)};var _webutils = require('@alessiofrittoli/web-utils');var H=e=>typeof e=="string"?_webutils.isEmpty.call(void 0, e):!e,w={value:"",isTouched:!1,isValid:!0},N=(e,n)=>{switch(n.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:n.value};case"BLUR":return{...e,value:e.value,isTouched:!H(_nullishCoalesce(e.value, () => ("")))};case"RESET":return w}};var It=(e={})=>{let{inputRef:n}=e,{initialValue:r}=e,{touchTimeout:t=600}=e,{validate:i,parse:a}=e,{onChange:s}=e,[o,c]=_react.useReducer.call(void 0, N,{...w,value:r}),p=_react.useMemo.call(void 0, ()=>a?a(o.value):o.value,[o.value,a]),u=_react.useMemo.call(void 0, ()=>typeof i=="function"?i(p):!0,[p,i]),{isTouched:l}=o,d=H(p),f=!u&&l||!!r&&!u;L(()=>{let T=setTimeout(()=>{H(p)||c({type:"TOUCHED"})},t);return()=>clearTimeout(T)},[p,t]);let y=_react.useCallback.call(void 0, T=>{let{target:x}=T,{type:v}=x,k=v==="checkbox"?x.checked:x.value;c({type:"CHANGE",value:k}),_optionalChain([s, 'optionalCall', _2 => _2(a?a(k):k)])},[s,a]),S=_react.useCallback.call(void 0, ()=>{c({type:"BLUR"})},[]),b=_react.useCallback.call(void 0, ()=>{c({type:"TOUCHED"})},[]),E=_react.useCallback.call(void 0, T=>{c({type:"CHANGE",value:T})},[]),O=_react.useCallback.call(void 0, ()=>{_optionalChain([n, 'optionalAccess', _3 => _3.current, 'optionalAccess', _4 => _4.focus, 'call', _5 => _5()])},[n]),D=_react.useCallback.call(void 0, ()=>{c({type:"RESET"})},[]);return{value:p,isTouched:l,isValid:u,isEmpty:d,hasError:f,changeHandler:y,blurHandler:S,setValue:E,submit:b,focus:O,reset:D}};var Dt=(e,n)=>_react.useCallback.call(void 0, _webutils.deferCallback.call(void 0, e),n);var R=e=>{let n=V();_react.useEffect.call(void 0, ()=>{if(n)return e()},[])};var _=()=>{let[e,n]=_react.useState.call(void 0, !1);return _react.useEffect.call(void 0, ()=>n(!0),[]),e};var _helpers = require('@alessiofrittoli/math-utils/helpers');var Bt=(e={})=>_react.useMemo.call(void 0, ()=>_helpers.paginate.call(void 0, e),[e]);var zt=(e,n=[])=>{let[r,t]=_react.useState.call(void 0, n),i=r.length>0,a=u=>r.includes(u),s=_react.useCallback.call(void 0, u=>t(l=>{let d=new Set(l);return d.has(u)?d.delete(u):d.add(u),Array.from(d.values())}),[]),o=_react.useCallback.call(void 0, u=>{t(l=>{if(l.length===0)return[u];let d=[...e],f=d.indexOf(l.at(0)),y=d.indexOf(u);if(f>y){let S=[...d].reverse(),b=S.indexOf(l.at(0)),E=S.indexOf(u);return S.slice(b,E+1)}return d.slice(f,y+1)})},[e]),c=_react.useCallback.call(void 0, ()=>{t(e)},[e]),p=_react.useCallback.call(void 0, u=>t(u?n:[]),[n]);return{selection:r,hasSelection:i,isSelected:a,setSelection:t,select:s,groupSelect:o,selectAll:c,resetSelection:p}};var _browserapi = require('@alessiofrittoli/web-utils/browser-api');function M(e,n={}){let{updateState:r=!0,onChange:t}=n,[i,a]=_react.useState.call(void 0, _browserapi.getMediaMatches.call(void 0, e)),s=_react.useCallback.call(void 0, ()=>{let o=_browserapi.getMediaMatches.call(void 0, e);r&&a(o),_optionalChain([t, 'optionalCall', _6 => _6(o)])},[e,r,t]);if(_react.useEffect.call(void 0, ()=>{let o=window.matchMedia(e),{matches:c}=o;return r&&a(c),_optionalChain([t, 'optionalCall', _7 => _7(c)]),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,r,t,s]),!!r)return i}var an=(e={})=>{let n=_(),r=M("(prefers-color-scheme: dark)"),{initial:t=r,docClassNames:i=[]}=e,[a,s]=$("dark-mode",t),o=_nullishCoalesce(a, () => (r)),[c,p]=i,u=_react.useRef.call(void 0, {light:"",dark:""});return L(()=>{s(r)},[r,s]),_react.useEffect.call(void 0, ()=>{c&&document.documentElement.classList.toggle(c,o),p&&document.documentElement.classList.toggle(p,!o)},[o,c,p]),_react.useEffect.call(void 0, ()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(l=>{let d=l.getAttribute("media"),f=l.getAttribute("content");if(f){if(!d||d==="(prefers-color-scheme: light)"){u.current.light=f;return}u.current.dark=f}})},[]),L(()=>{let l=u.current.dark,d=u.current.light;a&&!l||!a&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(f=>{f.setAttribute("content",a?l:d)})},[a]),{isDarkMode:n?o:!1,isDarkOS:n?r:!1,toggleDarkMode:_react.useCallback.call(void 0, ()=>s(l=>!l),[s]),enableDarkMode:_react.useCallback.call(void 0, ()=>s(!0),[s]),disableDarkMode:_react.useCallback.call(void 0, ()=>s(!1),[s])}};function X(e={}){let{updateState:n=!0,onVisibilityChange:r}=e,[t,i]=_react.useState.call(void 0, !1),a=_react.useCallback.call(void 0, ()=>{let s=!document.hidden;n&&i(s),_optionalChain([r, 'optionalCall', _8 => _8(s)])},[n,r]);if(R(()=>{n&&i(!document.hidden)}),_react.useEffect.call(void 0, ()=>(document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)),[a]),n)return t}function B(e,n){let{target:r,query:t,options:i,listener:a,onLoad:s,onCleanUp:o}=n;_react.useEffect.call(void 0, ()=>{let c=Array.isArray(e)?e:[e],p=_nullishCoalesce((t?window.matchMedia(t):r&&"current"in r?r.current:r), () => (window));if(p.addEventListener)return _optionalChain([s, 'optionalCall', _9 => _9()]),c.map(u=>{p.addEventListener(u,a,i)}),()=>{c.map(u=>{p.removeEventListener(u,a,i)}),_optionalChain([o, 'optionalCall', _10 => _10()])}},[e,r,t,i,a,s,o])}var _device = require('@alessiofrittoli/web-utils/device');var xn=()=>M(_device.portraitMediaQuery);var kn=()=>M("(pointer: coarse)");var Vn=(e={})=>{let{onMount:n=!0,onError:r}=e,[t,i]=_react.useState.call(void 0, null),a=_react.useRef.call(void 0, n),s=t&&!t.released||!1,o=_react.useCallback.call(void 0, async l=>!t||t.released?navigator.wakeLock.request("screen").then(d=>{i(d),_optionalChain([l, 'optionalCall', _11 => _11()])}).catch(r||console.error):t,[t,r]),c=_react.useCallback.call(void 0, async()=>_optionalChain([t, 'optionalAccess', _12 => _12.release, 'call', _13 => _13()]),[t]),p=_react.useCallback.call(void 0, async()=>{o(()=>{a.current=!0})},[o]),u=_react.useCallback.call(void 0, async()=>{a.current=!1,c()},[c]);return X({updateState:!1,onVisibilityChange:_react.useCallback.call(void 0, l=>{if(l&&!s&&a.current)return o();if(!l)return c()},[s,o,c])}),R(()=>{s||!n||o()}),_react.useEffect.call(void 0, ()=>{if(!t)return;let l=()=>{t.released&&i(null)};return t.addEventListener("release",l),()=>{t.removeEventListener("release",l),!t.released&&t.release()}},[t]),{wakeLock:t,enabled:s,requestWakeLock:p,releaseWakeLock:u}};var Ue=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),Dn= exports.useFocusTrap =e=>{let n=_react.useMemo.call(void 0, ()=>_optionalChain([e, 'optionalAccess', _14 => _14.current]),[e]),[r,t]=_react.useState.call(void 0, !1),i=_react.useRef.call(void 0, null),a=_react.useCallback.call(void 0, o=>{i.current=document.activeElement;let c=o||n||!1;if(c)return t(c)},[n]),s=_react.useCallback.call(void 0, ()=>{_optionalChain([i, 'access', _15 => _15.current, 'optionalAccess', _16 => _16.focus, 'call', _17 => _17()]),t(!1)},[]);return _react.useEffect.call(void 0, ()=>{if(!r)return;let o=c=>{if(c.key!=="Tab")return;let p=Array.from(r.querySelectorAll(Ue)),u=p.at(0),l=p.at(-1);if(!c.shiftKey){document.activeElement===l&&(c.preventDefault(),_optionalChain([u, 'optionalAccess', _18 => _18.focus, 'call', _19 => _19()]));return}document.activeElement===u&&(c.preventDefault(),_optionalChain([l, 'optionalAccess', _20 => _20.focus, 'call', _21 => _21()]))};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[r]),[a,s]};var Kn=(e,n={})=>{let{initial:r=!1,once:t,amount:i,margin:a,root:s,enable:o=!0}=n,{onEnter:c,onExit:p,onIntersect:u}=n,l=_react.useRef.call(void 0, !0),[d,f]=_react.useState.call(void 0, r),[y,S]=_react.useState.call(void 0, o),b=_react.useRef.call(void 0, null),E=_react.useRef.call(void 0, !1),O=_react.useMemo.call(void 0, ()=>{if(!y||typeof IntersectionObserver>"u")return;let D=i==="all"?1:i==="some"?.5:i;try{return new IntersectionObserver(async([T],x)=>{if(!T)return;let v=T.isIntersecting;try{if(E.current=!v&&!!b.current,v&&c&&await c({entry:T,observer:x}),E.current&&p&&await p({entry:T,observer:x}),u&&(v||!v&&b.current!=null)){let k={isEntering:v,isExiting:E.current};await u({entry:T,observer:x,...k})}if(b.current=v,!l.current)return;f(v)}catch(k){console.error(k)}v&&t&&x.disconnect()},{root:s||void 0,rootMargin:a,threshold:D})}catch(T){console.error(T)}},[s,a,i,t,y,c,p,u]);return _react.useEffect.call(void 0, ()=>{if(l.current=!0,!(!y||!e.current||!O))return O.observe(e.current),()=>{l.current=!1,O.disconnect()}},[e,O,y]),{inView:d,enabled:y,observer:O,isExiting:E.current,setInView:f,setEnabled:S}};var _dom = require('@alessiofrittoli/web-utils/dom');var Pn=e=>{let n=_react.useMemo.call(void 0, ()=>_optionalChain([e, 'optionalAccess', _22 => _22.current]),[e]),r=_react.useCallback.call(void 0, ()=>_dom.blockScroll.call(void 0, n||void 0),[n]),t=_react.useCallback.call(void 0, ()=>_dom.restoreScroll.call(void 0, n||void 0),[n]);return[r,t]};var te=(e,n={})=>{let{delay:r=1,args:t}=n;_react.useEffect.call(void 0, ()=>{let i=setTimeout(e,r,...t||[]);return()=>clearTimeout(i)},[r,t,e])};var Jn=(e,n=500)=>{let[r,t]=_react.useState.call(void 0, e),i=_react.useMemo.call(void 0, ()=>[e],[e]);return te(t,{delay:n,args:i}),r};function ne(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[c,p]=_react.useState.call(void 0, i),u=_react.useCallback.call(void 0, ()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),l=_react.useCallback.call(void 0, ()=>{let f=u();return a&&(t?e(...t):e()),o.current=setInterval(e,r,...t||[]),!f&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=_react.useCallback.call(void 0, ()=>{u()&&s&&p(!1)},[s,u]);return _react.useEffect.call(void 0, ()=>{if(i)return l(),d},[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}var rr=(e,n={})=>{let{delay:r=1,args:t}=n;_react.useEffect.call(void 0, ()=>{let i=setInterval(e,r,...t||[]);return()=>clearInterval(i)},[r,t,e])};function cr(e,n={}){let{autoplay:r=!0}=n,t=ne(e,{autoplay:!1,...n}),{start:i,stop:a}=t,s=_react.useCallback.call(void 0, ()=>document.hidden?a():i(),[i,a]),o=_react.useCallback.call(void 0, ()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),c=_react.useCallback.call(void 0, ()=>{a(),document.removeEventListener("visibilitychange",s)},[a,s]);return _react.useEffect.call(void 0, ()=>{if(r)return o(),c},[r,o,c]),{...t,start:o,stop:c}}function dr(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=_react.useRef.call(void 0, void 0),[c,p]=_react.useState.call(void 0, i),u=_react.useCallback.call(void 0, ()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),l=_react.useCallback.call(void 0, ()=>{let f=u();return a&&(t?e(...t):e()),o.current=setTimeout(()=>{if(o.current=void 0,s&&p(!1),t)return e(...t);e()},r),!f&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=_react.useCallback.call(void 0, ()=>{u()&&s&&p(!1)},[s,u]);return _react.useEffect.call(void 0, ()=>{if(i)return l(),d},[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}exports.getState = j; exports.useConnection = dt; exports.useDarkMode = an; exports.useDebounce = Jn; exports.useDeferCallback = Dt; exports.useDocumentVisibility = X; exports.useEffectOnce = R; exports.useEventListener = B; exports.useFocusTrap = Dn; exports.useInView = Kn; exports.useInput = It; exports.useInterval = ne; exports.useIntervalWhenVisible = cr; exports.useIsClient = _; exports.useIsFirstRender = V; exports.useIsPortrait = xn; exports.useIsTouchDevice = kn; exports.useLightInterval = rr; exports.useLightTimeout = te; exports.useLocalStorage = $; exports.useMediaQuery = M; exports.usePagination = Bt; exports.useScrollBlock = Pn; exports.useSelection = zt; exports.useSessionStorage = at; exports.useStorage = I; exports.useTimeout = dr; exports.useUpdateEffect = L; exports.useWakeLock = Vn;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useCallback as Q,useEffect as te,useState as ne}from"react";import{LocalStorage as F}from"@alessiofrittoli/web-utils/storage/LocalStorage";import{SessionStorage as $}from"@alessiofrittoli/web-utils/storage/SessionStorage";var h=(e,t,n="local")=>{let r=Q(()=>(n==="local"?F:$).get(e)??t,[n,e,t]),[s,u]=ne(t),i=Q(o=>{u(c=>{let l=o instanceof Function?o(c):o;return(typeof window<"u"&&n==="local"?F:$).set(e,l),l})},[n,e]);return te(()=>{u(r())},[r]),[s,i]};var j=(e,t)=>h(e,t,"local");var Ze=(e,t)=>h(e,t,"session");import{useCallback as re,useState as oe}from"react";var P=e=>e?"online":"offline",ot=()=>{let[e,t]=oe(P(!0)),n=e==="online",r=e==="offline",s=re(()=>t(P(navigator.onLine)),[]);return B(["online","offline"],{listener:s,onLoad:s}),{connection:e,isOnline:n,isOffline:r}};import{useCallback as w,useEffect as z,useRef as Se}from"react";import{useCallback as I,useMemo as G,useReducer as ue}from"react";import{useEffect as ie}from"react";import{useRef as se}from"react";var R=()=>{let e=se(!0);return e.current?(e.current=!1,!0):e.current};var H=(e,t)=>{let n=R();ie(()=>{if(!n)return e()},t)};import{isEmpty as ae}from"@alessiofrittoli/web-utils";var L=e=>typeof e=="string"?ae(e):!e,D={value:"",isTouched:!1,isValid:!0},N=(e,t)=>{switch(t.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:t.value};case"BLUR":return{...e,value:e.value,isTouched:!L(e.value??"")};case"RESET":return D}};var St=(e={})=>{let{inputRef:t}=e,{initialValue:n}=e,{touchTimeout:r=600}=e,{validate:s,parse:u}=e,{onChange:i}=e,[o,c]=ue(N,{...D,value:n}),l=G(()=>u?u(o.value):o.value,[o.value,u]),a=G(()=>typeof s=="function"?s(l):!0,[l,s]),{isTouched:p}=o,d=L(l),T=!a&&p||!!n&&!a;H(()=>{let y=setTimeout(()=>{L(l)||c({type:"TOUCHED"})},r);return()=>clearTimeout(y)},[l,r]);let v=I(y=>{let{target:S}=y,{type:E}=S,b=E==="checkbox"?S.checked:S.value;c({type:"CHANGE",value:b}),i?.(u?u(b):b)},[i,u]),O=I(()=>{c({type:"BLUR"})},[]),g=I(()=>{c({type:"TOUCHED"})},[]),x=I(y=>{c({type:"CHANGE",value:y})},[]),M=I(()=>{t?.current?.focus()},[t]),C=I(()=>{c({type:"RESET"})},[]);return{value:l,isTouched:p,isValid:a,isEmpty:d,hasError:T,changeHandler:v,blurHandler:O,setValue:x,submit:g,focus:M,reset:C}};import{useCallback as ce}from"react";import{deferCallback as le}from"@alessiofrittoli/web-utils";var It=(e,t)=>ce(le(e),t);import{useEffect as pe}from"react";var kt=e=>{let t=R();pe(()=>{if(t)return e()},[])};import{useEffect as de,useState as me}from"react";var q=()=>{let[e,t]=me(!1);return de(()=>t(!0),[]),e};import{useMemo as fe}from"react";import{paginate as Te}from"@alessiofrittoli/math-utils/helpers";var Wt=(e={})=>fe(()=>Te(e),[e]);import{useCallback as k,useState as ye}from"react";var jt=(e,t=[])=>{let[n,r]=ye(t),s=n.length>0,u=a=>n.includes(a),i=k(a=>r(p=>{let d=new Set(p);return d.has(a)?d.delete(a):d.add(a),Array.from(d.values())}),[]),o=k(a=>{r(p=>{if(p.length===0)return[a];let d=[...e],T=d.indexOf(p.at(0)),v=d.indexOf(a);if(T>v){let O=[...d].reverse(),g=O.indexOf(p.at(0)),x=O.indexOf(a);return O.slice(g,x+1)}return d.slice(T,v+1)})},[e]),c=k(()=>{r(e)},[e]),l=k(a=>r(a?t:[]),[t]);return{selection:n,hasSelection:s,isSelected:u,setSelection:r,select:i,groupSelect:o,selectAll:c,resetSelection:l}};import{useCallback as ve,useEffect as Ee,useState as xe}from"react";import{getMediaMatches as _}from"@alessiofrittoli/web-utils/browser-api";function V(e,t={}){let{updateState:n=!0,onChange:r}=t,[s,u]=xe(_(e)),i=ve(()=>{let o=_(e);n&&u(o),r?.(o)},[e,n,r]);if(Ee(()=>{let o=window.matchMedia(e),{matches:c}=o;return n&&u(c),r?.(c),o.addEventListener("change",i),()=>{o.removeEventListener("change",i)}},[e,n,r,i]),!!n)return s}var Zt=(e={})=>{let t=q(),n=V("(prefers-color-scheme: dark)"),{initial:r=n,docClassNames:s=[]}=e,[u,i]=j("dark-mode",r),o=u??n,[c,l]=s,a=Se({light:"",dark:""});return H(()=>{i(n)},[n,i]),z(()=>{c&&document.documentElement.classList.toggle(c,o),l&&document.documentElement.classList.toggle(l,!o)},[o,c,l]),z(()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(p=>{let d=p.getAttribute("media"),T=p.getAttribute("content");if(T){if(!d||d==="(prefers-color-scheme: light)"){a.current.light=T;return}a.current.dark=T}})},[]),H(()=>{let p=a.current.dark,d=a.current.light;u&&!p||!u&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(T=>{T.setAttribute("content",u?p:d)})},[u]),{isDarkMode:t?o:!1,isDarkOS:t?n:!1,toggleDarkMode:w(()=>i(p=>!p),[i]),enableDarkMode:w(()=>i(!0),[i]),disableDarkMode:w(()=>i(!1),[i])}};import{useEffect as Oe}from"react";function B(e,t){let{target:n,query:r,options:s,listener:u,onLoad:i,onCleanUp:o}=t;Oe(()=>{let c=Array.isArray(e)?e:[e],l=(r?window.matchMedia(r):n&&"current"in n?n.current:n)??window;if(l.addEventListener)return i?.(),c.map(a=>{l.addEventListener(a,u,s)}),()=>{c.map(a=>{l.removeEventListener(a,u,s)}),o?.()}},[e,n,r,s,u,i,o])}import{portraitMediaQuery as ge}from"@alessiofrittoli/web-utils/device";var un=()=>V(ge);import{useCallback as J,useEffect as Me,useMemo as be,useRef as Ie,useState as He}from"react";var he=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),dn=e=>{let t=be(()=>e?.current,[e]),[n,r]=He(!1),s=Ie(null),u=J(o=>{s.current=document.activeElement;let c=o||t||!1;if(c)return r(c)},[t]),i=J(()=>{s.current?.focus(),r(!1)},[]);return Me(()=>{if(!n)return;let o=c=>{if(c.key!=="Tab")return;let l=Array.from(n.querySelectorAll(he)),a=l.at(0),p=l.at(-1);if(!c.shiftKey){document.activeElement===p&&(c.preventDefault(),a?.focus());return}document.activeElement===a&&(c.preventDefault(),p?.focus())};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[n]),[u,i]};import{useEffect as Re,useMemo as Le,useRef as U,useState as X}from"react";var yn=(e,t={})=>{let{initial:n=!1,once:r,amount:s,margin:u,root:i,enable:o=!0}=t,{onEnter:c,onExit:l,onIntersect:a}=t,p=U(!0),[d,T]=X(n),[v,O]=X(o),g=U(null),x=U(!1),M=Le(()=>{if(!v||typeof IntersectionObserver>"u")return;let C=s==="all"?1:s==="some"?.5:s;try{return new IntersectionObserver(async([y],S)=>{if(!y)return;let E=y.isIntersecting;try{if(x.current=!E&&!!g.current,E&&c&&await c({entry:y,observer:S}),x.current&&l&&await l({entry:y,observer:S}),a&&(E||!E&&g.current!=null)){let b={isEntering:E,isExiting:x.current};await a({entry:y,observer:S,...b})}if(g.current=E,!p.current)return;T(E)}catch(b){console.error(b)}E&&r&&S.disconnect()},{root:i||void 0,rootMargin:u,threshold:C})}catch(y){console.error(y)}},[i,u,s,r,v,c,l,a]);return Re(()=>{if(p.current=!0,!(!v||!e.current||!M))return M.observe(e.current),()=>{p.current=!1,M.disconnect()}},[e,M,v]),{inView:d,enabled:v,observer:M,isExiting:x.current,setInView:T,setEnabled:O}};import{useCallback as Y,useMemo as ke}from"react";import{blockScroll as Ve,restoreScroll as Ce}from"@alessiofrittoli/web-utils/dom";var On=e=>{let t=ke(()=>e?.current,[e]),n=Y(()=>Ve(t||void 0),[t]),r=Y(()=>Ce(t||void 0),[t]);return[n,r]};import{useMemo as we,useState as Ue}from"react";import{useEffect as De}from"react";var Z=(e,t={})=>{let{delay:n=1,args:r}=t;De(()=>{let s=setTimeout(e,n,...r||[]);return()=>clearTimeout(s)},[n,r,e])};var Ln=(e,t=500)=>{let[n,r]=Ue(e),s=we(()=>[e],[e]);return Z(r,{delay:t,args:s}),n};import{useCallback as K,useEffect as Ke,useRef as Ae,useState as We}from"react";function ee(e,t={}){let{delay:n=1,args:r,autoplay:s=!0,runOnStart:u=!1,updateState:i=!1}=t,o=Ae(void 0),[c,l]=We(s),a=K(()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),p=K(()=>{let T=a();return u&&(r?e(...r):e()),o.current=setInterval(e,n,...r||[]),!T&&i&&l(!0),o.current},[n,r,i,u,e,a]),d=K(()=>{a()&&i&&l(!1)},[i,a]);return Ke(()=>{if(s)return p(),d},[s,p,d]),i?{isActive:c,start:p,stop:d}:{start:p,stop:d}}import{useEffect as Qe}from"react";var Kn=(e,t={})=>{let{delay:n=1,args:r}=t;Qe(()=>{let s=setInterval(e,n,...r||[]);return()=>clearInterval(s)},[n,r,e])};import{useCallback as A,useEffect as Fe}from"react";function $n(e,t={}){let{autoplay:n=!0}=t,r=ee(e,{autoplay:!1,...t}),{start:s,stop:u}=r,i=A(()=>document.hidden?u():s(),[s,u]),o=A(()=>{if(document.addEventListener("visibilitychange",i),!document.hidden)return s()},[s,i]),c=A(()=>{u(),document.removeEventListener("visibilitychange",i)},[u,i]);return Fe(()=>{if(n)return o(),c},[n,o,c]),{...r,start:o,stop:c}}import{useCallback as W,useEffect as $e,useRef as je,useState as Pe}from"react";function Nn(e,t={}){let{delay:n=1,args:r,autoplay:s=!0,runOnStart:u=!1,updateState:i=!1}=t,o=je(void 0),[c,l]=Pe(s),a=W(()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),p=W(()=>{let T=a();return u&&(r?e(...r):e()),o.current=setTimeout(()=>{if(o.current=void 0,i&&l(!1),r)return e(...r);e()},n),!T&&i&&l(!0),o.current},[n,r,i,u,e,a]),d=W(()=>{a()&&i&&l(!1)},[i,a]);return $e(()=>{if(s)return p(),d},[s,p,d]),i?{isActive:c,start:p,stop:d}:{start:p,stop:d}}export{P as getState,ot as useConnection,Zt as useDarkMode,Ln as useDebounce,It as useDeferCallback,kt as useEffectOnce,B as useEventListener,dn as useFocusTrap,yn as useInView,St as useInput,ee as useInterval,$n as useIntervalWhenVisible,q as useIsClient,R as useIsFirstRender,un as useIsPortrait,Kn as useLightInterval,Z as useLightTimeout,j as useLocalStorage,V as useMediaQuery,Wt as usePagination,On as useScrollBlock,jt as useSelection,Ze as useSessionStorage,h as useStorage,Nn as useTimeout,H as useUpdateEffect};
|
|
1
|
+
import{useCallback as q,useEffect as oe,useState as se}from"react";import{LocalStorage as P}from"@alessiofrittoli/web-utils/storage/LocalStorage";import{SessionStorage as $}from"@alessiofrittoli/web-utils/storage/SessionStorage";var V=(e,n,r="local")=>{let t=q(()=>(r==="local"?P:$).get(e)??n,[r,e,n]),[i,a]=se(n),s=q(o=>{a(c=>{let p=o instanceof Function?o(c):o;return(typeof window<"u"&&r==="local"?P:$).set(e,p),p})},[r,e]);return oe(()=>{a(t())},[t]),[i,s]};var j=(e,n)=>V(e,n,"local");var ct=(e,n)=>V(e,n,"session");import{useCallback as ie,useState as ae}from"react";var B=e=>e?"online":"offline",mt=()=>{let[e,n]=ae(B(!0)),r=e==="online",t=e==="offline",i=ie(()=>n(B(navigator.onLine)),[]);return N(["online","offline"],{listener:i,onLoad:i}),{connection:e,isOnline:r,isOffline:t}};import{useCallback as W,useEffect as X,useRef as ke}from"react";import{useCallback as M,useMemo as _,useReducer as pe}from"react";import{useEffect as ue}from"react";import{useRef as ce}from"react";var H=()=>{let e=ce(!0);return e.current?(e.current=!1,!0):e.current};var h=(e,n)=>{let r=H();ue(()=>{if(!r)return e()},n)};import{isEmpty as le}from"@alessiofrittoli/web-utils";var R=e=>typeof e=="string"?le(e):!e,U={value:"",isTouched:!1,isValid:!0},G=(e,n)=>{switch(n.type){case"TOUCHED":return{...e,isTouched:!0};case"CHANGE":return{...e,value:n.value};case"BLUR":return{...e,value:e.value,isTouched:!R(e.value??"")};case"RESET":return U}};var Vt=(e={})=>{let{inputRef:n}=e,{initialValue:r}=e,{touchTimeout:t=600}=e,{validate:i,parse:a}=e,{onChange:s}=e,[o,c]=pe(G,{...U,value:r}),p=_(()=>a?a(o.value):o.value,[o.value,a]),u=_(()=>typeof i=="function"?i(p):!0,[p,i]),{isTouched:l}=o,d=R(p),T=!u&&l||!!r&&!u;h(()=>{let y=setTimeout(()=>{R(p)||c({type:"TOUCHED"})},t);return()=>clearTimeout(y)},[p,t]);let v=M(y=>{let{target:S}=y,{type:E}=S,g=E==="checkbox"?S.checked:S.value;c({type:"CHANGE",value:g}),s?.(a?a(g):g)},[s,a]),b=M(()=>{c({type:"BLUR"})},[]),O=M(()=>{c({type:"TOUCHED"})},[]),x=M(y=>{c({type:"CHANGE",value:y})},[]),k=M(()=>{n?.current?.focus()},[n]),w=M(()=>{c({type:"RESET"})},[]);return{value:p,isTouched:l,isValid:u,isEmpty:d,hasError:T,changeHandler:v,blurHandler:b,setValue:x,submit:O,focus:k,reset:w}};import{useCallback as de}from"react";import{deferCallback as me}from"@alessiofrittoli/web-utils";var wt=(e,n)=>de(me(e),n);import{useEffect as fe}from"react";var C=e=>{let n=H();fe(()=>{if(n)return e()},[])};import{useEffect as Te,useState as ye}from"react";var z=()=>{let[e,n]=ye(!1);return Te(()=>n(!0),[]),e};import{useMemo as ve}from"react";import{paginate as Ee}from"@alessiofrittoli/math-utils/helpers";var Nt=(e={})=>ve(()=>Ee(e),[e]);import{useCallback as D,useState as xe}from"react";var Jt=(e,n=[])=>{let[r,t]=xe(n),i=r.length>0,a=u=>r.includes(u),s=D(u=>t(l=>{let d=new Set(l);return d.has(u)?d.delete(u):d.add(u),Array.from(d.values())}),[]),o=D(u=>{t(l=>{if(l.length===0)return[u];let d=[...e],T=d.indexOf(l.at(0)),v=d.indexOf(u);if(T>v){let b=[...d].reverse(),O=b.indexOf(l.at(0)),x=b.indexOf(u);return b.slice(O,x+1)}return d.slice(T,v+1)})},[e]),c=D(()=>{t(e)},[e]),p=D(u=>t(u?n:[]),[n]);return{selection:r,hasSelection:i,isSelected:a,setSelection:t,select:s,groupSelect:o,selectAll:c,resetSelection:p}};import{useCallback as Se,useEffect as be,useState as Oe}from"react";import{getMediaMatches as J}from"@alessiofrittoli/web-utils/browser-api";function L(e,n={}){let{updateState:r=!0,onChange:t}=n,[i,a]=Oe(J(e)),s=Se(()=>{let o=J(e);r&&a(o),t?.(o)},[e,r,t]);if(be(()=>{let o=window.matchMedia(e),{matches:c}=o;return r&&a(c),t?.(c),o.addEventListener("change",s),()=>{o.removeEventListener("change",s)}},[e,r,t,s]),!!r)return i}var cn=(e={})=>{let n=z(),r=L("(prefers-color-scheme: dark)"),{initial:t=r,docClassNames:i=[]}=e,[a,s]=j("dark-mode",t),o=a??r,[c,p]=i,u=ke({light:"",dark:""});return h(()=>{s(r)},[r,s]),X(()=>{c&&document.documentElement.classList.toggle(c,o),p&&document.documentElement.classList.toggle(p,!o)},[o,c,p]),X(()=>{document.head.querySelectorAll('meta[name="theme-color"]').forEach(l=>{let d=l.getAttribute("media"),T=l.getAttribute("content");if(T){if(!d||d==="(prefers-color-scheme: light)"){u.current.light=T;return}u.current.dark=T}})},[]),h(()=>{let l=u.current.dark,d=u.current.light;a&&!l||!a&&!d||document.head.querySelectorAll('meta[name="theme-color"]').forEach(T=>{T.setAttribute("content",a?l:d)})},[a]),{isDarkMode:n?o:!1,isDarkOS:n?r:!1,toggleDarkMode:W(()=>s(l=>!l),[s]),enableDarkMode:W(()=>s(!0),[s]),disableDarkMode:W(()=>s(!1),[s])}};import{useCallback as ge,useEffect as Me,useState as Le}from"react";function Y(e={}){let{updateState:n=!0,onVisibilityChange:r}=e,[t,i]=Le(!1),a=ge(()=>{let s=!document.hidden;n&&i(s),r?.(s)},[n,r]);if(C(()=>{n&&i(!document.hidden)}),Me(()=>(document.addEventListener("visibilitychange",a),()=>document.removeEventListener("visibilitychange",a)),[a]),n)return t}import{useEffect as he}from"react";function N(e,n){let{target:r,query:t,options:i,listener:a,onLoad:s,onCleanUp:o}=n;he(()=>{let c=Array.isArray(e)?e:[e],p=(t?window.matchMedia(t):r&&"current"in r?r.current:r)??window;if(p.addEventListener)return s?.(),c.map(u=>{p.addEventListener(u,a,i)}),()=>{c.map(u=>{p.removeEventListener(u,a,i)}),o?.()}},[e,r,t,i,a,s,o])}import{portraitMediaQuery as Ie}from"@alessiofrittoli/web-utils/device";var Sn=()=>L(Ie);var gn=()=>L("(pointer: coarse)");import{useCallback as I,useEffect as Ve,useRef as He,useState as Re}from"react";var Hn=(e={})=>{let{onMount:n=!0,onError:r}=e,[t,i]=Re(null),a=He(n),s=t&&!t.released||!1,o=I(async l=>!t||t.released?navigator.wakeLock.request("screen").then(d=>{i(d),l?.()}).catch(r||console.error):t,[t,r]),c=I(async()=>t?.release(),[t]),p=I(async()=>{o(()=>{a.current=!0})},[o]),u=I(async()=>{a.current=!1,c()},[c]);return Y({updateState:!1,onVisibilityChange:I(l=>{if(l&&!s&&a.current)return o();if(!l)return c()},[s,o,c])}),C(()=>{s||!n||o()}),Ve(()=>{if(!t)return;let l=()=>{t.released&&i(null)};return t.addEventListener("release",l),()=>{t.removeEventListener("release",l),!t.released&&t.release()}},[t]),{wakeLock:t,enabled:s,requestWakeLock:p,releaseWakeLock:u}};import{useCallback as Z,useEffect as Ce,useMemo as De,useRef as we,useState as Ue}from"react";var We=["input","select","textarea","button","[href]",'[tabindex]:not([tabindex="-1"])'].join(", "),wn=e=>{let n=De(()=>e?.current,[e]),[r,t]=Ue(!1),i=we(null),a=Z(o=>{i.current=document.activeElement;let c=o||n||!1;if(c)return t(c)},[n]),s=Z(()=>{i.current?.focus(),t(!1)},[]);return Ce(()=>{if(!r)return;let o=c=>{if(c.key!=="Tab")return;let p=Array.from(r.querySelectorAll(We)),u=p.at(0),l=p.at(-1);if(!c.shiftKey){document.activeElement===l&&(c.preventDefault(),u?.focus());return}document.activeElement===u&&(c.preventDefault(),l?.focus())};return document.addEventListener("keydown",o),()=>{document.removeEventListener("keydown",o)}},[r]),[a,s]};import{useEffect as Ke,useMemo as Ae,useRef as K,useState as ee}from"react";var An=(e,n={})=>{let{initial:r=!1,once:t,amount:i,margin:a,root:s,enable:o=!0}=n,{onEnter:c,onExit:p,onIntersect:u}=n,l=K(!0),[d,T]=ee(r),[v,b]=ee(o),O=K(null),x=K(!1),k=Ae(()=>{if(!v||typeof IntersectionObserver>"u")return;let w=i==="all"?1:i==="some"?.5:i;try{return new IntersectionObserver(async([y],S)=>{if(!y)return;let E=y.isIntersecting;try{if(x.current=!E&&!!O.current,E&&c&&await c({entry:y,observer:S}),x.current&&p&&await p({entry:y,observer:S}),u&&(E||!E&&O.current!=null)){let g={isEntering:E,isExiting:x.current};await u({entry:y,observer:S,...g})}if(O.current=E,!l.current)return;T(E)}catch(g){console.error(g)}E&&t&&S.disconnect()},{root:s||void 0,rootMargin:a,threshold:w})}catch(y){console.error(y)}},[s,a,i,t,v,c,p,u]);return Ke(()=>{if(l.current=!0,!(!v||!e.current||!k))return k.observe(e.current),()=>{l.current=!1,k.disconnect()}},[e,k,v]),{inView:d,enabled:v,observer:k,isExiting:x.current,setInView:T,setEnabled:b}};import{useCallback as te,useMemo as Qe}from"react";import{blockScroll as Fe,restoreScroll as qe}from"@alessiofrittoli/web-utils/dom";var $n=e=>{let n=Qe(()=>e?.current,[e]),r=te(()=>Fe(n||void 0),[n]),t=te(()=>qe(n||void 0),[n]);return[r,t]};import{useMemo as $e,useState as je}from"react";import{useEffect as Pe}from"react";var ne=(e,n={})=>{let{delay:r=1,args:t}=n;Pe(()=>{let i=setTimeout(e,r,...t||[]);return()=>clearTimeout(i)},[r,t,e])};var Xn=(e,n=500)=>{let[r,t]=je(e),i=$e(()=>[e],[e]);return ne(t,{delay:n,args:i}),r};import{useCallback as A,useEffect as Be,useRef as Ne,useState as Ge}from"react";function re(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=Ne(void 0),[c,p]=Ge(i),u=A(()=>o.current?(clearInterval(o.current),o.current=void 0,!0):!1,[]),l=A(()=>{let T=u();return a&&(t?e(...t):e()),o.current=setInterval(e,r,...t||[]),!T&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=A(()=>{u()&&s&&p(!1)},[s,u]);return Be(()=>{if(i)return l(),d},[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}import{useEffect as _e}from"react";var or=(e,n={})=>{let{delay:r=1,args:t}=n;_e(()=>{let i=setInterval(e,r,...t||[]);return()=>clearInterval(i)},[r,t,e])};import{useCallback as Q,useEffect as ze}from"react";function ur(e,n={}){let{autoplay:r=!0}=n,t=re(e,{autoplay:!1,...n}),{start:i,stop:a}=t,s=Q(()=>document.hidden?a():i(),[i,a]),o=Q(()=>{if(document.addEventListener("visibilitychange",s),!document.hidden)return i()},[i,s]),c=Q(()=>{a(),document.removeEventListener("visibilitychange",s)},[a,s]);return ze(()=>{if(r)return o(),c},[r,o,c]),{...t,start:o,stop:c}}import{useCallback as F,useEffect as Je,useRef as Xe,useState as Ye}from"react";function mr(e,n={}){let{delay:r=1,args:t,autoplay:i=!0,runOnStart:a=!1,updateState:s=!1}=n,o=Xe(void 0),[c,p]=Ye(i),u=F(()=>o.current?(clearTimeout(o.current),o.current=void 0,!0):!1,[]),l=F(()=>{let T=u();return a&&(t?e(...t):e()),o.current=setTimeout(()=>{if(o.current=void 0,s&&p(!1),t)return e(...t);e()},r),!T&&s&&p(!0),o.current},[r,t,s,a,e,u]),d=F(()=>{u()&&s&&p(!1)},[s,u]);return Je(()=>{if(i)return l(),d},[i,l,d]),s?{isActive:c,start:l,stop:d}:{start:l,stop:d}}export{B as getState,mt as useConnection,cn as useDarkMode,Xn as useDebounce,wt as useDeferCallback,Y as useDocumentVisibility,C as useEffectOnce,N as useEventListener,wn as useFocusTrap,An as useInView,Vt as useInput,re as useInterval,ur as useIntervalWhenVisible,z as useIsClient,H as useIsFirstRender,Sn as useIsPortrait,gn as useIsTouchDevice,or as useLightInterval,ne as useLightTimeout,j as useLocalStorage,L as useMediaQuery,Nt as usePagination,$n as useScrollBlock,Jt as useSelection,ct as useSessionStorage,V as useStorage,mr as useTimeout,h as useUpdateEffect,Hn as useWakeLock};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alessiofrittoli/react-hooks",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.6.0",
|
|
4
4
|
"description": "TypeScript React utility Hooks",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Alessio Frittoli",
|
|
@@ -95,39 +95,39 @@
|
|
|
95
95
|
},
|
|
96
96
|
"devDependencies": {
|
|
97
97
|
"@alessiofrittoli/event-emitter": "^1.6.0",
|
|
98
|
-
"@alessiofrittoli/node-scripts": "^3.
|
|
98
|
+
"@alessiofrittoli/node-scripts": "^3.3.0",
|
|
99
99
|
"@eslint/compat": "^2.0.0",
|
|
100
100
|
"@eslint/eslintrc": "^3.3.3",
|
|
101
|
-
"@eslint/js": "^9.39.
|
|
101
|
+
"@eslint/js": "^9.39.2",
|
|
102
102
|
"@jest/globals": "^30.2.0",
|
|
103
103
|
"@testing-library/dom": "^10.4.1",
|
|
104
104
|
"@testing-library/jest-dom": "^6.9.1",
|
|
105
|
-
"@testing-library/react": "^16.3.
|
|
105
|
+
"@testing-library/react": "^16.3.1",
|
|
106
106
|
"@testing-library/user-event": "^14.6.1",
|
|
107
107
|
"@types/jest": "^30.0.0",
|
|
108
|
-
"@types/node": "^
|
|
108
|
+
"@types/node": "^25.0.3",
|
|
109
109
|
"@types/react": "^19.2.7",
|
|
110
110
|
"@types/react-dom": "^19.2.3",
|
|
111
111
|
"concurrently": "^9.2.1",
|
|
112
112
|
"cross-env": "^10.1.0",
|
|
113
113
|
"dotenv": "^17.2.3",
|
|
114
|
-
"eslint": "^9.39.
|
|
114
|
+
"eslint": "^9.39.2",
|
|
115
115
|
"eslint-plugin-react": "^7.37.5",
|
|
116
116
|
"eslint-plugin-react-hooks": "^7.0.1",
|
|
117
117
|
"globals": "^16.5.0",
|
|
118
118
|
"http-server": "^14.1.1",
|
|
119
119
|
"jest": "^30.2.0",
|
|
120
120
|
"jest-environment-jsdom": "^30.2.0",
|
|
121
|
-
"react": "^19.2.
|
|
122
|
-
"react-dom": "^19.2.
|
|
121
|
+
"react": "^19.2.3",
|
|
122
|
+
"react-dom": "^19.2.3",
|
|
123
123
|
"ts-jest": "^29.4.6",
|
|
124
124
|
"ts-node": "^10.9.2",
|
|
125
125
|
"tsup": "^8.5.1",
|
|
126
126
|
"typescript": "^5.9.3",
|
|
127
|
-
"typescript-eslint": "^8.
|
|
127
|
+
"typescript-eslint": "^8.50.0"
|
|
128
128
|
},
|
|
129
129
|
"dependencies": {
|
|
130
|
-
"@alessiofrittoli/math-utils": "^1.
|
|
130
|
+
"@alessiofrittoli/math-utils": "^1.17.0",
|
|
131
131
|
"@alessiofrittoli/type-utils": "^1.9.0",
|
|
132
132
|
"@alessiofrittoli/web-utils": "^1.18.0"
|
|
133
133
|
}
|