-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(usePerformance): support
entryTypes
check
- Loading branch information
Showing
2 changed files
with
31 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,44 @@ | ||
import { useWebObserver } from '../use-web-observer' | ||
import { isDev } from '../utils/basic' | ||
|
||
import type { UseWebObserverOptions, UseWebObserverReturns } from '../use-web-observer' | ||
|
||
export interface UsePerformanceObserverOptions extends UseWebObserverOptions, PerformanceObserverInit {} | ||
export interface UsePerformanceObserverOptions | ||
extends UseWebObserverOptions, | ||
Omit<PerformanceObserverInit, 'entryTypes'> { | ||
entryTypes: string[] | ||
} | ||
|
||
export interface UsePerformanceObserverReturns extends UseWebObserverReturns<PerformanceObserver> {} | ||
|
||
/** | ||
* A React Hook that helps to use [PerformanceObserver API](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver) with ease. | ||
*/ | ||
export function usePerformanceObserver( | ||
callback: PerformanceObserverCallback = () => {}, | ||
options: UsePerformanceObserverOptions = {}, | ||
callback: PerformanceObserverCallback, | ||
options: Omit<UsePerformanceObserverOptions, 'supported'>, | ||
): UsePerformanceObserverReturns { | ||
const { immediate = true, ...observerOptions } = options | ||
|
||
return useWebObserver('PerformanceObserver', undefined, callback, { immediate }, undefined, observerOptions) | ||
if (isDev) { | ||
if (!options.entryTypes || !Array.isArray(options.entryTypes) || options.entryTypes.length === 0) { | ||
throw new Error('usePerformanceObserver: entryTypes must be an array and not empty.') | ||
} | ||
} | ||
|
||
return useWebObserver( | ||
'PerformanceObserver', | ||
undefined, | ||
callback, | ||
{ | ||
immediate, | ||
supported() { | ||
return options.entryTypes.every((e) => { | ||
return PerformanceObserver.supportedEntryTypes.includes(e) | ||
}) | ||
}, | ||
}, | ||
undefined, | ||
observerOptions, | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters