first commit

This commit is contained in:
Stefan Hacker
2026-04-03 09:38:48 +02:00
commit 37ad745546
47450 changed files with 3120798 additions and 0 deletions
+3393
View File
File diff suppressed because it is too large Load Diff
+1298
View File
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
@fluentui/react-hooks
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Note: Usage of the fonts and icons referenced in Fluent UI React is subject to the terms listed at https://aka.ms/fluentui-assets-license
+403
View File
@@ -0,0 +1,403 @@
# @fluentui/react-hooks
**[Fluent UI React](https://developer.microsoft.com/en-us/fluentui) hooks**
Helpful hooks not provided by React itself. These hooks were built for use in Fluent UI React ([formerly Office UI Fabric React](https://developer.microsoft.com/en-us/office/blogs/ui-fabric-is-evolving-into-fluent-ui/)) but can be used in React apps built with any UI library.
- [useBoolean](#useboolean) - Return a boolean value and callbacks for setting it to true or false, or toggling.
- [useConst](#useconst) - Initialize and return a value that's always constant.
- [useControllableValue](#usecontrollablevalue) - Manage the current value for a component that could be either controlled or uncontrolled.
- [useEventCallback](#useeventcallback) - Modified `useCallback` that returns the same function reference every time, but always calls the latest implementation.
- [useForceUpdate](#useforceupdate) - Force a function component to update.
- [useId](#useid) - Get a globally unique ID.
- [useIsomorphicLayoutEffect](#useisomorphiclayouteffect) - Calls `useLayoutEffect` in browser and `useEffect` in SSR, to avoid warnings.
- [useMergedRefs](#usemergedrefs) - Merge multiple refs into a single ref callback.
- [useOnEvent](#useonevent) - Attach an event handler on mount and handle cleanup.
- [usePrevious](#useprevious) - Get a value from the previous execution of the component.
- [useRefEffect](#userefeffect) - Call a function with cleanup when a ref changes. Like `useEffect` with a dependency on a ref.
- [useSetInterval](#usesetinterval) - Version of `setInterval` that automatically cleans up when component is unmounted.
- [useSetTimeout](#usesettimeout) - Version of `setTimeout` that automatically cleans up when component is unmounted.
- [useTarget](#usetarget) - Logic used by several popup components to determine the target element or point to position against.
- [useWarnings](#usewarnings) - Display debug-only warnings for invalid or deprecated props or other issues.
## useBoolean
```ts
function useBoolean(initialState: boolean): [boolean, IUseBooleanCallbacks];
interface IUseBooleanCallbacks {
setTrue: () => void;
setFalse: () => void;
toggle: () => void;
}
```
Hook to store a boolean state value and generate callbacks for setting the value to true or false, or toggling the value.
The hook returns a tuple containing the current value and an object with callbacks for updating the value.
Each callback will always have the same identity.
### Example
```jsx
import { useBoolean } from '@fluentui/react-hooks';
const MyComponent = () => {
const [value, { setTrue: showDialog, setFalse: hideDialog, toggle: toggleDialogVisible }] = useBoolean(false);
// ^^^ Instead of:
// const [isDialogVisible, setIsDialogVisible] = React.useState(false);
// const showDialog = React.useCallback(() => setIsDialogVisible(true), []);
// const hideDialog = React.useCallback(() => setIsDialogVisible(false), []);
// const toggleDialogVisible = isDialogVisible ? setFalse : setTrue;
// ... code that shows a dialog when a button is clicked ...
};
```
## useConst
```ts
function useConst<T>(initialValue: T | (() => T)): T;
```
Hook to initialize and return a constant value. Unlike `React.useMemo`, this will **always** return the same value (and if the initializer is a function, only call it once). This is similar to setting a private member in a class constructor.
Its one parameter is the initial value, or a function to get the initial value. Similar to `useState`, only the first value/function passed in is respected.
If the value should ever change based on dependencies, use `React.useMemo` instead.
### Example
```jsx
import { useConst } from '@fluentui/react-hooks';
const MyComponent = () => {
const value = useConst(() => {
/* some computation that must only run once or has side effects */
});
const valueThatMustNeverChange = useConst(/*...*/);
...
};
```
### Why not just `useMemo`?
According to the [React docs](https://reactjs.org/docs/hooks-reference.html#usememo):
> **You may rely on `useMemo` as a performance optimization, not as a semantic guarantee.** In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without `useMemo` — and then add it to optimize performance.
In cases where the value **must** never change, the recommended workaround is to store it with `useRef`, but refs are more awkward to initialize and don't enforce or even communicate that the value should be immutable. An alternative workaround is `const [value] = useState(initializer)`, but this is semantically wrong and more costly under the hood.
## useControllableValue
```ts
// Without onChange
function useControllableValue<TValue, TElement extends HTMLElement>(
controlledValue: TValue | undefined,
defaultUncontrolledValue: TValue | undefined,
): Readonly<[TValue | undefined, (update: React.SetStateAction<TValue | undefined>) => void]>;
// With onChange
function useControllableValue<
TValue,
TElement extends HTMLElement,
TCallback extends ChangeCallback<TElement, TValue> | undefined,
>(
controlledValue: TValue | undefined,
defaultUncontrolledValue: TValue | undefined,
onChange: TCallback,
): Readonly<
[TValue | undefined, (update: React.SetStateAction<TValue | undefined>, ev: React.FormEvent<TElement>) => void]
>;
type ChangeCallback<TElement extends HTMLElement, TValue> = (
ev: React.FormEvent<TElement> | undefined,
newValue: TValue | undefined,
) => void;
```
Hook to manage the current value for a component that could be either controlled or uncontrolled, such as a checkbox or input field. (See the [React docs](https://reactjs.org/docs/uncontrolled-components.html) about the distinction between controlled and uncontrolled components.)
Parameters:
- `controlledValue` (required): the current value if the component is controlled
- `defaultUncontrolledValue` (required): the default value if the component is uncontrolled (will not be used if `controlledValue` is defined)
- `onChange` (optional): callback to be notified of any changes triggered by the user
The returned value is an array with two elements:
- The current value
- A function that will update the internal state if uncontrolled, and invoke the `onChange` callback if present.
- Like the setter returned by `React.useState`, the identity of this callback will never change.
- Also like `React.useState`, you can call this function with either a value, or an updater function which takes the previous value as a parameter and returns the new value.
## useEventCallback
```ts
// The type parameters just copy the type of the passed function to the returned function
function useEventCallback<Args extends unknown[], Return>(fn: (...args: Args) => Return): (...args: Args) => Return;
```
Modified `useCallback` that returns the same function reference every time, but internally calls the most-recently passed callback implementation. Can be useful in situations such as:
- Event handler dependencies change too frequently, such as user props which might change on every render, or volatile values such as useState/useDispatch.
- Callback must be referenced in a captured context (such as a window event handler or unmount handler that's registered once) but needs access to the latest props.
In general, prefer `useCallback` unless you've encountered one of the problems above.
## useForceUpdate
```ts
function useForceUpdate(): () => void;
```
Returns a function which, when called, will force update a function component by updating a fake state value.
The returned function always has the same identity.
## useId
```ts
function useId(prefix?: string): string;
```
Hook to generate a unique ID (with optional `prefix`) in the global scope. This will return the same ID on every render.
Useful for cases in which a component may be rendered multiple times on the same page and needs to use an ID for internal purposes, such as associating a label and an input.
### Example
```jsx
import { useId } from '@fluentui/react-hooks';
const TextField = ({ labelText, defaultValue }) => {
const id = useId('field');
return (
<div>
<label htmlFor={id}>{labelText}</label>
<input id={id} type="text" defaultValue={defaultValue} />
</div>
);
};
```
## useIsomorphicLayoutEffect
```ts
// Type is the same as React.useEffect (not fully specifying here)
function useIsomorphicLayoutEffect(effect, deps?): void;
```
To avoid warnings about `useLayoutEffect` when server-side rendering, this calls `useEffect` on the server (no-op) and `useLayoutEffect` on the client. SSR is determined based on `setSSR` from `@fluentui/utilities`.
Prefer `useEffect` unless you have a specific need to do something after mount and before paint.
## useMergedRefs
```ts
function useMergedRefs<T>(...refs: React.Ref<T>[]): (instance: T) => void;
```
Hook to merge multiple refs (such as one passed in as a prop and one used locally) into a single ref callback that can be passed on to a child component.
```tsx
const Example = React.forwardRef(function Example(props: {}, forwardedRef: React.Ref<HTMLDivElement>) {
const localRef = React.useRef<HTMLDivElement>();
const mergedRef = useMergedRef(localRef, forwardedRef);
React.useEffect(() => {
localRef.current.focus();
}, []);
return <div>Example</div>;
});
```
## useMount
```ts
const useMount: (callback: () => void) => void;
```
Hook which asynchronously executes a callback once the component has been mounted using [useEffect](https://reactjs.org/docs/hooks-reference.html#useeffect)..
```tsx
import { useMount } from '@fluentui/react-hooks';
const MyComponent = () => {
useMount(() => {
console.log('Example');
})
return <div />;
};
});
```
## useOnEvent
```ts
function useOnEvent<TElement extends Element, TEvent extends Event>(
element: React.RefObject<TElement | undefined | null> | TElement | Window | undefined | null,
eventName: string,
callback: (ev: TEvent) => void,
useCapture?: boolean,
): void;
```
Attach an event handler on mount and handle cleanup. The event handler is attached using `on()` from `@fluentui/utilities`.
## usePrevious
```ts
function usePrevious<T>(value: T): T | undefined;
```
Hook keeping track of a given value from a previous execution of the component the Hook is used in. See [React Hooks FAQ](https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state).
## useRefEffect
```ts
function useRefEffect<T>(callback: (value: T) => (() => void) | void, initial: T | null = null): RefCallback<T>;
type RefCallback<T> = ((value: T | null) => void) & React.RefObject<T>;
```
Creates a ref, and calls a callback whenever the ref changes to a non-null value. The callback can optionally return a cleanup function that'll be called before the value changes, and when the ref is unmounted.
The return value is a function that should be called to set the ref's value. The returned object also has a `.current` member that can be used to access the ref's value (like a normal `RefObject`). This can be hooked up to an element's `ref` property.
`useRefEffect` can be used to work around a limitation that [`useEffect` cannot depend on `ref.current`](https://github.com/facebook/react/issues/14387#issuecomment-503616820).
### Example
```tsx
import { useRefEffect } from '@fluentui/react-hooks';
const MyComponent = () => {
const myDivRef = useRefEffect<HTMLElement>(myDiv => {
const observer = new ResizeObserver(entries => {
console.log(`myDiv is ${entries[0].contentRect.width} px wide`);
});
observer.observe(myDiv);
// Return a function to clean up the ResizeObserver when the ref is unmounted
return () => observer.disconnect();
});
return <div ref={myDivRef} />;
};
```
## useSetInterval
```ts
function useSetInterval(): {
setInterval: (callback: () => void, duration: number) => number;
clearInterval: (id: number) => void;
};
```
Hook which returns safe `setInterval` and `clearInterval` methods. Intervals set up using this hook will be automatically cleared when the component is unmounted.
The returned callbacks always have the same identity.
### Example
```jsx
import { useSetInterval } from '@fluentui/react-hooks';
const MyComponent = () => {
const { setInterval, clearInterval } = useSetInterval();
// Set an interval
const id = setInterval(() => console.log('test'), 500);
// If needed, clear an interval manually.
clearInterval(id);
};
```
## useSetTimeout
```ts
function useSetTimeout(): {
setTimeout: (callback: () => void, duration: number) => number;
clearTimeout: (id: number) => void;
};
```
Hook which returns safe `setTimeout` and `clearTimeout` methods. Timeout callbacks set up using this hook will be automatically cleared when the component is unmounted.
The returned callbacks always have the same identity.
### Example
```jsx
import { useSetTimeout } from '@fluentui/react-hooks';
const MyComponent = () => {
const { setTimeout, clearTimeout } = useSetTimeout();
// Set a timeout
const id = setTimeout(() => console.log('test'), 500);
// If needed, clear an timeout manually.
clearTimeout(id);
};
```
## useTarget
```ts
type Target = Element | string | MouseEvent | Point | null | React.RefObject<Element>;
function useTarget<TElement extends HTMLElement = HTMLElement>(
target: Target | undefined,
hostElement?: React.RefObject<TElement | null>,
): Readonly<[React.RefObject<Element | MouseEvent | Point | null>, React.RefObject<Window | undefined>]>;
```
Hook which queries the document for the element indicated by a CSS query string (if provided), or returns the element/event/point provided. Also attempts to determine the Window object for the provided target.
## useUnmount
```ts
const useUnmount: (callback: () => void) => void;
```
Hook that asynchronously fires a callback during unmount using [useEffect](https://reactjs.org/docs/hooks-reference.html#useeffect).
```tsx
import { useUnmount } from '@fluentui/react-hooks';
const MyComponent = () => {
useUnmount(() => {
console.log('Example');
});
return <div />;
};
```
## useWarnings
```ts
function useWarnings<P>(options: IWarningOptions<P>): void;
```
Display console warnings when certain conditions are met. If using webpack, the warning code will automatically be stripped out in production mode.
The following types of warnings are supported (see typings for details on how to specify all of these):
- `other`: Generic string messages.
- `conditionallyRequired`: Warns about props that are required if a condition is met.
- `deprecations`: Warns when deprecated props are being used.
- `mutuallyExclusive`: Warns when two props which are mutually exclusive are both being used.
- `controlledUsage`: Warns on any of the following error conditions in a form component (mimicking the warnings React gives for these error conditions on an input element):
- A value prop is provided (indicated it's being used as controlled) without a change handler, and the component is not read-only
- Both the value and default value props are provided
- The component is attempting to switch between controlled and uncontrolled
Note that all warnings except `controlledUsage` will only be shown on first render. New `controlledUsage` warnings may be shown later based on prop changes. All warnings are shown synchronously during render (not wrapped in `useEffect`) for easier tracing/debugging.
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "@fluentui/scripts-api-extractor/api-extractor.common.json"
}
+1
View File
@@ -0,0 +1 @@
/** Jest test setup file. */
+277
View File
@@ -0,0 +1,277 @@
import { Async } from '@fluentui/utilities';
import type { ISettingsMap } from '@fluentui/utilities';
import type { IWarnControlledUsageParams } from '@fluentui/utilities';
import type { Point } from '@fluentui/utilities';
import * as React_2 from 'react';
import { Rectangle } from '@fluentui/utilities';
import { useIsomorphicLayoutEffect } from '@fluentui/utilities';
export declare type ChangeCallback<TElement extends HTMLElement, TValue, TEvent extends React_2.SyntheticEvent<TElement> | undefined> = (ev: TEvent, newValue: TValue | undefined) => void;
/** Updater callbacks returned by `useBoolean`. */
export declare interface IUseBooleanCallbacks {
/** Set the value to true. Always has the same identity. */
setTrue: () => void;
/** Set the value to false. Always has the same identity. */
setFalse: () => void;
/** Toggle the value. Always has the same identity. */
toggle: () => void;
}
export declare interface IWarningOptions<P> {
/** Name of the component */
name: string;
/** Current component props */
props: P;
/** Generic messages */
other?: string[];
/** Warns when props are required if a condition is met */
conditionallyRequired?: {
/** Props required when the condition is met */
requiredProps: string[];
/** Name of the prop that the condition is based on */
conditionalPropName: string;
/** Whether the condition is met */
condition: boolean;
}[];
/**
* Warns when deprecated props are being used. Each key is a prop name and each value is
* either undefined or a replacement prop name.
*/
deprecations?: ISettingsMap<P>;
/**
* Warns when two props which are mutually exclusive are both being used.
* The key is one prop name and the value is the other.
*/
mutuallyExclusive?: ISettingsMap<P>;
/**
* Check for and warn on the following error conditions with a form component:
* - A value prop is provided (indicated it's being used as controlled) without a change handler,
* and the component is not read-only
* - Both the value and defaultValue props are provided
* - The component is attempting to switch between controlled and uncontrolled
*
* The messages mimic the warnings React gives for these error conditions on input elements.
* The warning will only be displayed once per component instance.
*/
controlledUsage?: Pick<IWarnControlledUsageParams<P>, 'valueProp' | 'defaultValueProp' | 'onChangeProp' | 'readOnlyProp'>;
}
/**
* A callback ref function that also has a .current member for the ref's current value.
*/
export declare type RefCallback<T> = ((value: T | null) => void) & React_2.RefObject<T | null>;
/**
* A Ref function which can be treated like a ref object in that it has an attached
* current property, which will be updated as the ref is evaluated.
*/
export declare type RefObjectFunction<T> = React_2.RefObject<T | null> & ((value: T) => void);
export declare type Target = Element | string | MouseEvent | Point | Rectangle | null | React_2.RefObject<Element | null>;
/**
* Hook to provide an Async instance that is automatically cleaned up on dismount.
*/
export declare function useAsync(): Async;
/**
* Hook to store a value and generate callbacks for setting the value to true or false.
* The identity of the callbacks will always stay the same.
*
* @param initialState - Initial value
* @returns Array with the current value and an object containing the updater callbacks.
*/
export declare function useBoolean(initialState: boolean): [boolean, IUseBooleanCallbacks];
/**
* Hook to initialize and return a constant value. Unlike `React.useMemo`, this is guaranteed to
* always return the same value (and if the initializer is a function, only call it once).
* This is similar to setting a private member in a class constructor.
*
* If the value should ever change based on dependencies, use `React.useMemo` instead.
*
* @param initialValue - Initial value, or function to get the initial value. Similar to `useState`,
* only the value/function passed in the first time this is called is respected.
* @returns The value. The identity of this value will always be the same.
*/
export declare function useConst<T>(initialValue: T | (() => T)): T;
/**
* @deprecated Deprecated due to potential for misuse. Generally, use `React.useCallback` instead.
* If you need a callback reference that never changes, consider `useEventCallback`.
*
* This hook was intended for creating callbacks which have no dependencies, and therefore never
* need to change. It works fine if everyone using it is extremely mindful of how closures work,
* but that's not a safe assumption--so in practice, usage of this hook tends to result in bugs
* like unintentionally capturing the first value of a prop and not respecting updates (when
* updates should be respected).
*/
export declare function useConstCallback<T extends (...args: any[]) => any>(callback: T): T;
/**
* Hook to manage a value that could be either controlled or uncontrolled, such as a checked state or
* text box string.
* @param controlledValue - The controlled value passed in the props. This value will always be used if provided,
* and the internal state will be updated to reflect it.
* @param defaultUncontrolledValue - Initial value for the internal state in the uncontrolled case.
* @returns An array of the current value and an updater callback. Like `React.useState`, the updater
* callback always has the same identity, and it can take either a new value, or a function which
* is passed the previous value and returns the new value.
* @see https://reactjs.org/docs/uncontrolled-components.html
*/
export declare function useControllableValue<TValue, TElement extends HTMLElement>(controlledValue: TValue | undefined, defaultUncontrolledValue: TValue | undefined): Readonly<[TValue | undefined, (update: React_2.SetStateAction<TValue | undefined>) => void]>;
export declare function useControllableValue<TValue, TElement extends HTMLElement, TEvent extends React_2.SyntheticEvent<TElement> | undefined>(controlledValue: TValue | undefined, defaultUncontrolledValue: TValue | undefined, onChange: ChangeCallback<TElement, TValue, TEvent> | undefined): Readonly<[
TValue | undefined,
(update: React_2.SetStateAction<TValue | undefined>, ev?: React_2.FormEvent<TElement>) => void
]>;
/**
* Modified `useCallback` that returns the same function reference every time, but internally calls
* the most-recently passed callback implementation. Can be useful in situations such as:
* - Event handler dependencies change too frequently, such as user props which might change on
* every render, or volatile values such as useState/useDispatch
* - Callback must be referenced in a captured context (such as a window event handler or unmount
* handler that's registered once) but needs access to the latest props
*
* In general, prefer `useCallback` unless you've encountered one of the problems above.
*
* https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
*
* @param fn - The callback function that will be used
* @returns A function which is referentially stable but internally calls the most recently passed callback
*/
export declare function useEventCallback<Args extends unknown[], Return>(fn: (...args: Args) => Return): (...args: Args) => Return;
/**
* Hook to force update a function component by updating a dummy state.
*/
export declare function useForceUpdate(): () => void;
/**
* Hook to generate a unique ID in the global scope (spanning across duplicate copies of the same library).
*
* @param prefix - Optional prefix for the ID
* @param providedId - Optional id provided by a parent component. Defaults to the provided value if present,
* without conditioning the hook call
* @returns The ID
*/
export declare function useId(prefix?: string, providedId?: string): string;
export { useIsomorphicLayoutEffect }
/**
* React hook to merge multiple React refs (either MutableRefObjects or ref callbacks) into a single ref callback that
* updates all provided refs
* @param refs - Refs to collectively update with one ref value.
* @returns A function with an attached "current" prop, so that it can be treated like a RefObject.
*/
export declare function useMergedRefs<T>(...refs: (React_2.Ref<T> | undefined)[]): RefObjectFunction<T>;
/**
* Hook which asynchronously executes a callback once the component has been mounted.
*
* @param callback - Function to call before mount.
*/
export declare const useMount: (callback: () => void) => void;
/**
* Hook which synchronously executes a callback once the component has been mounted.
*
* `WARNING` This should only be used if you need to perform an action after the component has been mounted and
* before the browser paints. useMountSync will trigger debug warnings in server-rendered scenarios and should be used
* sparingly.
*
* @deprecated Consider to use React.useEffect() or React.useLayoutEffect() directly based on a use case
*
* @param callback - Function to call once the component has been mounted.
*/
export declare const useMountSync: (callback: () => void) => void;
/**
* Hook to attach an event handler on mount and handle cleanup.
* @param element - Element (or ref to an element) to attach the event handler to
* @param eventName - The event to attach a handler for
* @param callback - The handler for the event
* @param useCapture - Whether or not to attach the handler for the capture phase
*/
export declare function useOnEvent<TElement extends Element, TEvent extends Event>(element: React_2.RefObject<TElement | undefined | null> | TElement | Window | Document | undefined | null, eventName: string, callback: (ev: TEvent) => void, useCapture?: boolean): void;
/**
* Hook keeping track of a given value from a previous execution of the component the Hook is used in.
*
* See [React Hooks FAQ](https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state)
*/
export declare function usePrevious<T>(value: T): T | undefined;
/**
* Creates a ref, and calls a callback whenever the ref changes to a non-null value. The callback can optionally return
* a cleanup function that'll be called before the value changes, and when the ref is unmounted.
*
* This can be used to work around a limitation that useEffect cannot depend on `ref.current` (see
* https://github.com/facebook/react/issues/14387#issuecomment-503616820).
*
* Usage example:
* ```ts
* const myRef = useRefEffect<HTMLElement>(element => {
* ...
* return () => { ... cleanup ... };
* });
* ```
* ```jsx
* <div ref={myRef} />
* ```
*
* @param callback - Called whenever the ref's value changes to non-null. Can optionally return a cleanup function.
* @param initial - (Optional) The initial value for the ref.
*
* @returns A function that should be called to set the ref's value. The object also has a `.current` member that can be
* used to access the ref's value (like a normal RefObject). It can be hooked up to an element's `ref` property.
*/
export declare function useRefEffect<T>(callback: (value: T) => (() => void) | void, initial?: T | null): RefCallback<T>;
/**
* Returns a wrapper function for `setInterval` which automatically handles disposal.
*/
export declare const useSetInterval: () => UseSetIntervalReturnType;
export declare type UseSetIntervalReturnType = {
setInterval: (callback: () => void, duration: number) => number;
clearInterval: (id: number) => void;
};
/**
* Returns a wrapper function for `setTimeout` which automatically handles disposal.
*/
export declare const useSetTimeout: () => UseSetTimeoutReturnType;
export declare type UseSetTimeoutReturnType = {
setTimeout: (callback: () => void, duration: number) => number;
clearTimeout: (id: number) => void;
};
/**
* Hook to calculate and cache the target element specified by the given target attribute,
* as well as the target element's (or host element's) parent window
* @param target- Target selector passed to the component as a property, describing the element that
* the callout should target
* @param hostElement- The callout's host element, used for determining the parent window.
*/
export declare function useTarget<TElement extends HTMLElement = HTMLElement>(target: Target | undefined, hostElement?: React_2.RefObject<TElement | null>): Readonly<[React_2.RefObject<Element | MouseEvent | Point | Rectangle | null>, Window | undefined]>;
/**
* Hook which synchronously executes a callback when the component is about to unmount.
*
* @param callback - Function to call during unmount.
*/
export declare const useUnmount: (callback: () => void) => void;
/**
* Only in development mode, display console warnings when certain conditions are met.
* Note that all warnings except `controlledUsage` will only be shown on first render
* (new `controlledUsage` warnings may be shown later due to prop changes).
*/
export declare function useWarnings<P extends {}>(options: IWarningOptions<P>): void;
export { }
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+128
View File
@@ -0,0 +1,128 @@
## API Report File for "@fluentui/react-hooks"
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
import { Async } from '@fluentui/utilities';
import type { ISettingsMap } from '@fluentui/utilities';
import type { IWarnControlledUsageParams } from '@fluentui/utilities';
import type { Point } from '@fluentui/utilities';
import * as React_2 from 'react';
import { Rectangle } from '@fluentui/utilities';
import { useIsomorphicLayoutEffect } from '@fluentui/utilities';
// @public (undocumented)
export type ChangeCallback<TElement extends HTMLElement, TValue, TEvent extends React_2.SyntheticEvent<TElement> | undefined> = (ev: TEvent, newValue: TValue | undefined) => void;
// @public
export interface IUseBooleanCallbacks {
setFalse: () => void;
setTrue: () => void;
toggle: () => void;
}
// @public (undocumented)
export interface IWarningOptions<P> {
conditionallyRequired?: {
requiredProps: string[];
conditionalPropName: string;
condition: boolean;
}[];
controlledUsage?: Pick<IWarnControlledUsageParams<P>, 'valueProp' | 'defaultValueProp' | 'onChangeProp' | 'readOnlyProp'>;
deprecations?: ISettingsMap<P>;
mutuallyExclusive?: ISettingsMap<P>;
name: string;
other?: string[];
props: P;
}
// @public
export type RefCallback<T> = ((value: T | null) => void) & React_2.RefObject<T | null>;
// @public
export type RefObjectFunction<T> = React_2.RefObject<T | null> & ((value: T) => void);
// @public (undocumented)
export type Target = Element | string | MouseEvent | Point | Rectangle | null | React_2.RefObject<Element | null>;
// @public
export function useAsync(): Async;
// @public
export function useBoolean(initialState: boolean): [boolean, IUseBooleanCallbacks];
// @public
export function useConst<T>(initialValue: T | (() => T)): T;
// @public @deprecated (undocumented)
export function useConstCallback<T extends (...args: any[]) => any>(callback: T): T;
// @public
export function useControllableValue<TValue, TElement extends HTMLElement>(controlledValue: TValue | undefined, defaultUncontrolledValue: TValue | undefined): Readonly<[TValue | undefined, (update: React_2.SetStateAction<TValue | undefined>) => void]>;
// @public (undocumented)
export function useControllableValue<TValue, TElement extends HTMLElement, TEvent extends React_2.SyntheticEvent<TElement> | undefined>(controlledValue: TValue | undefined, defaultUncontrolledValue: TValue | undefined, onChange: ChangeCallback<TElement, TValue, TEvent> | undefined): Readonly<[
TValue | undefined,
(update: React_2.SetStateAction<TValue | undefined>, ev?: React_2.FormEvent<TElement>) => void
]>;
// @public
export function useEventCallback<Args extends unknown[], Return>(fn: (...args: Args) => Return): (...args: Args) => Return;
// @public
export function useForceUpdate(): () => void;
// @public
export function useId(prefix?: string, providedId?: string): string;
export { useIsomorphicLayoutEffect }
// @public
export function useMergedRefs<T>(...refs: (React_2.Ref<T> | undefined)[]): RefObjectFunction<T>;
// @public
export const useMount: (callback: () => void) => void;
// @public @deprecated
export const useMountSync: (callback: () => void) => void;
// @public
export function useOnEvent<TElement extends Element, TEvent extends Event>(element: React_2.RefObject<TElement | undefined | null> | TElement | Window | Document | undefined | null, eventName: string, callback: (ev: TEvent) => void, useCapture?: boolean): void;
// @public
export function usePrevious<T>(value: T): T | undefined;
// @public
export function useRefEffect<T>(callback: (value: T) => (() => void) | void, initial?: T | null): RefCallback<T>;
// @public
export const useSetInterval: () => UseSetIntervalReturnType;
// @public (undocumented)
export type UseSetIntervalReturnType = {
setInterval: (callback: () => void, duration: number) => number;
clearInterval: (id: number) => void;
};
// @public
export const useSetTimeout: () => UseSetTimeoutReturnType;
// @public (undocumented)
export type UseSetTimeoutReturnType = {
setTimeout: (callback: () => void, duration: number) => number;
clearTimeout: (id: number) => void;
};
// @public
export function useTarget<TElement extends HTMLElement = HTMLElement>(target: Target | undefined, hostElement?: React_2.RefObject<TElement | null>): Readonly<[React_2.RefObject<Element | MouseEvent | Point | Rectangle | null>, Window | undefined]>;
// @public
export const useUnmount: (callback: () => void) => void;
// @public
export function useWarnings<P extends {}>(options: IWarningOptions<P>): void;
// (No @packageDocumentation comment for this package)
```
+5
View File
@@ -0,0 +1,5 @@
import { preset, task } from '@fluentui/scripts-tasks';
preset();
task('build', 'build:react-with-umd');
+21
View File
@@ -0,0 +1,21 @@
import './version';
export * from './useAsync';
export * from './useBoolean';
export * from './useConst';
export * from './useConstCallback';
export * from './useControllableValue';
export * from './useEventCallback';
export * from './useForceUpdate';
export * from './useId';
export * from './useMergedRefs';
export * from './useMount';
export * from './useMountSync';
export * from './useOnEvent';
export * from './usePrevious';
export * from './useRefEffect';
export * from './useSetInterval';
export * from './useSetTimeout';
export * from './useTarget';
export * from './useUnmount';
export * from './useWarnings';
export { useIsomorphicLayoutEffect } from '@fluentui/utilities';
+26
View File
@@ -0,0 +1,26 @@
define(["require", "exports", "tslib", "./useAsync", "./useBoolean", "./useConst", "./useConstCallback", "./useControllableValue", "./useEventCallback", "./useForceUpdate", "./useId", "./useMergedRefs", "./useMount", "./useMountSync", "./useOnEvent", "./usePrevious", "./useRefEffect", "./useSetInterval", "./useSetTimeout", "./useTarget", "./useUnmount", "./useWarnings", "@fluentui/utilities", "./version"], function (require, exports, tslib_1, useAsync_1, useBoolean_1, useConst_1, useConstCallback_1, useControllableValue_1, useEventCallback_1, useForceUpdate_1, useId_1, useMergedRefs_1, useMount_1, useMountSync_1, useOnEvent_1, usePrevious_1, useRefEffect_1, useSetInterval_1, useSetTimeout_1, useTarget_1, useUnmount_1, useWarnings_1, utilities_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useIsomorphicLayoutEffect = void 0;
tslib_1.__exportStar(useAsync_1, exports);
tslib_1.__exportStar(useBoolean_1, exports);
tslib_1.__exportStar(useConst_1, exports);
tslib_1.__exportStar(useConstCallback_1, exports);
tslib_1.__exportStar(useControllableValue_1, exports);
tslib_1.__exportStar(useEventCallback_1, exports);
tslib_1.__exportStar(useForceUpdate_1, exports);
tslib_1.__exportStar(useId_1, exports);
tslib_1.__exportStar(useMergedRefs_1, exports);
tslib_1.__exportStar(useMount_1, exports);
tslib_1.__exportStar(useMountSync_1, exports);
tslib_1.__exportStar(useOnEvent_1, exports);
tslib_1.__exportStar(usePrevious_1, exports);
tslib_1.__exportStar(useRefEffect_1, exports);
tslib_1.__exportStar(useSetInterval_1, exports);
tslib_1.__exportStar(useSetTimeout_1, exports);
tslib_1.__exportStar(useTarget_1, exports);
tslib_1.__exportStar(useUnmount_1, exports);
tslib_1.__exportStar(useWarnings_1, exports);
Object.defineProperty(exports, "useIsomorphicLayoutEffect", { enumerable: true, get: function () { return utilities_1.useIsomorphicLayoutEffect; } });
});
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"../src/","sources":["index.ts"],"names":[],"mappings":";;;;IACA,0CAA2B;IAC3B,4CAA6B;IAC7B,0CAA2B;IAC3B,kDAAmC;IACnC,sDAAuC;IACvC,kDAAmC;IACnC,gDAAiC;IACjC,uCAAwB;IACxB,+CAAgC;IAChC,0CAA2B;IAC3B,8CAA+B;IAC/B,4CAA6B;IAC7B,6CAA8B;IAC9B,8CAA+B;IAC/B,gDAAiC;IACjC,+CAAgC;IAChC,2CAA4B;IAC5B,4CAA6B;IAC7B,6CAA8B;IAErB,sHAAA,yBAAyB,OAAA","sourcesContent":["import './version';\nexport * from './useAsync';\nexport * from './useBoolean';\nexport * from './useConst';\nexport * from './useConstCallback';\nexport * from './useControllableValue';\nexport * from './useEventCallback';\nexport * from './useForceUpdate';\nexport * from './useId';\nexport * from './useMergedRefs';\nexport * from './useMount';\nexport * from './useMountSync';\nexport * from './useOnEvent';\nexport * from './usePrevious';\nexport * from './useRefEffect';\nexport * from './useSetInterval';\nexport * from './useSetTimeout';\nexport * from './useTarget';\nexport * from './useUnmount';\nexport * from './useWarnings';\n// re-export since this is a hook, which people would reasonably expect to import from react-hooks\nexport { useIsomorphicLayoutEffect } from '@fluentui/utilities';\n"]}
+9
View File
@@ -0,0 +1,9 @@
/**
* Validate that value(s) returned by a hook do not change in identity.
* @param testDescription - Custom test description
* @param useHook - Function to invoke the hook and return an array of return values which
* should not change
* @param useHookAgain - If you want to verify that the return value doesn't change when hook
* parameters change, you can pass this second callback which calls the hook differently.
*/
export declare function validateHookValueNotChanged<TValues extends NonNullable<any>[]>(testDescription: string, useHook: () => TValues, useHookAgain?: () => TValues): void;
+46
View File
@@ -0,0 +1,46 @@
define(["require", "exports", "react", "@testing-library/react"], function (require, exports, React, react_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateHookValueNotChanged = validateHookValueNotChanged;
/**
* Validate that value(s) returned by a hook do not change in identity.
* @param testDescription - Custom test description
* @param useHook - Function to invoke the hook and return an array of return values which
* should not change
* @param useHookAgain - If you want to verify that the return value doesn't change when hook
* parameters change, you can pass this second callback which calls the hook differently.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function validateHookValueNotChanged(testDescription, useHook, useHookAgain) {
it(testDescription || 'returns the same value(s) each time', function () {
var latestValues;
var callCount = 0;
var TestComponent = function () {
callCount++;
// eslint-disable-next-line react-hooks/rules-of-hooks
latestValues = callCount === 1 ? useHook() : (useHookAgain || useHook)();
return React.createElement("div", null);
};
var wrapper = (0, react_1.render)(React.createElement(TestComponent, null));
expect(callCount).toBe(1);
var firstValues = latestValues;
expect(firstValues).toBeDefined();
latestValues = undefined;
wrapper.rerender(React.createElement(TestComponent, null));
expect(callCount).toBe(2);
expect(latestValues).toBeDefined();
expect(latestValues).toHaveLength(firstValues.length);
for (var i = 0; i < latestValues.length; i++) {
try {
expect(latestValues[i]).toBe(firstValues[i]);
}
catch (err) {
// Make a more informative error message
var valueText = latestValues[i].toString();
expect('').toBe("Identity of value at index ".concat(i, " has changed. This might help identify it:\n").concat(valueText));
}
}
});
}
});
//# sourceMappingURL=testUtilities.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"testUtilities.js","sourceRoot":"../src/","sources":["testUtilities.tsx"],"names":[],"mappings":";;;IAYA,kEAqCC;IA9CD;;;;;;;OAOG;IACH,8DAA8D;IAC9D,SAAgB,2BAA2B,CACzC,eAAuB,EACvB,OAAsB,EACtB,YAA4B;QAE5B,EAAE,CAAC,eAAe,IAAI,qCAAqC,EAAE;YAC3D,IAAI,YAAiC,CAAC;YACtC,IAAI,SAAS,GAAG,CAAC,CAAC;YAElB,IAAM,aAAa,GAA4B;gBAC7C,SAAS,EAAE,CAAC;gBACZ,sDAAsD;gBACtD,YAAY,GAAG,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,YAAY,IAAI,OAAO,CAAC,EAAE,CAAC;gBACzE,OAAO,gCAAO,CAAC;YACjB,CAAC,CAAC;YAEF,IAAM,OAAO,GAAG,IAAA,cAAM,EAAC,oBAAC,aAAa,OAAG,CAAC,CAAC;YAC1C,MAAM,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC1B,IAAM,WAAW,GAAG,YAAY,CAAC;YACjC,MAAM,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC;YAClC,YAAY,GAAG,SAAS,CAAC;YAEzB,OAAO,CAAC,QAAQ,CAAC,oBAAC,aAAa,OAAG,CAAC,CAAC;YACpC,MAAM,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAC1B,MAAM,CAAC,YAAY,CAAC,CAAC,WAAW,EAAE,CAAC;YACnC,MAAM,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,WAAY,CAAC,MAAM,CAAC,CAAC;YAEvD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAa,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBAC9C,IAAI,CAAC;oBACH,MAAM,CAAC,YAAa,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,WAAY,CAAC,CAAC,CAAC,CAAC,CAAC;gBACjD,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,wCAAwC;oBACxC,IAAM,SAAS,GAAG,YAAa,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;oBAC9C,MAAM,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,qCAA8B,CAAC,yDAA+C,SAAS,CAAE,CAAC,CAAC;gBAC7G,CAAC;YACH,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC","sourcesContent":["import * as React from 'react';\nimport { render } from '@testing-library/react';\n\n/**\n * Validate that value(s) returned by a hook do not change in identity.\n * @param testDescription - Custom test description\n * @param useHook - Function to invoke the hook and return an array of return values which\n * should not change\n * @param useHookAgain - If you want to verify that the return value doesn't change when hook\n * parameters change, you can pass this second callback which calls the hook differently.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function validateHookValueNotChanged<TValues extends NonNullable<any>[]>(\n testDescription: string,\n useHook: () => TValues,\n useHookAgain?: () => TValues,\n): void {\n it(testDescription || 'returns the same value(s) each time', () => {\n let latestValues: TValues | undefined;\n let callCount = 0;\n\n const TestComponent: React.FunctionComponent = () => {\n callCount++;\n // eslint-disable-next-line react-hooks/rules-of-hooks\n latestValues = callCount === 1 ? useHook() : (useHookAgain || useHook)();\n return <div />;\n };\n\n const wrapper = render(<TestComponent />);\n expect(callCount).toBe(1);\n const firstValues = latestValues;\n expect(firstValues).toBeDefined();\n latestValues = undefined;\n\n wrapper.rerender(<TestComponent />);\n expect(callCount).toBe(2);\n expect(latestValues).toBeDefined();\n expect(latestValues).toHaveLength(firstValues!.length);\n\n for (let i = 0; i < latestValues!.length; i++) {\n try {\n expect(latestValues![i]).toBe(firstValues![i]);\n } catch (err) {\n // Make a more informative error message\n const valueText = latestValues![i].toString();\n expect('').toBe(`Identity of value at index ${i} has changed. This might help identify it:\\n${valueText}`);\n }\n }\n });\n}\n"]}
+5
View File
@@ -0,0 +1,5 @@
import { Async } from '@fluentui/utilities';
/**
* Hook to provide an Async instance that is automatically cleaned up on dismount.
*/
export declare function useAsync(): Async;
+23
View File
@@ -0,0 +1,23 @@
define(["require", "exports", "@fluentui/utilities", "react"], function (require, exports, utilities_1, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAsync = useAsync;
/**
* Hook to provide an Async instance that is automatically cleaned up on dismount.
*/
function useAsync() {
var asyncRef = React.useRef(undefined);
if (!asyncRef.current) {
asyncRef.current = new utilities_1.Async();
}
React.useEffect(function () {
return function () {
var _a;
(_a = asyncRef.current) === null || _a === void 0 ? void 0 : _a.dispose();
asyncRef.current = undefined;
};
}, []);
return asyncRef.current;
}
});
//# sourceMappingURL=useAsync.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useAsync.js","sourceRoot":"../src/","sources":["useAsync.ts"],"names":[],"mappings":";;;IAMA,4BAYC;IAfD;;OAEG;IACH,SAAgB,QAAQ;QACtB,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAQ,SAAS,CAAC,CAAC;QAChD,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;YACtB,QAAQ,CAAC,OAAO,GAAG,IAAI,iBAAK,EAAE,CAAC;QACjC,CAAC;QACD,KAAK,CAAC,SAAS,CAAC;YACd,OAAO;;gBACL,MAAA,QAAQ,CAAC,OAAO,0CAAE,OAAO,EAAE,CAAC;gBAC5B,QAAQ,CAAC,OAAO,GAAG,SAAS,CAAC;YAC/B,CAAC,CAAC;QACJ,CAAC,EAAE,EAAE,CAAC,CAAC;QACP,OAAO,QAAQ,CAAC,OAAO,CAAC;IAC1B,CAAC","sourcesContent":["import { Async } from '@fluentui/utilities';\nimport * as React from 'react';\n\n/**\n * Hook to provide an Async instance that is automatically cleaned up on dismount.\n */\nexport function useAsync(): Async {\n const asyncRef = React.useRef<Async>(undefined);\n if (!asyncRef.current) {\n asyncRef.current = new Async();\n }\n React.useEffect(() => {\n return () => {\n asyncRef.current?.dispose();\n asyncRef.current = undefined;\n };\n }, []);\n return asyncRef.current;\n}\n"]}
+17
View File
@@ -0,0 +1,17 @@
/** Updater callbacks returned by `useBoolean`. */
export interface IUseBooleanCallbacks {
/** Set the value to true. Always has the same identity. */
setTrue: () => void;
/** Set the value to false. Always has the same identity. */
setFalse: () => void;
/** Toggle the value. Always has the same identity. */
toggle: () => void;
}
/**
* Hook to store a value and generate callbacks for setting the value to true or false.
* The identity of the callbacks will always stay the same.
*
* @param initialState - Initial value
* @returns Array with the current value and an object containing the updater callbacks.
*/
export declare function useBoolean(initialState: boolean): [boolean, IUseBooleanCallbacks];
+26
View File
@@ -0,0 +1,26 @@
define(["require", "exports", "react", "./useConst"], function (require, exports, React, useConst_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useBoolean = useBoolean;
/**
* Hook to store a value and generate callbacks for setting the value to true or false.
* The identity of the callbacks will always stay the same.
*
* @param initialState - Initial value
* @returns Array with the current value and an object containing the updater callbacks.
*/
function useBoolean(initialState) {
var _a = React.useState(initialState), value = _a[0], setValue = _a[1];
var setTrue = (0, useConst_1.useConst)(function () { return function () {
setValue(true);
}; });
var setFalse = (0, useConst_1.useConst)(function () { return function () {
setValue(false);
}; });
var toggle = (0, useConst_1.useConst)(function () { return function () {
setValue(function (currentValue) { return !currentValue; });
}; });
return [value, { setTrue: setTrue, setFalse: setFalse, toggle: toggle }];
}
});
//# sourceMappingURL=useBoolean.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useBoolean.js","sourceRoot":"../src/","sources":["useBoolean.ts"],"names":[],"mappings":";;;IAoBA,gCAcC;IArBD;;;;;;OAMG;IACH,SAAgB,UAAU,CAAC,YAAqB;QACxC,IAAA,KAAoB,KAAK,CAAC,QAAQ,CAAC,YAAY,CAAC,EAA/C,KAAK,QAAA,EAAE,QAAQ,QAAgC,CAAC;QAEvD,IAAM,OAAO,GAAG,IAAA,mBAAQ,EAAC,cAAM,OAAA;YAC7B,QAAQ,CAAC,IAAI,CAAC,CAAC;QACjB,CAAC,EAF8B,CAE9B,CAAC,CAAC;QACH,IAAM,QAAQ,GAAG,IAAA,mBAAQ,EAAC,cAAM,OAAA;YAC9B,QAAQ,CAAC,KAAK,CAAC,CAAC;QAClB,CAAC,EAF+B,CAE/B,CAAC,CAAC;QACH,IAAM,MAAM,GAAG,IAAA,mBAAQ,EAAC,cAAM,OAAA;YAC5B,QAAQ,CAAC,UAAA,YAAY,IAAI,OAAA,CAAC,YAAY,EAAb,CAAa,CAAC,CAAC;QAC1C,CAAC,EAF6B,CAE7B,CAAC,CAAC;QAEH,OAAO,CAAC,KAAK,EAAE,EAAE,OAAO,SAAA,EAAE,QAAQ,UAAA,EAAE,MAAM,QAAA,EAAE,CAAC,CAAC;IAChD,CAAC","sourcesContent":["import * as React from 'react';\nimport { useConst } from './useConst';\n\n/** Updater callbacks returned by `useBoolean`. */\nexport interface IUseBooleanCallbacks {\n /** Set the value to true. Always has the same identity. */\n setTrue: () => void;\n /** Set the value to false. Always has the same identity. */\n setFalse: () => void;\n /** Toggle the value. Always has the same identity. */\n toggle: () => void;\n}\n\n/**\n * Hook to store a value and generate callbacks for setting the value to true or false.\n * The identity of the callbacks will always stay the same.\n *\n * @param initialState - Initial value\n * @returns Array with the current value and an object containing the updater callbacks.\n */\nexport function useBoolean(initialState: boolean): [boolean, IUseBooleanCallbacks] {\n const [value, setValue] = React.useState(initialState);\n\n const setTrue = useConst(() => () => {\n setValue(true);\n });\n const setFalse = useConst(() => () => {\n setValue(false);\n });\n const toggle = useConst(() => () => {\n setValue(currentValue => !currentValue);\n });\n\n return [value, { setTrue, setFalse, toggle }];\n}\n"]}
+12
View File
@@ -0,0 +1,12 @@
/**
* Hook to initialize and return a constant value. Unlike `React.useMemo`, this is guaranteed to
* always return the same value (and if the initializer is a function, only call it once).
* This is similar to setting a private member in a class constructor.
*
* If the value should ever change based on dependencies, use `React.useMemo` instead.
*
* @param initialValue - Initial value, or function to get the initial value. Similar to `useState`,
* only the value/function passed in the first time this is called is respected.
* @returns The value. The identity of this value will always be the same.
*/
export declare function useConst<T>(initialValue: T | (() => T)): T;
+31
View File
@@ -0,0 +1,31 @@
define(["require", "exports", "react"], function (require, exports, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useConst = useConst;
/**
* Hook to initialize and return a constant value. Unlike `React.useMemo`, this is guaranteed to
* always return the same value (and if the initializer is a function, only call it once).
* This is similar to setting a private member in a class constructor.
*
* If the value should ever change based on dependencies, use `React.useMemo` instead.
*
* @param initialValue - Initial value, or function to get the initial value. Similar to `useState`,
* only the value/function passed in the first time this is called is respected.
* @returns The value. The identity of this value will always be the same.
*/
function useConst(initialValue) {
// Use useRef to store the value because it's the least expensive built-in hook that works here
// (we could also use `const [value] = React.useState(initialValue)` but that's more expensive
// internally due to reducer handling which we don't need)
var ref = React.useRef(undefined);
if (ref.current === undefined) {
// Box the value in an object so we can tell if it's initialized even if the initializer
// returns/is undefined
ref.current = {
value: typeof initialValue === 'function' ? initialValue() : initialValue,
};
}
return ref.current.value;
}
});
//# sourceMappingURL=useConst.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useConst.js","sourceRoot":"../src/","sources":["useConst.ts"],"names":[],"mappings":";;;IAaA,4BAaC;IAxBD;;;;;;;;;;OAUG;IACH,SAAgB,QAAQ,CAAI,YAA2B;QACrD,+FAA+F;QAC/F,8FAA8F;QAC9F,0DAA0D;QAC1D,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAe,SAAS,CAAC,CAAC;QAClD,IAAI,GAAG,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;YAC9B,wFAAwF;YACxF,uBAAuB;YACvB,GAAG,CAAC,OAAO,GAAG;gBACZ,KAAK,EAAE,OAAO,YAAY,KAAK,UAAU,CAAC,CAAC,CAAE,YAAyB,EAAE,CAAC,CAAC,CAAC,YAAY;aACxF,CAAC;QACJ,CAAC;QACD,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC;IAC3B,CAAC","sourcesContent":["import * as React from 'react';\n\n/**\n * Hook to initialize and return a constant value. Unlike `React.useMemo`, this is guaranteed to\n * always return the same value (and if the initializer is a function, only call it once).\n * This is similar to setting a private member in a class constructor.\n *\n * If the value should ever change based on dependencies, use `React.useMemo` instead.\n *\n * @param initialValue - Initial value, or function to get the initial value. Similar to `useState`,\n * only the value/function passed in the first time this is called is respected.\n * @returns The value. The identity of this value will always be the same.\n */\nexport function useConst<T>(initialValue: T | (() => T)): T {\n // Use useRef to store the value because it's the least expensive built-in hook that works here\n // (we could also use `const [value] = React.useState(initialValue)` but that's more expensive\n // internally due to reducer handling which we don't need)\n const ref = React.useRef<{ value: T }>(undefined);\n if (ref.current === undefined) {\n // Box the value in an object so we can tell if it's initialized even if the initializer\n // returns/is undefined\n ref.current = {\n value: typeof initialValue === 'function' ? (initialValue as Function)() : initialValue,\n };\n }\n return ref.current.value;\n}\n"]}
+11
View File
@@ -0,0 +1,11 @@
/**
* @deprecated Deprecated due to potential for misuse. Generally, use `React.useCallback` instead.
* If you need a callback reference that never changes, consider `useEventCallback`.
*
* This hook was intended for creating callbacks which have no dependencies, and therefore never
* need to change. It works fine if everyone using it is extremely mindful of how closures work,
* but that's not a safe assumption--so in practice, usage of this hook tends to result in bugs
* like unintentionally capturing the first value of a prop and not respecting updates (when
* updates should be respected).
*/
export declare function useConstCallback<T extends (...args: any[]) => any>(callback: T): T;
+24
View File
@@ -0,0 +1,24 @@
define(["require", "exports", "react"], function (require, exports, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useConstCallback = useConstCallback;
/**
* @deprecated Deprecated due to potential for misuse. Generally, use `React.useCallback` instead.
* If you need a callback reference that never changes, consider `useEventCallback`.
*
* This hook was intended for creating callbacks which have no dependencies, and therefore never
* need to change. It works fine if everyone using it is extremely mindful of how closures work,
* but that's not a safe assumption--so in practice, usage of this hook tends to result in bugs
* like unintentionally capturing the first value of a prop and not respecting updates (when
* updates should be respected).
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function useConstCallback(callback) {
var ref = React.useRef(undefined);
if (!ref.current) {
ref.current = callback;
}
return ref.current;
}
});
//# sourceMappingURL=useConstCallback.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useConstCallback.js","sourceRoot":"../src/","sources":["useConstCallback.ts"],"names":[],"mappings":";;;IAaA,4CAMC;IAjBD;;;;;;;;;OASG;IACH,8DAA8D;IAC9D,SAAgB,gBAAgB,CAAoC,QAAW;QAC7E,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAI,SAAS,CAAC,CAAC;QACvC,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC;YACjB,GAAG,CAAC,OAAO,GAAG,QAAQ,CAAC;QACzB,CAAC;QACD,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC","sourcesContent":["import * as React from 'react';\n\n/**\n * @deprecated Deprecated due to potential for misuse. Generally, use `React.useCallback` instead.\n * If you need a callback reference that never changes, consider `useEventCallback`.\n *\n * This hook was intended for creating callbacks which have no dependencies, and therefore never\n * need to change. It works fine if everyone using it is extremely mindful of how closures work,\n * but that's not a safe assumption--so in practice, usage of this hook tends to result in bugs\n * like unintentionally capturing the first value of a prop and not respecting updates (when\n * updates should be respected).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useConstCallback<T extends (...args: any[]) => any>(callback: T): T {\n const ref = React.useRef<T>(undefined);\n if (!ref.current) {\n ref.current = callback;\n }\n return ref.current;\n}\n"]}
+18
View File
@@ -0,0 +1,18 @@
import * as React from 'react';
export type ChangeCallback<TElement extends HTMLElement, TValue, TEvent extends React.SyntheticEvent<TElement> | undefined> = (ev: TEvent, newValue: TValue | undefined) => void;
/**
* Hook to manage a value that could be either controlled or uncontrolled, such as a checked state or
* text box string.
* @param controlledValue - The controlled value passed in the props. This value will always be used if provided,
* and the internal state will be updated to reflect it.
* @param defaultUncontrolledValue - Initial value for the internal state in the uncontrolled case.
* @returns An array of the current value and an updater callback. Like `React.useState`, the updater
* callback always has the same identity, and it can take either a new value, or a function which
* is passed the previous value and returns the new value.
* @see https://reactjs.org/docs/uncontrolled-components.html
*/
export declare function useControllableValue<TValue, TElement extends HTMLElement>(controlledValue: TValue | undefined, defaultUncontrolledValue: TValue | undefined): Readonly<[TValue | undefined, (update: React.SetStateAction<TValue | undefined>) => void]>;
export declare function useControllableValue<TValue, TElement extends HTMLElement, TEvent extends React.SyntheticEvent<TElement> | undefined>(controlledValue: TValue | undefined, defaultUncontrolledValue: TValue | undefined, onChange: ChangeCallback<TElement, TValue, TEvent> | undefined): Readonly<[
TValue | undefined,
(update: React.SetStateAction<TValue | undefined>, ev?: React.FormEvent<TElement>) => void
]>;
+33
View File
@@ -0,0 +1,33 @@
define(["require", "exports", "react", "./useConst"], function (require, exports, React, useConst_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useControllableValue = useControllableValue;
function useControllableValue(controlledValue, defaultUncontrolledValue, onChange) {
var _a = React.useState(defaultUncontrolledValue), value = _a[0], setValue = _a[1];
var isControlled = (0, useConst_1.useConst)(controlledValue !== undefined);
var currentValue = isControlled ? controlledValue : value;
// Duplicate the current value and onChange in refs so they're accessible from
// setValueOrCallOnChange without creating a new callback every time
var valueRef = React.useRef(currentValue);
var onChangeRef = React.useRef(onChange);
React.useEffect(function () {
valueRef.current = currentValue;
onChangeRef.current = onChange;
});
// To match the behavior of the setter returned by React.useState, this callback's identity
// should never change. This means it MUST NOT directly reference variables that can change.
var setValueOrCallOnChange = (0, useConst_1.useConst)(function () { return function (update, ev) {
// Assuming here that TValue is not a function, because a controllable value will typically
// be something a user can enter as input
var newValue = typeof update === 'function' ? update(valueRef.current) : update;
if (onChangeRef.current) {
onChangeRef.current(ev, newValue);
}
if (!isControlled) {
setValue(newValue);
}
}; });
return [currentValue, setValueOrCallOnChange];
}
});
//# sourceMappingURL=useControllableValue.js.map
@@ -0,0 +1 @@
{"version":3,"file":"useControllableValue.js","sourceRoot":"../src/","sources":["useControllableValue.ts"],"names":[],"mappings":";;;IAmCA,oDAuCC;IAvCD,SAAgB,oBAAoB,CAKlC,eAAmC,EACnC,wBAA4C,EAC5C,QAAmD;QAE7C,IAAA,KAAoB,KAAK,CAAC,QAAQ,CAAqB,wBAAwB,CAAC,EAA/E,KAAK,QAAA,EAAE,QAAQ,QAAgE,CAAC;QACvF,IAAM,YAAY,GAAG,IAAA,mBAAQ,EAAU,eAAe,KAAK,SAAS,CAAC,CAAC;QACtE,IAAM,YAAY,GAAG,YAAY,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC;QAE5D,8EAA8E;QAC9E,oEAAoE;QACpE,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;QAC5C,IAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC3C,KAAK,CAAC,SAAS,CAAC;YACd,QAAQ,CAAC,OAAO,GAAG,YAAY,CAAC;YAChC,WAAW,CAAC,OAAO,GAAG,QAAQ,CAAC;QACjC,CAAC,CAAC,CAAC;QAEH,2FAA2F;QAC3F,4FAA4F;QAC5F,IAAM,sBAAsB,GAAG,IAAA,mBAAQ,EAAC,cAAM,OAAA,UAAC,MAAgD,EAAE,EAAW;YAC1G,2FAA2F;YAC3F,yCAAyC;YACzC,IAAM,QAAQ,GAAG,OAAO,MAAM,KAAK,UAAU,CAAC,CAAC,CAAE,MAAmB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;YAEhG,IAAI,WAAW,CAAC,OAAO,EAAE,CAAC;gBACxB,WAAW,CAAC,OAAO,CAAC,EAAG,EAAE,QAAQ,CAAC,CAAC;YACrC,CAAC;YAED,IAAI,CAAC,YAAY,EAAE,CAAC;gBAClB,QAAQ,CAAC,QAAQ,CAAC,CAAC;YACrB,CAAC;QACH,CAAC,EAZ6C,CAY7C,CAAC,CAAC;QAEH,OAAO,CAAC,YAAY,EAAE,sBAAsB,CAAU,CAAC;IACzD,CAAC","sourcesContent":["import * as React from 'react';\nimport { useConst } from './useConst';\n\nexport type ChangeCallback<\n TElement extends HTMLElement,\n TValue,\n TEvent extends React.SyntheticEvent<TElement> | undefined,\n> = (ev: TEvent, newValue: TValue | undefined) => void;\n\n/**\n * Hook to manage a value that could be either controlled or uncontrolled, such as a checked state or\n * text box string.\n * @param controlledValue - The controlled value passed in the props. This value will always be used if provided,\n * and the internal state will be updated to reflect it.\n * @param defaultUncontrolledValue - Initial value for the internal state in the uncontrolled case.\n * @returns An array of the current value and an updater callback. Like `React.useState`, the updater\n * callback always has the same identity, and it can take either a new value, or a function which\n * is passed the previous value and returns the new value.\n * @see https://reactjs.org/docs/uncontrolled-components.html\n */\nexport function useControllableValue<TValue, TElement extends HTMLElement>(\n controlledValue: TValue | undefined,\n defaultUncontrolledValue: TValue | undefined,\n): Readonly<[TValue | undefined, (update: React.SetStateAction<TValue | undefined>) => void]>;\nexport function useControllableValue<\n TValue,\n TElement extends HTMLElement,\n TEvent extends React.SyntheticEvent<TElement> | undefined,\n>(\n controlledValue: TValue | undefined,\n defaultUncontrolledValue: TValue | undefined,\n onChange: ChangeCallback<TElement, TValue, TEvent> | undefined,\n): Readonly<\n [TValue | undefined, (update: React.SetStateAction<TValue | undefined>, ev?: React.FormEvent<TElement>) => void]\n>;\nexport function useControllableValue<\n TValue,\n TElement extends HTMLElement,\n TEvent extends React.SyntheticEvent<TElement> | undefined,\n>(\n controlledValue: TValue | undefined,\n defaultUncontrolledValue: TValue | undefined,\n onChange?: ChangeCallback<TElement, TValue, TEvent>,\n) {\n const [value, setValue] = React.useState<TValue | undefined>(defaultUncontrolledValue);\n const isControlled = useConst<boolean>(controlledValue !== undefined);\n const currentValue = isControlled ? controlledValue : value;\n\n // Duplicate the current value and onChange in refs so they're accessible from\n // setValueOrCallOnChange without creating a new callback every time\n const valueRef = React.useRef(currentValue);\n const onChangeRef = React.useRef(onChange);\n React.useEffect(() => {\n valueRef.current = currentValue;\n onChangeRef.current = onChange;\n });\n\n // To match the behavior of the setter returned by React.useState, this callback's identity\n // should never change. This means it MUST NOT directly reference variables that can change.\n const setValueOrCallOnChange = useConst(() => (update: React.SetStateAction<TValue | undefined>, ev?: TEvent) => {\n // Assuming here that TValue is not a function, because a controllable value will typically\n // be something a user can enter as input\n const newValue = typeof update === 'function' ? (update as Function)(valueRef.current) : update;\n\n if (onChangeRef.current) {\n onChangeRef.current(ev!, newValue);\n }\n\n if (!isControlled) {\n setValue(newValue);\n }\n });\n\n return [currentValue, setValueOrCallOnChange] as const;\n}\n"]}
+16
View File
@@ -0,0 +1,16 @@
/**
* Modified `useCallback` that returns the same function reference every time, but internally calls
* the most-recently passed callback implementation. Can be useful in situations such as:
* - Event handler dependencies change too frequently, such as user props which might change on
* every render, or volatile values such as useState/useDispatch
* - Callback must be referenced in a captured context (such as a window event handler or unmount
* handler that's registered once) but needs access to the latest props
*
* In general, prefer `useCallback` unless you've encountered one of the problems above.
*
* https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
*
* @param fn - The callback function that will be used
* @returns A function which is referentially stable but internally calls the most recently passed callback
*/
export declare function useEventCallback<Args extends unknown[], Return>(fn: (...args: Args) => Return): (...args: Args) => Return;
+39
View File
@@ -0,0 +1,39 @@
define(["require", "exports", "react", "./useConst", "@fluentui/utilities"], function (require, exports, React, useConst_1, utilities_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useEventCallback = useEventCallback;
/**
* Modified `useCallback` that returns the same function reference every time, but internally calls
* the most-recently passed callback implementation. Can be useful in situations such as:
* - Event handler dependencies change too frequently, such as user props which might change on
* every render, or volatile values such as useState/useDispatch
* - Callback must be referenced in a captured context (such as a window event handler or unmount
* handler that's registered once) but needs access to the latest props
*
* In general, prefer `useCallback` unless you've encountered one of the problems above.
*
* https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
*
* @param fn - The callback function that will be used
* @returns A function which is referentially stable but internally calls the most recently passed callback
*/
function useEventCallback(fn) {
var callbackRef = React.useRef(function () {
throw new Error('Cannot call an event handler while rendering');
});
(0, utilities_1.useIsomorphicLayoutEffect)(function () {
callbackRef.current = fn;
}, [fn]);
// useConst rather than useCallback to ensure the reference is always stable
// (useCallback's deps list is an optimization, not a guarantee)
return (0, useConst_1.useConst)(function () { return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var callback = callbackRef.current;
return callback.apply(void 0, args);
}; });
}
});
//# sourceMappingURL=useEventCallback.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useEventCallback.js","sourceRoot":"../src/","sources":["useEventCallback.ts"],"names":[],"mappings":";;;IAmBA,4CAiBC;IAhCD;;;;;;;;;;;;;;OAcG;IACH,SAAgB,gBAAgB,CAC9B,EAA6B;QAE7B,IAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAY;YAC1C,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;QAClE,CAAC,CAAC,CAAC;QAEH,IAAA,qCAAyB,EAAC;YACxB,WAAW,CAAC,OAAO,GAAG,EAAE,CAAC;QAC3B,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;QAET,4EAA4E;QAC5E,gEAAgE;QAChE,OAAO,IAAA,mBAAQ,EAAC,cAAM,OAAA;YAAC,cAAa;iBAAb,UAAa,EAAb,qBAAa,EAAb,IAAa;gBAAb,yBAAa;;YAClC,IAAM,QAAQ,GAAG,WAAW,CAAC,OAAO,CAAC;YACrC,OAAO,QAAQ,eAAI,IAAI,EAAE;QAC3B,CAAC,EAHqB,CAGrB,CAAC,CAAC;IACL,CAAC","sourcesContent":["import * as React from 'react';\nimport { useConst } from './useConst';\nimport { useIsomorphicLayoutEffect } from '@fluentui/utilities';\n\n/**\n * Modified `useCallback` that returns the same function reference every time, but internally calls\n * the most-recently passed callback implementation. Can be useful in situations such as:\n * - Event handler dependencies change too frequently, such as user props which might change on\n * every render, or volatile values such as useState/useDispatch\n * - Callback must be referenced in a captured context (such as a window event handler or unmount\n * handler that's registered once) but needs access to the latest props\n *\n * In general, prefer `useCallback` unless you've encountered one of the problems above.\n *\n * https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback\n *\n * @param fn - The callback function that will be used\n * @returns A function which is referentially stable but internally calls the most recently passed callback\n */\nexport function useEventCallback<Args extends unknown[], Return>(\n fn: (...args: Args) => Return,\n): (...args: Args) => Return {\n const callbackRef = React.useRef<typeof fn>(() => {\n throw new Error('Cannot call an event handler while rendering');\n });\n\n useIsomorphicLayoutEffect(() => {\n callbackRef.current = fn;\n }, [fn]);\n\n // useConst rather than useCallback to ensure the reference is always stable\n // (useCallback's deps list is an optimization, not a guarantee)\n return useConst(() => (...args: Args) => {\n const callback = callbackRef.current;\n return callback(...args);\n });\n}\n"]}
+4
View File
@@ -0,0 +1,4 @@
/**
* Hook to force update a function component by updating a dummy state.
*/
export declare function useForceUpdate(): () => void;
+14
View File
@@ -0,0 +1,14 @@
define(["require", "exports", "react", "./useConst"], function (require, exports, React, useConst_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useForceUpdate = useForceUpdate;
/**
* Hook to force update a function component by updating a dummy state.
*/
function useForceUpdate() {
var _a = React.useState(0), setValue = _a[1];
var forceUpdate = (0, useConst_1.useConst)(function () { return function () { return setValue(function (value) { return ++value; }); }; });
return forceUpdate;
}
});
//# sourceMappingURL=useForceUpdate.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useForceUpdate.js","sourceRoot":"../src/","sources":["useForceUpdate.ts"],"names":[],"mappings":";;;IAMA,wCAIC;IAPD;;OAEG;IACH,SAAgB,cAAc;QACtB,IAAA,KAAe,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,EAA7B,QAAQ,QAAqB,CAAC;QACvC,IAAM,WAAW,GAAG,IAAA,mBAAQ,EAAC,cAAM,OAAA,cAAM,OAAA,QAAQ,CAAC,UAAA,KAAK,IAAI,OAAA,EAAE,KAAK,EAAP,CAAO,CAAC,EAA1B,CAA0B,EAAhC,CAAgC,CAAC,CAAC;QACrE,OAAO,WAAW,CAAC;IACrB,CAAC","sourcesContent":["import * as React from 'react';\nimport { useConst } from './useConst';\n\n/**\n * Hook to force update a function component by updating a dummy state.\n */\nexport function useForceUpdate(): () => void {\n const [, setValue] = React.useState(0);\n const forceUpdate = useConst(() => () => setValue(value => ++value));\n return forceUpdate;\n}\n"]}
+9
View File
@@ -0,0 +1,9 @@
/**
* Hook to generate a unique ID in the global scope (spanning across duplicate copies of the same library).
*
* @param prefix - Optional prefix for the ID
* @param providedId - Optional id provided by a parent component. Defaults to the provided value if present,
* without conditioning the hook call
* @returns The ID
*/
export declare function useId(prefix?: string, providedId?: string): string;
+23
View File
@@ -0,0 +1,23 @@
define(["require", "exports", "react", "@fluentui/utilities"], function (require, exports, React, utilities_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useId = useId;
/**
* Hook to generate a unique ID in the global scope (spanning across duplicate copies of the same library).
*
* @param prefix - Optional prefix for the ID
* @param providedId - Optional id provided by a parent component. Defaults to the provided value if present,
* without conditioning the hook call
* @returns The ID
*/
function useId(prefix, providedId) {
// getId should only be called once since it updates the global constant for the next ID value.
// (While an extra update isn't likely to cause problems in practice, it's better to avoid it.)
var ref = React.useRef(providedId);
if (!ref.current) {
ref.current = (0, utilities_1.getId)(prefix);
}
return ref.current;
}
});
//# sourceMappingURL=useId.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useId.js","sourceRoot":"../src/","sources":["useId.ts"],"names":[],"mappings":";;;IAWA,sBAQC;IAhBD;;;;;;;OAOG;IACH,SAAgB,KAAK,CAAC,MAAe,EAAE,UAAmB;QACxD,+FAA+F;QAC/F,+FAA+F;QAC/F,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAqB,UAAU,CAAC,CAAC;QACzD,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC;YACjB,GAAG,CAAC,OAAO,GAAG,IAAA,iBAAK,EAAC,MAAM,CAAC,CAAC;QAC9B,CAAC;QACD,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC","sourcesContent":["import * as React from 'react';\nimport { getId } from '@fluentui/utilities';\n\n/**\n * Hook to generate a unique ID in the global scope (spanning across duplicate copies of the same library).\n *\n * @param prefix - Optional prefix for the ID\n * @param providedId - Optional id provided by a parent component. Defaults to the provided value if present,\n * without conditioning the hook call\n * @returns The ID\n */\nexport function useId(prefix?: string, providedId?: string): string {\n // getId should only be called once since it updates the global constant for the next ID value.\n // (While an extra update isn't likely to cause problems in practice, it's better to avoid it.)\n const ref = React.useRef<string | undefined>(providedId);\n if (!ref.current) {\n ref.current = getId(prefix);\n }\n return ref.current;\n}\n"]}
+13
View File
@@ -0,0 +1,13 @@
import * as React from 'react';
/**
* A Ref function which can be treated like a ref object in that it has an attached
* current property, which will be updated as the ref is evaluated.
*/
export type RefObjectFunction<T> = React.RefObject<T | null> & ((value: T) => void);
/**
* React hook to merge multiple React refs (either MutableRefObjects or ref callbacks) into a single ref callback that
* updates all provided refs
* @param refs - Refs to collectively update with one ref value.
* @returns A function with an attached "current" prop, so that it can be treated like a RefObject.
*/
export declare function useMergedRefs<T>(...refs: (React.Ref<T> | undefined)[]): RefObjectFunction<T>;
+35
View File
@@ -0,0 +1,35 @@
define(["require", "exports", "tslib", "react"], function (require, exports, tslib_1, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMergedRefs = useMergedRefs;
/**
* React hook to merge multiple React refs (either MutableRefObjects or ref callbacks) into a single ref callback that
* updates all provided refs
* @param refs - Refs to collectively update with one ref value.
* @returns A function with an attached "current" prop, so that it can be treated like a RefObject.
*/
function useMergedRefs() {
var refs = [];
for (var _i = 0; _i < arguments.length; _i++) {
refs[_i] = arguments[_i];
}
var mergedCallback = React.useCallback(function (value) {
// Update the "current" prop hanging on the function.
// eslint-disable-next-line @typescript-eslint/no-deprecated
mergedCallback.current = value;
for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) {
var ref = refs_1[_i];
if (typeof ref === 'function') {
ref(value);
}
else if (ref) {
// work around the immutability of the React.Ref type
// eslint-disable-next-line @typescript-eslint/no-deprecated
ref.current = value;
}
}
}, tslib_1.__spreadArray([], refs, true));
return mergedCallback;
}
});
//# sourceMappingURL=useMergedRefs.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useMergedRefs.js","sourceRoot":"../src/","sources":["useMergedRefs.ts"],"names":[],"mappings":";;;IAcA,sCAsBC;IA5BD;;;;;OAKG;IACH,SAAgB,aAAa;QAAI,cAAqC;aAArC,UAAqC,EAArC,qBAAqC,EAArC,IAAqC;YAArC,yBAAqC;;QACpE,IAAM,cAAc,GAAyB,KAAK,CAAC,WAAW,CAC5D,UAAC,KAAQ;YACP,qDAAqD;YACrD,4DAA4D;YAC3D,cAAuD,CAAC,OAAO,GAAG,KAAK,CAAC;YAEzE,KAAkB,UAAI,EAAJ,aAAI,EAAJ,kBAAI,EAAJ,IAAI,EAAE,CAAC;gBAApB,IAAM,GAAG,aAAA;gBACZ,IAAI,OAAO,GAAG,KAAK,UAAU,EAAE,CAAC;oBAC9B,GAAG,CAAC,KAAK,CAAC,CAAC;gBACb,CAAC;qBAAM,IAAI,GAAG,EAAE,CAAC;oBACf,qDAAqD;oBACrD,4DAA4D;oBAC3D,GAA4C,CAAC,OAAO,GAAG,KAAK,CAAC;gBAChE,CAAC;YACH,CAAC;QACH,CAAC,4BAEG,IAAI,QAC0B,CAAC;QAErC,OAAO,cAAc,CAAC;IACxB,CAAC","sourcesContent":["import * as React from 'react';\n\n/**\n * A Ref function which can be treated like a ref object in that it has an attached\n * current property, which will be updated as the ref is evaluated.\n */\nexport type RefObjectFunction<T> = React.RefObject<T | null> & ((value: T) => void);\n\n/**\n * React hook to merge multiple React refs (either MutableRefObjects or ref callbacks) into a single ref callback that\n * updates all provided refs\n * @param refs - Refs to collectively update with one ref value.\n * @returns A function with an attached \"current\" prop, so that it can be treated like a RefObject.\n */\nexport function useMergedRefs<T>(...refs: (React.Ref<T> | undefined)[]): RefObjectFunction<T> {\n const mergedCallback: RefObjectFunction<T> = React.useCallback(\n (value: T) => {\n // Update the \"current\" prop hanging on the function.\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n (mergedCallback as unknown as React.MutableRefObject<T>).current = value;\n\n for (const ref of refs) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n // work around the immutability of the React.Ref type\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n (ref as unknown as React.MutableRefObject<T>).current = value;\n }\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- already exhaustive\n [...refs],\n ) as unknown as RefObjectFunction<T>;\n\n return mergedCallback;\n}\n"]}
+6
View File
@@ -0,0 +1,6 @@
/**
* Hook which asynchronously executes a callback once the component has been mounted.
*
* @param callback - Function to call before mount.
*/
export declare const useMount: (callback: () => void) => void;
+20
View File
@@ -0,0 +1,20 @@
define(["require", "exports", "react"], function (require, exports, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMount = void 0;
/**
* Hook which asynchronously executes a callback once the component has been mounted.
*
* @param callback - Function to call before mount.
*/
var useMount = function (callback) {
var mountRef = React.useRef(callback);
mountRef.current = callback;
React.useEffect(function () {
var _a;
(_a = mountRef.current) === null || _a === void 0 ? void 0 : _a.call(mountRef);
}, []);
};
exports.useMount = useMount;
});
//# sourceMappingURL=useMount.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useMount.js","sourceRoot":"../src/","sources":["useMount.ts"],"names":[],"mappings":";;;;IAEA;;;;OAIG;IACI,IAAM,QAAQ,GAAG,UAAC,QAAoB;QAC3C,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACxC,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;QAC5B,KAAK,CAAC,SAAS,CAAC;;YACd,MAAA,QAAQ,CAAC,OAAO,wDAAI,CAAC;QACvB,CAAC,EAAE,EAAE,CAAC,CAAC;IACT,CAAC,CAAC;IANW,QAAA,QAAQ,YAMnB","sourcesContent":["import * as React from 'react';\n\n/**\n * Hook which asynchronously executes a callback once the component has been mounted.\n *\n * @param callback - Function to call before mount.\n */\nexport const useMount = (callback: () => void): void => {\n const mountRef = React.useRef(callback);\n mountRef.current = callback;\n React.useEffect(() => {\n mountRef.current?.();\n }, []);\n};\n"]}
+12
View File
@@ -0,0 +1,12 @@
/**
* Hook which synchronously executes a callback once the component has been mounted.
*
* `WARNING` This should only be used if you need to perform an action after the component has been mounted and
* before the browser paints. useMountSync will trigger debug warnings in server-rendered scenarios and should be used
* sparingly.
*
* @deprecated Consider to use React.useEffect() or React.useLayoutEffect() directly based on a use case
*
* @param callback - Function to call once the component has been mounted.
*/
export declare const useMountSync: (callback: () => void) => void;
+27
View File
@@ -0,0 +1,27 @@
define(["require", "exports", "react"], function (require, exports, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMountSync = void 0;
/**
* Hook which synchronously executes a callback once the component has been mounted.
*
* `WARNING` This should only be used if you need to perform an action after the component has been mounted and
* before the browser paints. useMountSync will trigger debug warnings in server-rendered scenarios and should be used
* sparingly.
*
* @deprecated Consider to use React.useEffect() or React.useLayoutEffect() directly based on a use case
*
* @param callback - Function to call once the component has been mounted.
*/
var useMountSync = function (callback) {
var mountRef = React.useRef(callback);
mountRef.current = callback;
// eslint-disable-next-line no-restricted-properties
React.useLayoutEffect(function () {
var _a;
(_a = mountRef.current) === null || _a === void 0 ? void 0 : _a.call(mountRef);
}, []);
};
exports.useMountSync = useMountSync;
});
//# sourceMappingURL=useMountSync.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useMountSync.js","sourceRoot":"../src/","sources":["useMountSync.ts"],"names":[],"mappings":";;;;IAEA;;;;;;;;;;OAUG;IACI,IAAM,YAAY,GAAG,UAAC,QAAoB;QAC/C,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACxC,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;QAC5B,oDAAoD;QACpD,KAAK,CAAC,eAAe,CAAC;;YACpB,MAAA,QAAQ,CAAC,OAAO,wDAAI,CAAC;QACvB,CAAC,EAAE,EAAE,CAAC,CAAC;IACT,CAAC,CAAC;IAPW,QAAA,YAAY,gBAOvB","sourcesContent":["import * as React from 'react';\n\n/**\n * Hook which synchronously executes a callback once the component has been mounted.\n *\n * `WARNING` This should only be used if you need to perform an action after the component has been mounted and\n * before the browser paints. useMountSync will trigger debug warnings in server-rendered scenarios and should be used\n * sparingly.\n *\n * @deprecated Consider to use React.useEffect() or React.useLayoutEffect() directly based on a use case\n *\n * @param callback - Function to call once the component has been mounted.\n */\nexport const useMountSync = (callback: () => void): void => {\n const mountRef = React.useRef(callback);\n mountRef.current = callback;\n // eslint-disable-next-line no-restricted-properties\n React.useLayoutEffect(() => {\n mountRef.current?.();\n }, []);\n};\n"]}
+9
View File
@@ -0,0 +1,9 @@
import * as React from 'react';
/**
* Hook to attach an event handler on mount and handle cleanup.
* @param element - Element (or ref to an element) to attach the event handler to
* @param eventName - The event to attach a handler for
* @param callback - The handler for the event
* @param useCapture - Whether or not to attach the handler for the capture phase
*/
export declare function useOnEvent<TElement extends Element, TEvent extends Event>(element: React.RefObject<TElement | undefined | null> | TElement | Window | Document | undefined | null, eventName: string, callback: (ev: TEvent) => void, useCapture?: boolean): void;
+26
View File
@@ -0,0 +1,26 @@
define(["require", "exports", "@fluentui/utilities", "react"], function (require, exports, utilities_1, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useOnEvent = useOnEvent;
/**
* Hook to attach an event handler on mount and handle cleanup.
* @param element - Element (or ref to an element) to attach the event handler to
* @param eventName - The event to attach a handler for
* @param callback - The handler for the event
* @param useCapture - Whether or not to attach the handler for the capture phase
*/
function useOnEvent(element, eventName, callback, useCapture) {
// Use a ref for the callback to prevent repeatedly attaching/unattaching callbacks that are unstable across renders
var callbackRef = React.useRef(callback);
callbackRef.current = callback;
React.useEffect(function () {
var actualElement = element && 'current' in element ? element.current : element;
if (!actualElement || !actualElement.addEventListener) {
return;
}
var dispose = (0, utilities_1.on)(actualElement, eventName, function (ev) { return callbackRef.current(ev); }, useCapture);
return dispose;
}, [element, eventName, useCapture]);
}
});
//# sourceMappingURL=useOnEvent.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useOnEvent.js","sourceRoot":"../src/","sources":["useOnEvent.ts"],"names":[],"mappings":";;;IAUA,gCAmBC;IA1BD;;;;;;OAMG;IACH,SAAgB,UAAU,CACxB,OAAuG,EACvG,SAAiB,EACjB,QAA8B,EAC9B,UAAoB;QAEpB,oHAAoH;QACpH,IAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC3C,WAAW,CAAC,OAAO,GAAG,QAAQ,CAAC;QAE/B,KAAK,CAAC,SAAS,CAAC;YACd,IAAM,aAAa,GAAG,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC;YAClF,IAAI,CAAC,aAAa,IAAI,CAAC,aAAa,CAAC,gBAAgB,EAAE,CAAC;gBACtD,OAAO;YACT,CAAC;YAED,IAAM,OAAO,GAAG,IAAA,cAAE,EAAC,aAAa,EAAE,SAAS,EAAE,UAAC,EAAU,IAAK,OAAA,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC,EAAvB,CAAuB,EAAE,UAAU,CAAC,CAAC;YAClG,OAAO,OAAO,CAAC;QACjB,CAAC,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC;IACvC,CAAC","sourcesContent":["import { on } from '@fluentui/utilities';\nimport * as React from 'react';\n\n/**\n * Hook to attach an event handler on mount and handle cleanup.\n * @param element - Element (or ref to an element) to attach the event handler to\n * @param eventName - The event to attach a handler for\n * @param callback - The handler for the event\n * @param useCapture - Whether or not to attach the handler for the capture phase\n */\nexport function useOnEvent<TElement extends Element, TEvent extends Event>(\n element: React.RefObject<TElement | undefined | null> | TElement | Window | Document | undefined | null,\n eventName: string,\n callback: (ev: TEvent) => void,\n useCapture?: boolean,\n): void {\n // Use a ref for the callback to prevent repeatedly attaching/unattaching callbacks that are unstable across renders\n const callbackRef = React.useRef(callback);\n callbackRef.current = callback;\n\n React.useEffect(() => {\n const actualElement = element && 'current' in element ? element.current : element;\n if (!actualElement || !actualElement.addEventListener) {\n return;\n }\n\n const dispose = on(actualElement, eventName, (ev: TEvent) => callbackRef.current(ev), useCapture);\n return dispose;\n }, [element, eventName, useCapture]);\n}\n"]}
+6
View File
@@ -0,0 +1,6 @@
/**
* Hook keeping track of a given value from a previous execution of the component the Hook is used in.
*
* See [React Hooks FAQ](https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state)
*/
export declare function usePrevious<T>(value: T): T | undefined;
+18
View File
@@ -0,0 +1,18 @@
define(["require", "exports", "react"], function (require, exports, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.usePrevious = usePrevious;
/**
* Hook keeping track of a given value from a previous execution of the component the Hook is used in.
*
* See [React Hooks FAQ](https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state)
*/
function usePrevious(value) {
var ref = React.useRef(undefined);
React.useEffect(function () {
ref.current = value;
});
return ref.current;
}
});
//# sourceMappingURL=usePrevious.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"usePrevious.js","sourceRoot":"../src/","sources":["usePrevious.ts"],"names":[],"mappings":";;;IAMA,kCAMC;IAXD;;;;OAIG;IACH,SAAgB,WAAW,CAAI,KAAQ;QACrC,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAgB,SAAS,CAAC,CAAC;QACnD,KAAK,CAAC,SAAS,CAAC;YACd,GAAG,CAAC,OAAO,GAAG,KAAK,CAAC;QACtB,CAAC,CAAC,CAAC;QACH,OAAO,GAAG,CAAC,OAAO,CAAC;IACrB,CAAC","sourcesContent":["import * as React from 'react';\n/**\n * Hook keeping track of a given value from a previous execution of the component the Hook is used in.\n *\n * See [React Hooks FAQ](https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state)\n */\nexport function usePrevious<T>(value: T): T | undefined {\n const ref = React.useRef<T | undefined>(undefined);\n React.useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n}\n"]}
+30
View File
@@ -0,0 +1,30 @@
import * as React from 'react';
/**
* A callback ref function that also has a .current member for the ref's current value.
*/
export type RefCallback<T> = ((value: T | null) => void) & React.RefObject<T | null>;
/**
* Creates a ref, and calls a callback whenever the ref changes to a non-null value. The callback can optionally return
* a cleanup function that'll be called before the value changes, and when the ref is unmounted.
*
* This can be used to work around a limitation that useEffect cannot depend on `ref.current` (see
* https://github.com/facebook/react/issues/14387#issuecomment-503616820).
*
* Usage example:
* ```ts
* const myRef = useRefEffect<HTMLElement>(element => {
* ...
* return () => { ... cleanup ... };
* });
* ```
* ```jsx
* <div ref={myRef} />
* ```
*
* @param callback - Called whenever the ref's value changes to non-null. Can optionally return a cleanup function.
* @param initial - (Optional) The initial value for the ref.
*
* @returns A function that should be called to set the ref's value. The object also has a `.current` member that can be
* used to access the ref's value (like a normal RefObject). It can be hooked up to an element's `ref` property.
*/
export declare function useRefEffect<T>(callback: (value: T) => (() => void) | void, initial?: T | null): RefCallback<T>;
+55
View File
@@ -0,0 +1,55 @@
define(["require", "exports", "react"], function (require, exports, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useRefEffect = useRefEffect;
/**
* Creates a ref, and calls a callback whenever the ref changes to a non-null value. The callback can optionally return
* a cleanup function that'll be called before the value changes, and when the ref is unmounted.
*
* This can be used to work around a limitation that useEffect cannot depend on `ref.current` (see
* https://github.com/facebook/react/issues/14387#issuecomment-503616820).
*
* Usage example:
* ```ts
* const myRef = useRefEffect<HTMLElement>(element => {
* ...
* return () => { ... cleanup ... };
* });
* ```
* ```jsx
* <div ref={myRef} />
* ```
*
* @param callback - Called whenever the ref's value changes to non-null. Can optionally return a cleanup function.
* @param initial - (Optional) The initial value for the ref.
*
* @returns A function that should be called to set the ref's value. The object also has a `.current` member that can be
* used to access the ref's value (like a normal RefObject). It can be hooked up to an element's `ref` property.
*/
function useRefEffect(callback, initial) {
if (initial === void 0) { initial = null; }
var createRefCallback = function () {
var refCallback = function (value) {
if (data.ref.current !== value) {
if (data.cleanup) {
data.cleanup();
data.cleanup = undefined;
}
data.ref.current = value;
if (value !== null) {
data.cleanup = data.callback(value);
}
}
};
refCallback.current = initial;
return refCallback;
};
var data = React.useRef({
ref: createRefCallback(),
callback: callback,
}).current;
data.callback = callback;
return data.ref;
}
});
//# sourceMappingURL=useRefEffect.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useRefEffect.js","sourceRoot":"../src/","sources":["useRefEffect.ts"],"names":[],"mappings":";;;IA+BA,oCAoCC;IA5DD;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACH,SAAgB,YAAY,CAAI,QAA2C,EAAE,OAAwB;QAAxB,wBAAA,EAAA,cAAwB;QAQnG,IAAM,iBAAiB,GAAG;YACxB,IAAM,WAAW,GAAG,UAAC,KAAe;gBAClC,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,KAAK,KAAK,EAAE,CAAC;oBAC/B,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;wBACjB,IAAI,CAAC,OAAO,EAAE,CAAC;wBACf,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;oBAC3B,CAAC;oBAED,IAAI,CAAC,GAAG,CAAC,OAAO,GAAG,KAAK,CAAC;oBAEzB,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;wBACnB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;oBACtC,CAAC;gBACH,CAAC;YACH,CAAC,CAAC;YAEF,WAAW,CAAC,OAAO,GAAG,OAAO,CAAC;YAC9B,OAAO,WAAW,CAAC;QACrB,CAAC,CAAC;QAEF,IAAM,IAAI,GAAG,KAAK,CAAC,MAAM,CAAU;YACjC,GAAG,EAAE,iBAAiB,EAAE;YACxB,QAAQ,UAAA;SACT,CAAC,CAAC,OAAO,CAAC;QAEX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,OAAO,IAAI,CAAC,GAAG,CAAC;IAClB,CAAC","sourcesContent":["import * as React from 'react';\n\n/**\n * A callback ref function that also has a .current member for the ref's current value.\n */\nexport type RefCallback<T> = ((value: T | null) => void) & React.RefObject<T | null>;\n\n/**\n * Creates a ref, and calls a callback whenever the ref changes to a non-null value. The callback can optionally return\n * a cleanup function that'll be called before the value changes, and when the ref is unmounted.\n *\n * This can be used to work around a limitation that useEffect cannot depend on `ref.current` (see\n * https://github.com/facebook/react/issues/14387#issuecomment-503616820).\n *\n * Usage example:\n * ```ts\n * const myRef = useRefEffect<HTMLElement>(element => {\n * ...\n * return () => { ... cleanup ... };\n * });\n * ```\n * ```jsx\n * <div ref={myRef} />\n * ```\n *\n * @param callback - Called whenever the ref's value changes to non-null. Can optionally return a cleanup function.\n * @param initial - (Optional) The initial value for the ref.\n *\n * @returns A function that should be called to set the ref's value. The object also has a `.current` member that can be\n * used to access the ref's value (like a normal RefObject). It can be hooked up to an element's `ref` property.\n */\nexport function useRefEffect<T>(callback: (value: T) => (() => void) | void, initial: T | null = null): RefCallback<T> {\n type RefData = {\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n ref: ((value: T | null) => void) & React.MutableRefObject<T | null>;\n callback: (value: T) => (() => void) | void;\n cleanup?: (() => void) | void;\n };\n\n const createRefCallback = () => {\n const refCallback = (value: T | null) => {\n if (data.ref.current !== value) {\n if (data.cleanup) {\n data.cleanup();\n data.cleanup = undefined;\n }\n\n data.ref.current = value;\n\n if (value !== null) {\n data.cleanup = data.callback(value);\n }\n }\n };\n\n refCallback.current = initial;\n return refCallback;\n };\n\n const data = React.useRef<RefData>({\n ref: createRefCallback(),\n callback,\n }).current;\n\n data.callback = callback;\n\n return data.ref;\n}\n"]}
+8
View File
@@ -0,0 +1,8 @@
export type UseSetIntervalReturnType = {
setInterval: (callback: () => void, duration: number) => number;
clearInterval: (id: number) => void;
};
/**
* Returns a wrapper function for `setInterval` which automatically handles disposal.
*/
export declare const useSetInterval: () => UseSetIntervalReturnType;
+33
View File
@@ -0,0 +1,33 @@
define(["require", "exports", "react", "./useConst"], function (require, exports, React, useConst_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSetInterval = void 0;
/**
* Returns a wrapper function for `setInterval` which automatically handles disposal.
*/
var useSetInterval = function () {
var intervalIds = (0, useConst_1.useConst)({});
React.useEffect(function () { return function () {
for (var _i = 0, _a = Object.keys(intervalIds); _i < _a.length; _i++) {
var id = _a[_i];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
clearInterval(id);
}
}; },
// useConst ensures this will never change, but react-hooks/exhaustive-deps doesn't know that
[intervalIds]);
return (0, useConst_1.useConst)({
setInterval: function (func, duration) {
var id = setInterval(func, duration);
intervalIds[id] = 1;
return id;
},
clearInterval: function (id) {
delete intervalIds[id];
clearInterval(id);
},
});
};
exports.useSetInterval = useSetInterval;
});
//# sourceMappingURL=useSetInterval.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useSetInterval.js","sourceRoot":"../src/","sources":["useSetInterval.ts"],"names":[],"mappings":";;;;IAQA;;OAEG;IACI,IAAM,cAAc,GAAG;QAC5B,IAAM,WAAW,GAAG,IAAA,mBAAQ,EAAyB,EAAE,CAAC,CAAC;QAEzD,KAAK,CAAC,SAAS,CACb,cAAM,OAAA;YACJ,KAAiB,UAAwB,EAAxB,KAAA,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAxB,cAAwB,EAAxB,IAAwB,EAAE,CAAC;gBAAvC,IAAM,EAAE,SAAA;gBACX,8DAA8D;gBAC9D,aAAa,CAAC,EAAS,CAAC,CAAC;YAC3B,CAAC;QACH,CAAC,EALK,CAKL;QACD,6FAA6F;QAC7F,CAAC,WAAW,CAAC,CACd,CAAC;QAEF,OAAO,IAAA,mBAAQ,EAAC;YACd,WAAW,EAAE,UAAC,IAAgB,EAAE,QAAgB;gBAC9C,IAAM,EAAE,GAAG,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAsB,CAAC;gBAE5D,WAAW,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;gBAEpB,OAAO,EAAE,CAAC;YACZ,CAAC;YAED,aAAa,EAAE,UAAC,EAAU;gBACxB,OAAO,WAAW,CAAC,EAAE,CAAC,CAAC;gBACvB,aAAa,CAAC,EAAE,CAAC,CAAC;YACpB,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC;IA5BW,QAAA,cAAc,kBA4BzB","sourcesContent":["import * as React from 'react';\nimport { useConst } from './useConst';\n\nexport type UseSetIntervalReturnType = {\n setInterval: (callback: () => void, duration: number) => number;\n clearInterval: (id: number) => void;\n};\n\n/**\n * Returns a wrapper function for `setInterval` which automatically handles disposal.\n */\nexport const useSetInterval = (): UseSetIntervalReturnType => {\n const intervalIds = useConst<Record<number, number>>({});\n\n React.useEffect(\n () => () => {\n for (const id of Object.keys(intervalIds)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n clearInterval(id as any);\n }\n },\n // useConst ensures this will never change, but react-hooks/exhaustive-deps doesn't know that\n [intervalIds],\n );\n\n return useConst({\n setInterval: (func: () => void, duration: number): number => {\n const id = setInterval(func, duration) as unknown as number;\n\n intervalIds[id] = 1;\n\n return id;\n },\n\n clearInterval: (id: number): void => {\n delete intervalIds[id];\n clearInterval(id);\n },\n });\n};\n"]}
+8
View File
@@ -0,0 +1,8 @@
export type UseSetTimeoutReturnType = {
setTimeout: (callback: () => void, duration: number) => number;
clearTimeout: (id: number) => void;
};
/**
* Returns a wrapper function for `setTimeout` which automatically handles disposal.
*/
export declare const useSetTimeout: () => UseSetTimeoutReturnType;
+35
View File
@@ -0,0 +1,35 @@
define(["require", "exports", "react", "./useConst"], function (require, exports, React, useConst_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSetTimeout = void 0;
/**
* Returns a wrapper function for `setTimeout` which automatically handles disposal.
*/
var useSetTimeout = function () {
var timeoutIds = (0, useConst_1.useConst)({});
// Cleanup function.
React.useEffect(function () { return function () {
for (var _i = 0, _a = Object.keys(timeoutIds); _i < _a.length; _i++) {
var id = _a[_i];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
clearTimeout(id);
}
}; },
// useConst ensures this will never change, but react-hooks/exhaustive-deps doesn't know that
[timeoutIds]);
// Return wrapper which will auto cleanup.
return (0, useConst_1.useConst)({
setTimeout: function (func, duration) {
var id = setTimeout(func, duration);
timeoutIds[id] = 1;
return id;
},
clearTimeout: function (id) {
delete timeoutIds[id];
clearTimeout(id);
},
});
};
exports.useSetTimeout = useSetTimeout;
});
//# sourceMappingURL=useSetTimeout.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useSetTimeout.js","sourceRoot":"../src/","sources":["useSetTimeout.ts"],"names":[],"mappings":";;;;IAQA;;OAEG;IACI,IAAM,aAAa,GAAG;QAC3B,IAAM,UAAU,GAAG,IAAA,mBAAQ,EAAyB,EAAE,CAAC,CAAC;QAExD,oBAAoB;QACpB,KAAK,CAAC,SAAS,CACb,cAAM,OAAA;YACJ,KAAiB,UAAuB,EAAvB,KAAA,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAvB,cAAuB,EAAvB,IAAuB,EAAE,CAAC;gBAAtC,IAAM,EAAE,SAAA;gBACX,8DAA8D;gBAC9D,YAAY,CAAC,EAAS,CAAC,CAAC;YAC1B,CAAC;QACH,CAAC,EALK,CAKL;QACD,6FAA6F;QAC7F,CAAC,UAAU,CAAC,CACb,CAAC;QAEF,0CAA0C;QAC1C,OAAO,IAAA,mBAAQ,EAAC;YACd,UAAU,EAAE,UAAC,IAAgB,EAAE,QAAgB;gBAC7C,IAAM,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAsB,CAAC;gBAE3D,UAAU,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;gBAEnB,OAAO,EAAE,CAAC;YACZ,CAAC;YAED,YAAY,EAAE,UAAC,EAAU;gBACvB,OAAO,UAAU,CAAC,EAAE,CAAC,CAAC;gBACtB,YAAY,CAAC,EAAE,CAAC,CAAC;YACnB,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC;IA9BW,QAAA,aAAa,iBA8BxB","sourcesContent":["import * as React from 'react';\nimport { useConst } from './useConst';\n\nexport type UseSetTimeoutReturnType = {\n setTimeout: (callback: () => void, duration: number) => number;\n clearTimeout: (id: number) => void;\n};\n\n/**\n * Returns a wrapper function for `setTimeout` which automatically handles disposal.\n */\nexport const useSetTimeout = (): UseSetTimeoutReturnType => {\n const timeoutIds = useConst<Record<number, number>>({});\n\n // Cleanup function.\n React.useEffect(\n () => () => {\n for (const id of Object.keys(timeoutIds)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n clearTimeout(id as any);\n }\n },\n // useConst ensures this will never change, but react-hooks/exhaustive-deps doesn't know that\n [timeoutIds],\n );\n\n // Return wrapper which will auto cleanup.\n return useConst({\n setTimeout: (func: () => void, duration: number): number => {\n const id = setTimeout(func, duration) as unknown as number;\n\n timeoutIds[id] = 1;\n\n return id;\n },\n\n clearTimeout: (id: number): void => {\n delete timeoutIds[id];\n clearTimeout(id);\n },\n });\n};\n"]}
+12
View File
@@ -0,0 +1,12 @@
import { Rectangle } from '@fluentui/utilities';
import * as React from 'react';
import type { Point } from '@fluentui/utilities';
export type Target = Element | string | MouseEvent | Point | Rectangle | null | React.RefObject<Element | null>;
/**
* Hook to calculate and cache the target element specified by the given target attribute,
* as well as the target element's (or host element's) parent window
* @param target- Target selector passed to the component as a property, describing the element that
* the callout should target
* @param hostElement- The callout's host element, used for determining the parent window.
*/
export declare function useTarget<TElement extends HTMLElement = HTMLElement>(target: Target | undefined, hostElement?: React.RefObject<TElement | null>): Readonly<[React.RefObject<Element | MouseEvent | Point | Rectangle | null>, Window | undefined]>;
+55
View File
@@ -0,0 +1,55 @@
define(["require", "exports", "@fluentui/utilities", "react", "@fluentui/react-window-provider"], function (require, exports, utilities_1, React, react_window_provider_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTarget = useTarget;
/**
* Hook to calculate and cache the target element specified by the given target attribute,
* as well as the target element's (or host element's) parent window
* @param target- Target selector passed to the component as a property, describing the element that
* the callout should target
* @param hostElement- The callout's host element, used for determining the parent window.
*/
function useTarget(target, hostElement) {
var _a, _b, _c;
var previousTargetProp = React.useRef(undefined);
var targetRef = React.useRef(null);
/**
* Stores an instance of Window, used to check
* for server side rendering and if focus was lost.
*/
var targetWindow = (0, react_window_provider_1.useWindow)();
// If the target element changed, find the new one. If we are tracking
// target with class name, always find element because we do not know if
// fabric has rendered a new element and disposed the old element.
if (!target || target !== previousTargetProp.current || typeof target === 'string') {
var currentElement = hostElement === null || hostElement === void 0 ? void 0 : hostElement.current;
if (target) {
if (typeof target === 'string') {
// If element is part of shadow dom, then querySelector on shadow root, else query on document
if ((_a = currentElement === null || currentElement === void 0 ? void 0 : currentElement.getRootNode()) === null || _a === void 0 ? void 0 : _a.host) {
targetRef.current = (_c = (_b = currentElement === null || currentElement === void 0 ? void 0 : currentElement.getRootNode()) === null || _b === void 0 ? void 0 : _b.querySelector(target)) !== null && _c !== void 0 ? _c : null;
}
else {
var currentDoc = (0, utilities_1.getDocument)(currentElement);
targetRef.current = currentDoc ? currentDoc.querySelector(target) : null;
}
}
else if ('stopPropagation' in target) {
targetRef.current = target;
}
else if ('getBoundingClientRect' in target) {
targetRef.current = target;
}
else if ('current' in target) {
targetRef.current = target.current;
}
else {
targetRef.current = target;
}
}
previousTargetProp.current = target;
}
return [targetRef, targetWindow];
}
});
//# sourceMappingURL=useTarget.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useTarget.js","sourceRoot":"../src/","sources":["useTarget.ts"],"names":[],"mappings":";;;IAcA,8BA2CC;IAlDD;;;;;;OAMG;IACH,SAAgB,SAAS,CACvB,MAA0B,EAC1B,WAA8C;;QAE9C,IAAM,kBAAkB,GAAG,KAAK,CAAC,MAAM,CAErC,SAAS,CAAC,CAAC;QAEb,IAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAkD,IAAI,CAAC,CAAC;QACtF;;;WAGG;QACH,IAAM,YAAY,GAAG,IAAA,iCAAS,GAAE,CAAC;QAEjC,sEAAsE;QACtE,wEAAwE;QACxE,kEAAkE;QAClE,IAAI,CAAC,MAAM,IAAI,MAAM,KAAK,kBAAkB,CAAC,OAAO,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;YACnF,IAAM,cAAc,GAAG,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAC;YAC5C,IAAI,MAAM,EAAE,CAAC;gBACX,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;oBAC/B,8FAA8F;oBAC9F,IAAI,MAAC,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,WAAW,EAAiB,0CAAE,IAAI,EAAE,CAAC;wBACxD,SAAS,CAAC,OAAO,GAAG,MAAA,MAAC,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,WAAW,EAAiB,0CAAE,aAAa,CAAC,MAAM,CAAC,mCAAI,IAAI,CAAC;oBACnG,CAAC;yBAAM,CAAC;wBACN,IAAM,UAAU,GAAa,IAAA,uBAAW,EAAC,cAAc,CAAE,CAAC;wBAC1D,SAAS,CAAC,OAAO,GAAG,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;oBAC3E,CAAC;gBACH,CAAC;qBAAM,IAAI,iBAAiB,IAAI,MAAM,EAAE,CAAC;oBACvC,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC;gBAC7B,CAAC;qBAAM,IAAI,uBAAuB,IAAI,MAAM,EAAE,CAAC;oBAC7C,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC;gBAC7B,CAAC;qBAAM,IAAI,SAAS,IAAI,MAAM,EAAE,CAAC;oBAC/B,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;gBACrC,CAAC;qBAAM,CAAC;oBACN,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC;gBAC7B,CAAC;YACH,CAAC;YACD,kBAAkB,CAAC,OAAO,GAAG,MAAM,CAAC;QACtC,CAAC;QAED,OAAO,CAAC,SAAS,EAAE,YAAY,CAAU,CAAC;IAC5C,CAAC","sourcesContent":["import { getDocument, Rectangle } from '@fluentui/utilities';\nimport * as React from 'react';\nimport { useWindow } from '@fluentui/react-window-provider';\nimport type { Point } from '@fluentui/utilities';\n\nexport type Target = Element | string | MouseEvent | Point | Rectangle | null | React.RefObject<Element | null>;\n\n/**\n * Hook to calculate and cache the target element specified by the given target attribute,\n * as well as the target element's (or host element's) parent window\n * @param target- Target selector passed to the component as a property, describing the element that\n * the callout should target\n * @param hostElement- The callout's host element, used for determining the parent window.\n */\nexport function useTarget<TElement extends HTMLElement = HTMLElement>(\n target: Target | undefined,\n hostElement?: React.RefObject<TElement | null>,\n): Readonly<[React.RefObject<Element | MouseEvent | Point | Rectangle | null>, Window | undefined]> {\n const previousTargetProp = React.useRef<\n Element | string | MouseEvent | Point | Rectangle | React.RefObject<Element | null> | null | undefined\n >(undefined);\n\n const targetRef = React.useRef<Element | MouseEvent | Point | Rectangle | null>(null);\n /**\n * Stores an instance of Window, used to check\n * for server side rendering and if focus was lost.\n */\n const targetWindow = useWindow();\n\n // If the target element changed, find the new one. If we are tracking\n // target with class name, always find element because we do not know if\n // fabric has rendered a new element and disposed the old element.\n if (!target || target !== previousTargetProp.current || typeof target === 'string') {\n const currentElement = hostElement?.current;\n if (target) {\n if (typeof target === 'string') {\n // If element is part of shadow dom, then querySelector on shadow root, else query on document\n if ((currentElement?.getRootNode() as ShadowRoot)?.host) {\n targetRef.current = (currentElement?.getRootNode() as ShadowRoot)?.querySelector(target) ?? null;\n } else {\n const currentDoc: Document = getDocument(currentElement)!;\n targetRef.current = currentDoc ? currentDoc.querySelector(target) : null;\n }\n } else if ('stopPropagation' in target) {\n targetRef.current = target;\n } else if ('getBoundingClientRect' in target) {\n targetRef.current = target;\n } else if ('current' in target) {\n targetRef.current = target.current;\n } else {\n targetRef.current = target;\n }\n }\n previousTargetProp.current = target;\n }\n\n return [targetRef, targetWindow] as const;\n}\n"]}
+6
View File
@@ -0,0 +1,6 @@
/**
* Hook which synchronously executes a callback when the component is about to unmount.
*
* @param callback - Function to call during unmount.
*/
export declare const useUnmount: (callback: () => void) => void;
+20
View File
@@ -0,0 +1,20 @@
define(["require", "exports", "react"], function (require, exports, React) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useUnmount = void 0;
/**
* Hook which synchronously executes a callback when the component is about to unmount.
*
* @param callback - Function to call during unmount.
*/
var useUnmount = function (callback) {
var unmountRef = React.useRef(callback);
unmountRef.current = callback;
React.useEffect(function () { return function () {
var _a;
(_a = unmountRef.current) === null || _a === void 0 ? void 0 : _a.call(unmountRef);
}; }, []);
};
exports.useUnmount = useUnmount;
});
//# sourceMappingURL=useUnmount.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useUnmount.js","sourceRoot":"../src/","sources":["useUnmount.ts"],"names":[],"mappings":";;;;IAEA;;;;OAIG;IACI,IAAM,UAAU,GAAG,UAAC,QAAoB;QAC7C,IAAM,UAAU,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC1C,UAAU,CAAC,OAAO,GAAG,QAAQ,CAAC;QAC9B,KAAK,CAAC,SAAS,CACb,cAAM,OAAA;;YACJ,MAAA,UAAU,CAAC,OAAO,0DAAI,CAAC;QACzB,CAAC,EAFK,CAEL,EACD,EAAE,CACH,CAAC;IACJ,CAAC,CAAC;IATW,QAAA,UAAU,cASrB","sourcesContent":["import * as React from 'react';\n\n/**\n * Hook which synchronously executes a callback when the component is about to unmount.\n *\n * @param callback - Function to call during unmount.\n */\nexport const useUnmount = (callback: () => void): void => {\n const unmountRef = React.useRef(callback);\n unmountRef.current = callback;\n React.useEffect(\n () => () => {\n unmountRef.current?.();\n },\n [],\n );\n};\n"]}
+45
View File
@@ -0,0 +1,45 @@
import type { ISettingsMap, IWarnControlledUsageParams } from '@fluentui/utilities';
export interface IWarningOptions<P> {
/** Name of the component */
name: string;
/** Current component props */
props: P;
/** Generic messages */
other?: string[];
/** Warns when props are required if a condition is met */
conditionallyRequired?: {
/** Props required when the condition is met */
requiredProps: string[];
/** Name of the prop that the condition is based on */
conditionalPropName: string;
/** Whether the condition is met */
condition: boolean;
}[];
/**
* Warns when deprecated props are being used. Each key is a prop name and each value is
* either undefined or a replacement prop name.
*/
deprecations?: ISettingsMap<P>;
/**
* Warns when two props which are mutually exclusive are both being used.
* The key is one prop name and the value is the other.
*/
mutuallyExclusive?: ISettingsMap<P>;
/**
* Check for and warn on the following error conditions with a form component:
* - A value prop is provided (indicated it's being used as controlled) without a change handler,
* and the component is not read-only
* - Both the value and defaultValue props are provided
* - The component is attempting to switch between controlled and uncontrolled
*
* The messages mimic the warnings React gives for these error conditions on input elements.
* The warning will only be displayed once per component instance.
*/
controlledUsage?: Pick<IWarnControlledUsageParams<P>, 'valueProp' | 'defaultValueProp' | 'onChangeProp' | 'readOnlyProp'>;
}
/**
* Only in development mode, display console warnings when certain conditions are met.
* Note that all warnings except `controlledUsage` will only be shown on first render
* (new `controlledUsage` warnings may be shown later due to prop changes).
*/
export declare function useWarnings<P extends {}>(options: IWarningOptions<P>): void;
+15
View File
@@ -0,0 +1,15 @@
define(["require", "exports", "tslib", "react", "@fluentui/utilities", "./usePrevious", "./useConst"], function (require, exports, tslib_1, React, utilities_1, usePrevious_1, useConst_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useWarnings = useWarnings;
var warningId = 0;
/**
* Only in development mode, display console warnings when certain conditions are met.
* Note that all warnings except `controlledUsage` will only be shown on first render
* (new `controlledUsage` warnings may be shown later due to prop changes).
*/
function useWarnings(options) {
}
});
//# sourceMappingURL=useWarnings.js.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export {};
+6
View File
@@ -0,0 +1,6 @@
define(["require", "exports", "@fluentui/set-version"], function (require, exports, set_version_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
(0, set_version_1.setVersion)('@fluentui/react-hooks', '8.10.2');
});
//# sourceMappingURL=version.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"version.js","sourceRoot":"../src/","sources":["version.ts"],"names":[],"mappings":";;;IAGA,IAAA,wBAAU,EAAC,uBAAuB,EAAE,QAAQ,CAAC,CAAC","sourcesContent":["// Do not modify this file; it is generated as part of publish.\n// The checked in version is a placeholder only and will not be updated.\nimport { setVersion } from '@fluentui/set-version';\nsetVersion('@fluentui/react-hooks', '8.10.2');"]}
+21
View File
@@ -0,0 +1,21 @@
import './version';
export * from './useAsync';
export * from './useBoolean';
export * from './useConst';
export * from './useConstCallback';
export * from './useControllableValue';
export * from './useEventCallback';
export * from './useForceUpdate';
export * from './useId';
export * from './useMergedRefs';
export * from './useMount';
export * from './useMountSync';
export * from './useOnEvent';
export * from './usePrevious';
export * from './useRefEffect';
export * from './useSetInterval';
export * from './useSetTimeout';
export * from './useTarget';
export * from './useUnmount';
export * from './useWarnings';
export { useIsomorphicLayoutEffect } from '@fluentui/utilities';
+28
View File
@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useIsomorphicLayoutEffect = void 0;
var tslib_1 = require("tslib");
require("./version");
tslib_1.__exportStar(require("./useAsync"), exports);
tslib_1.__exportStar(require("./useBoolean"), exports);
tslib_1.__exportStar(require("./useConst"), exports);
tslib_1.__exportStar(require("./useConstCallback"), exports);
tslib_1.__exportStar(require("./useControllableValue"), exports);
tslib_1.__exportStar(require("./useEventCallback"), exports);
tslib_1.__exportStar(require("./useForceUpdate"), exports);
tslib_1.__exportStar(require("./useId"), exports);
tslib_1.__exportStar(require("./useMergedRefs"), exports);
tslib_1.__exportStar(require("./useMount"), exports);
tslib_1.__exportStar(require("./useMountSync"), exports);
tslib_1.__exportStar(require("./useOnEvent"), exports);
tslib_1.__exportStar(require("./usePrevious"), exports);
tslib_1.__exportStar(require("./useRefEffect"), exports);
tslib_1.__exportStar(require("./useSetInterval"), exports);
tslib_1.__exportStar(require("./useSetTimeout"), exports);
tslib_1.__exportStar(require("./useTarget"), exports);
tslib_1.__exportStar(require("./useUnmount"), exports);
tslib_1.__exportStar(require("./useWarnings"), exports);
// re-export since this is a hook, which people would reasonably expect to import from react-hooks
var utilities_1 = require("@fluentui/utilities");
Object.defineProperty(exports, "useIsomorphicLayoutEffect", { enumerable: true, get: function () { return utilities_1.useIsomorphicLayoutEffect; } });
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"../src/","sources":["index.ts"],"names":[],"mappings":";;;;AAAA,qBAAmB;AACnB,qDAA2B;AAC3B,uDAA6B;AAC7B,qDAA2B;AAC3B,6DAAmC;AACnC,iEAAuC;AACvC,6DAAmC;AACnC,2DAAiC;AACjC,kDAAwB;AACxB,0DAAgC;AAChC,qDAA2B;AAC3B,yDAA+B;AAC/B,uDAA6B;AAC7B,wDAA8B;AAC9B,yDAA+B;AAC/B,2DAAiC;AACjC,0DAAgC;AAChC,sDAA4B;AAC5B,uDAA6B;AAC7B,wDAA8B;AAC9B,kGAAkG;AAClG,iDAAgE;AAAvD,sHAAA,yBAAyB,OAAA","sourcesContent":["import './version';\nexport * from './useAsync';\nexport * from './useBoolean';\nexport * from './useConst';\nexport * from './useConstCallback';\nexport * from './useControllableValue';\nexport * from './useEventCallback';\nexport * from './useForceUpdate';\nexport * from './useId';\nexport * from './useMergedRefs';\nexport * from './useMount';\nexport * from './useMountSync';\nexport * from './useOnEvent';\nexport * from './usePrevious';\nexport * from './useRefEffect';\nexport * from './useSetInterval';\nexport * from './useSetTimeout';\nexport * from './useTarget';\nexport * from './useUnmount';\nexport * from './useWarnings';\n// re-export since this is a hook, which people would reasonably expect to import from react-hooks\nexport { useIsomorphicLayoutEffect } from '@fluentui/utilities';\n"]}
+9
View File
@@ -0,0 +1,9 @@
/**
* Validate that value(s) returned by a hook do not change in identity.
* @param testDescription - Custom test description
* @param useHook - Function to invoke the hook and return an array of return values which
* should not change
* @param useHookAgain - If you want to verify that the return value doesn't change when hook
* parameters change, you can pass this second callback which calls the hook differently.
*/
export declare function validateHookValueNotChanged<TValues extends NonNullable<any>[]>(testDescription: string, useHook: () => TValues, useHookAgain?: () => TValues): void;
+46
View File
@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateHookValueNotChanged = validateHookValueNotChanged;
var React = require("react");
var react_1 = require("@testing-library/react");
/**
* Validate that value(s) returned by a hook do not change in identity.
* @param testDescription - Custom test description
* @param useHook - Function to invoke the hook and return an array of return values which
* should not change
* @param useHookAgain - If you want to verify that the return value doesn't change when hook
* parameters change, you can pass this second callback which calls the hook differently.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function validateHookValueNotChanged(testDescription, useHook, useHookAgain) {
it(testDescription || 'returns the same value(s) each time', function () {
var latestValues;
var callCount = 0;
var TestComponent = function () {
callCount++;
// eslint-disable-next-line react-hooks/rules-of-hooks
latestValues = callCount === 1 ? useHook() : (useHookAgain || useHook)();
return React.createElement("div", null);
};
var wrapper = (0, react_1.render)(React.createElement(TestComponent, null));
expect(callCount).toBe(1);
var firstValues = latestValues;
expect(firstValues).toBeDefined();
latestValues = undefined;
wrapper.rerender(React.createElement(TestComponent, null));
expect(callCount).toBe(2);
expect(latestValues).toBeDefined();
expect(latestValues).toHaveLength(firstValues.length);
for (var i = 0; i < latestValues.length; i++) {
try {
expect(latestValues[i]).toBe(firstValues[i]);
}
catch (err) {
// Make a more informative error message
var valueText = latestValues[i].toString();
expect('').toBe("Identity of value at index ".concat(i, " has changed. This might help identify it:\n").concat(valueText));
}
}
});
}
//# sourceMappingURL=testUtilities.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"testUtilities.js","sourceRoot":"../src/","sources":["testUtilities.tsx"],"names":[],"mappings":";;AAYA,kEAqCC;AAjDD,6BAA+B;AAC/B,gDAAgD;AAEhD;;;;;;;GAOG;AACH,8DAA8D;AAC9D,SAAgB,2BAA2B,CACzC,eAAuB,EACvB,OAAsB,EACtB,YAA4B;IAE5B,EAAE,CAAC,eAAe,IAAI,qCAAqC,EAAE;QAC3D,IAAI,YAAiC,CAAC;QACtC,IAAI,SAAS,GAAG,CAAC,CAAC;QAElB,IAAM,aAAa,GAA4B;YAC7C,SAAS,EAAE,CAAC;YACZ,sDAAsD;YACtD,YAAY,GAAG,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,YAAY,IAAI,OAAO,CAAC,EAAE,CAAC;YACzE,OAAO,gCAAO,CAAC;QACjB,CAAC,CAAC;QAEF,IAAM,OAAO,GAAG,IAAA,cAAM,EAAC,oBAAC,aAAa,OAAG,CAAC,CAAC;QAC1C,MAAM,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC1B,IAAM,WAAW,GAAG,YAAY,CAAC;QACjC,MAAM,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC;QAClC,YAAY,GAAG,SAAS,CAAC;QAEzB,OAAO,CAAC,QAAQ,CAAC,oBAAC,aAAa,OAAG,CAAC,CAAC;QACpC,MAAM,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC1B,MAAM,CAAC,YAAY,CAAC,CAAC,WAAW,EAAE,CAAC;QACnC,MAAM,CAAC,YAAY,CAAC,CAAC,YAAY,CAAC,WAAY,CAAC,MAAM,CAAC,CAAC;QAEvD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,YAAa,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC9C,IAAI,CAAC;gBACH,MAAM,CAAC,YAAa,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,WAAY,CAAC,CAAC,CAAC,CAAC,CAAC;YACjD,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,wCAAwC;gBACxC,IAAM,SAAS,GAAG,YAAa,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;gBAC9C,MAAM,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,qCAA8B,CAAC,yDAA+C,SAAS,CAAE,CAAC,CAAC;YAC7G,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as React from 'react';\nimport { render } from '@testing-library/react';\n\n/**\n * Validate that value(s) returned by a hook do not change in identity.\n * @param testDescription - Custom test description\n * @param useHook - Function to invoke the hook and return an array of return values which\n * should not change\n * @param useHookAgain - If you want to verify that the return value doesn't change when hook\n * parameters change, you can pass this second callback which calls the hook differently.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function validateHookValueNotChanged<TValues extends NonNullable<any>[]>(\n testDescription: string,\n useHook: () => TValues,\n useHookAgain?: () => TValues,\n): void {\n it(testDescription || 'returns the same value(s) each time', () => {\n let latestValues: TValues | undefined;\n let callCount = 0;\n\n const TestComponent: React.FunctionComponent = () => {\n callCount++;\n // eslint-disable-next-line react-hooks/rules-of-hooks\n latestValues = callCount === 1 ? useHook() : (useHookAgain || useHook)();\n return <div />;\n };\n\n const wrapper = render(<TestComponent />);\n expect(callCount).toBe(1);\n const firstValues = latestValues;\n expect(firstValues).toBeDefined();\n latestValues = undefined;\n\n wrapper.rerender(<TestComponent />);\n expect(callCount).toBe(2);\n expect(latestValues).toBeDefined();\n expect(latestValues).toHaveLength(firstValues!.length);\n\n for (let i = 0; i < latestValues!.length; i++) {\n try {\n expect(latestValues![i]).toBe(firstValues![i]);\n } catch (err) {\n // Make a more informative error message\n const valueText = latestValues![i].toString();\n expect('').toBe(`Identity of value at index ${i} has changed. This might help identify it:\\n${valueText}`);\n }\n }\n });\n}\n"]}
+5
View File
@@ -0,0 +1,5 @@
import { Async } from '@fluentui/utilities';
/**
* Hook to provide an Async instance that is automatically cleaned up on dismount.
*/
export declare function useAsync(): Async;
+23
View File
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAsync = useAsync;
var utilities_1 = require("@fluentui/utilities");
var React = require("react");
/**
* Hook to provide an Async instance that is automatically cleaned up on dismount.
*/
function useAsync() {
var asyncRef = React.useRef(undefined);
if (!asyncRef.current) {
asyncRef.current = new utilities_1.Async();
}
React.useEffect(function () {
return function () {
var _a;
(_a = asyncRef.current) === null || _a === void 0 ? void 0 : _a.dispose();
asyncRef.current = undefined;
};
}, []);
return asyncRef.current;
}
//# sourceMappingURL=useAsync.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useAsync.js","sourceRoot":"../src/","sources":["useAsync.ts"],"names":[],"mappings":";;AAMA,4BAYC;AAlBD,iDAA4C;AAC5C,6BAA+B;AAE/B;;GAEG;AACH,SAAgB,QAAQ;IACtB,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAQ,SAAS,CAAC,CAAC;IAChD,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;QACtB,QAAQ,CAAC,OAAO,GAAG,IAAI,iBAAK,EAAE,CAAC;IACjC,CAAC;IACD,KAAK,CAAC,SAAS,CAAC;QACd,OAAO;;YACL,MAAA,QAAQ,CAAC,OAAO,0CAAE,OAAO,EAAE,CAAC;YAC5B,QAAQ,CAAC,OAAO,GAAG,SAAS,CAAC;QAC/B,CAAC,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;IACP,OAAO,QAAQ,CAAC,OAAO,CAAC;AAC1B,CAAC","sourcesContent":["import { Async } from '@fluentui/utilities';\nimport * as React from 'react';\n\n/**\n * Hook to provide an Async instance that is automatically cleaned up on dismount.\n */\nexport function useAsync(): Async {\n const asyncRef = React.useRef<Async>(undefined);\n if (!asyncRef.current) {\n asyncRef.current = new Async();\n }\n React.useEffect(() => {\n return () => {\n asyncRef.current?.dispose();\n asyncRef.current = undefined;\n };\n }, []);\n return asyncRef.current;\n}\n"]}
+17
View File
@@ -0,0 +1,17 @@
/** Updater callbacks returned by `useBoolean`. */
export interface IUseBooleanCallbacks {
/** Set the value to true. Always has the same identity. */
setTrue: () => void;
/** Set the value to false. Always has the same identity. */
setFalse: () => void;
/** Toggle the value. Always has the same identity. */
toggle: () => void;
}
/**
* Hook to store a value and generate callbacks for setting the value to true or false.
* The identity of the callbacks will always stay the same.
*
* @param initialState - Initial value
* @returns Array with the current value and an object containing the updater callbacks.
*/
export declare function useBoolean(initialState: boolean): [boolean, IUseBooleanCallbacks];
+26
View File
@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useBoolean = useBoolean;
var React = require("react");
var useConst_1 = require("./useConst");
/**
* Hook to store a value and generate callbacks for setting the value to true or false.
* The identity of the callbacks will always stay the same.
*
* @param initialState - Initial value
* @returns Array with the current value and an object containing the updater callbacks.
*/
function useBoolean(initialState) {
var _a = React.useState(initialState), value = _a[0], setValue = _a[1];
var setTrue = (0, useConst_1.useConst)(function () { return function () {
setValue(true);
}; });
var setFalse = (0, useConst_1.useConst)(function () { return function () {
setValue(false);
}; });
var toggle = (0, useConst_1.useConst)(function () { return function () {
setValue(function (currentValue) { return !currentValue; });
}; });
return [value, { setTrue: setTrue, setFalse: setFalse, toggle: toggle }];
}
//# sourceMappingURL=useBoolean.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useBoolean.js","sourceRoot":"../src/","sources":["useBoolean.ts"],"names":[],"mappings":";;AAoBA,gCAcC;AAlCD,6BAA+B;AAC/B,uCAAsC;AAYtC;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,YAAqB;IACxC,IAAA,KAAoB,KAAK,CAAC,QAAQ,CAAC,YAAY,CAAC,EAA/C,KAAK,QAAA,EAAE,QAAQ,QAAgC,CAAC;IAEvD,IAAM,OAAO,GAAG,IAAA,mBAAQ,EAAC,cAAM,OAAA;QAC7B,QAAQ,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC,EAF8B,CAE9B,CAAC,CAAC;IACH,IAAM,QAAQ,GAAG,IAAA,mBAAQ,EAAC,cAAM,OAAA;QAC9B,QAAQ,CAAC,KAAK,CAAC,CAAC;IAClB,CAAC,EAF+B,CAE/B,CAAC,CAAC;IACH,IAAM,MAAM,GAAG,IAAA,mBAAQ,EAAC,cAAM,OAAA;QAC5B,QAAQ,CAAC,UAAA,YAAY,IAAI,OAAA,CAAC,YAAY,EAAb,CAAa,CAAC,CAAC;IAC1C,CAAC,EAF6B,CAE7B,CAAC,CAAC;IAEH,OAAO,CAAC,KAAK,EAAE,EAAE,OAAO,SAAA,EAAE,QAAQ,UAAA,EAAE,MAAM,QAAA,EAAE,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import * as React from 'react';\nimport { useConst } from './useConst';\n\n/** Updater callbacks returned by `useBoolean`. */\nexport interface IUseBooleanCallbacks {\n /** Set the value to true. Always has the same identity. */\n setTrue: () => void;\n /** Set the value to false. Always has the same identity. */\n setFalse: () => void;\n /** Toggle the value. Always has the same identity. */\n toggle: () => void;\n}\n\n/**\n * Hook to store a value and generate callbacks for setting the value to true or false.\n * The identity of the callbacks will always stay the same.\n *\n * @param initialState - Initial value\n * @returns Array with the current value and an object containing the updater callbacks.\n */\nexport function useBoolean(initialState: boolean): [boolean, IUseBooleanCallbacks] {\n const [value, setValue] = React.useState(initialState);\n\n const setTrue = useConst(() => () => {\n setValue(true);\n });\n const setFalse = useConst(() => () => {\n setValue(false);\n });\n const toggle = useConst(() => () => {\n setValue(currentValue => !currentValue);\n });\n\n return [value, { setTrue, setFalse, toggle }];\n}\n"]}
+12
View File
@@ -0,0 +1,12 @@
/**
* Hook to initialize and return a constant value. Unlike `React.useMemo`, this is guaranteed to
* always return the same value (and if the initializer is a function, only call it once).
* This is similar to setting a private member in a class constructor.
*
* If the value should ever change based on dependencies, use `React.useMemo` instead.
*
* @param initialValue - Initial value, or function to get the initial value. Similar to `useState`,
* only the value/function passed in the first time this is called is respected.
* @returns The value. The identity of this value will always be the same.
*/
export declare function useConst<T>(initialValue: T | (() => T)): T;
+30
View File
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useConst = useConst;
var React = require("react");
/**
* Hook to initialize and return a constant value. Unlike `React.useMemo`, this is guaranteed to
* always return the same value (and if the initializer is a function, only call it once).
* This is similar to setting a private member in a class constructor.
*
* If the value should ever change based on dependencies, use `React.useMemo` instead.
*
* @param initialValue - Initial value, or function to get the initial value. Similar to `useState`,
* only the value/function passed in the first time this is called is respected.
* @returns The value. The identity of this value will always be the same.
*/
function useConst(initialValue) {
// Use useRef to store the value because it's the least expensive built-in hook that works here
// (we could also use `const [value] = React.useState(initialValue)` but that's more expensive
// internally due to reducer handling which we don't need)
var ref = React.useRef(undefined);
if (ref.current === undefined) {
// Box the value in an object so we can tell if it's initialized even if the initializer
// returns/is undefined
ref.current = {
value: typeof initialValue === 'function' ? initialValue() : initialValue,
};
}
return ref.current.value;
}
//# sourceMappingURL=useConst.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"useConst.js","sourceRoot":"../src/","sources":["useConst.ts"],"names":[],"mappings":";;AAaA,4BAaC;AA1BD,6BAA+B;AAE/B;;;;;;;;;;GAUG;AACH,SAAgB,QAAQ,CAAI,YAA2B;IACrD,+FAA+F;IAC/F,8FAA8F;IAC9F,0DAA0D;IAC1D,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAe,SAAS,CAAC,CAAC;IAClD,IAAI,GAAG,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QAC9B,wFAAwF;QACxF,uBAAuB;QACvB,GAAG,CAAC,OAAO,GAAG;YACZ,KAAK,EAAE,OAAO,YAAY,KAAK,UAAU,CAAC,CAAC,CAAE,YAAyB,EAAE,CAAC,CAAC,CAAC,YAAY;SACxF,CAAC;IACJ,CAAC;IACD,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC;AAC3B,CAAC","sourcesContent":["import * as React from 'react';\n\n/**\n * Hook to initialize and return a constant value. Unlike `React.useMemo`, this is guaranteed to\n * always return the same value (and if the initializer is a function, only call it once).\n * This is similar to setting a private member in a class constructor.\n *\n * If the value should ever change based on dependencies, use `React.useMemo` instead.\n *\n * @param initialValue - Initial value, or function to get the initial value. Similar to `useState`,\n * only the value/function passed in the first time this is called is respected.\n * @returns The value. The identity of this value will always be the same.\n */\nexport function useConst<T>(initialValue: T | (() => T)): T {\n // Use useRef to store the value because it's the least expensive built-in hook that works here\n // (we could also use `const [value] = React.useState(initialValue)` but that's more expensive\n // internally due to reducer handling which we don't need)\n const ref = React.useRef<{ value: T }>(undefined);\n if (ref.current === undefined) {\n // Box the value in an object so we can tell if it's initialized even if the initializer\n // returns/is undefined\n ref.current = {\n value: typeof initialValue === 'function' ? (initialValue as Function)() : initialValue,\n };\n }\n return ref.current.value;\n}\n"]}
+11
View File
@@ -0,0 +1,11 @@
/**
* @deprecated Deprecated due to potential for misuse. Generally, use `React.useCallback` instead.
* If you need a callback reference that never changes, consider `useEventCallback`.
*
* This hook was intended for creating callbacks which have no dependencies, and therefore never
* need to change. It works fine if everyone using it is extremely mindful of how closures work,
* but that's not a safe assumption--so in practice, usage of this hook tends to result in bugs
* like unintentionally capturing the first value of a prop and not respecting updates (when
* updates should be respected).
*/
export declare function useConstCallback<T extends (...args: any[]) => any>(callback: T): T;
+23
View File
@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useConstCallback = useConstCallback;
var React = require("react");
/**
* @deprecated Deprecated due to potential for misuse. Generally, use `React.useCallback` instead.
* If you need a callback reference that never changes, consider `useEventCallback`.
*
* This hook was intended for creating callbacks which have no dependencies, and therefore never
* need to change. It works fine if everyone using it is extremely mindful of how closures work,
* but that's not a safe assumption--so in practice, usage of this hook tends to result in bugs
* like unintentionally capturing the first value of a prop and not respecting updates (when
* updates should be respected).
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function useConstCallback(callback) {
var ref = React.useRef(undefined);
if (!ref.current) {
ref.current = callback;
}
return ref.current;
}
//# sourceMappingURL=useConstCallback.js.map
@@ -0,0 +1 @@
{"version":3,"file":"useConstCallback.js","sourceRoot":"../src/","sources":["useConstCallback.ts"],"names":[],"mappings":";;AAaA,4CAMC;AAnBD,6BAA+B;AAE/B;;;;;;;;;GASG;AACH,8DAA8D;AAC9D,SAAgB,gBAAgB,CAAoC,QAAW;IAC7E,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAI,SAAS,CAAC,CAAC;IACvC,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC;QACjB,GAAG,CAAC,OAAO,GAAG,QAAQ,CAAC;IACzB,CAAC;IACD,OAAO,GAAG,CAAC,OAAO,CAAC;AACrB,CAAC","sourcesContent":["import * as React from 'react';\n\n/**\n * @deprecated Deprecated due to potential for misuse. Generally, use `React.useCallback` instead.\n * If you need a callback reference that never changes, consider `useEventCallback`.\n *\n * This hook was intended for creating callbacks which have no dependencies, and therefore never\n * need to change. It works fine if everyone using it is extremely mindful of how closures work,\n * but that's not a safe assumption--so in practice, usage of this hook tends to result in bugs\n * like unintentionally capturing the first value of a prop and not respecting updates (when\n * updates should be respected).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function useConstCallback<T extends (...args: any[]) => any>(callback: T): T {\n const ref = React.useRef<T>(undefined);\n if (!ref.current) {\n ref.current = callback;\n }\n return ref.current;\n}\n"]}
@@ -0,0 +1,18 @@
import * as React from 'react';
export type ChangeCallback<TElement extends HTMLElement, TValue, TEvent extends React.SyntheticEvent<TElement> | undefined> = (ev: TEvent, newValue: TValue | undefined) => void;
/**
* Hook to manage a value that could be either controlled or uncontrolled, such as a checked state or
* text box string.
* @param controlledValue - The controlled value passed in the props. This value will always be used if provided,
* and the internal state will be updated to reflect it.
* @param defaultUncontrolledValue - Initial value for the internal state in the uncontrolled case.
* @returns An array of the current value and an updater callback. Like `React.useState`, the updater
* callback always has the same identity, and it can take either a new value, or a function which
* is passed the previous value and returns the new value.
* @see https://reactjs.org/docs/uncontrolled-components.html
*/
export declare function useControllableValue<TValue, TElement extends HTMLElement>(controlledValue: TValue | undefined, defaultUncontrolledValue: TValue | undefined): Readonly<[TValue | undefined, (update: React.SetStateAction<TValue | undefined>) => void]>;
export declare function useControllableValue<TValue, TElement extends HTMLElement, TEvent extends React.SyntheticEvent<TElement> | undefined>(controlledValue: TValue | undefined, defaultUncontrolledValue: TValue | undefined, onChange: ChangeCallback<TElement, TValue, TEvent> | undefined): Readonly<[
TValue | undefined,
(update: React.SetStateAction<TValue | undefined>, ev?: React.FormEvent<TElement>) => void
]>;
@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useControllableValue = useControllableValue;
var React = require("react");
var useConst_1 = require("./useConst");
function useControllableValue(controlledValue, defaultUncontrolledValue, onChange) {
var _a = React.useState(defaultUncontrolledValue), value = _a[0], setValue = _a[1];
var isControlled = (0, useConst_1.useConst)(controlledValue !== undefined);
var currentValue = isControlled ? controlledValue : value;
// Duplicate the current value and onChange in refs so they're accessible from
// setValueOrCallOnChange without creating a new callback every time
var valueRef = React.useRef(currentValue);
var onChangeRef = React.useRef(onChange);
React.useEffect(function () {
valueRef.current = currentValue;
onChangeRef.current = onChange;
});
// To match the behavior of the setter returned by React.useState, this callback's identity
// should never change. This means it MUST NOT directly reference variables that can change.
var setValueOrCallOnChange = (0, useConst_1.useConst)(function () { return function (update, ev) {
// Assuming here that TValue is not a function, because a controllable value will typically
// be something a user can enter as input
var newValue = typeof update === 'function' ? update(valueRef.current) : update;
if (onChangeRef.current) {
onChangeRef.current(ev, newValue);
}
if (!isControlled) {
setValue(newValue);
}
}; });
return [currentValue, setValueOrCallOnChange];
}
//# sourceMappingURL=useControllableValue.js.map
@@ -0,0 +1 @@
{"version":3,"file":"useControllableValue.js","sourceRoot":"../src/","sources":["useControllableValue.ts"],"names":[],"mappings":";;AAmCA,oDAuCC;AA1ED,6BAA+B;AAC/B,uCAAsC;AAkCtC,SAAgB,oBAAoB,CAKlC,eAAmC,EACnC,wBAA4C,EAC5C,QAAmD;IAE7C,IAAA,KAAoB,KAAK,CAAC,QAAQ,CAAqB,wBAAwB,CAAC,EAA/E,KAAK,QAAA,EAAE,QAAQ,QAAgE,CAAC;IACvF,IAAM,YAAY,GAAG,IAAA,mBAAQ,EAAU,eAAe,KAAK,SAAS,CAAC,CAAC;IACtE,IAAM,YAAY,GAAG,YAAY,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC;IAE5D,8EAA8E;IAC9E,oEAAoE;IACpE,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IAC5C,IAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC3C,KAAK,CAAC,SAAS,CAAC;QACd,QAAQ,CAAC,OAAO,GAAG,YAAY,CAAC;QAChC,WAAW,CAAC,OAAO,GAAG,QAAQ,CAAC;IACjC,CAAC,CAAC,CAAC;IAEH,2FAA2F;IAC3F,4FAA4F;IAC5F,IAAM,sBAAsB,GAAG,IAAA,mBAAQ,EAAC,cAAM,OAAA,UAAC,MAAgD,EAAE,EAAW;QAC1G,2FAA2F;QAC3F,yCAAyC;QACzC,IAAM,QAAQ,GAAG,OAAO,MAAM,KAAK,UAAU,CAAC,CAAC,CAAE,MAAmB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;QAEhG,IAAI,WAAW,CAAC,OAAO,EAAE,CAAC;YACxB,WAAW,CAAC,OAAO,CAAC,EAAG,EAAE,QAAQ,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACrB,CAAC;IACH,CAAC,EAZ6C,CAY7C,CAAC,CAAC;IAEH,OAAO,CAAC,YAAY,EAAE,sBAAsB,CAAU,CAAC;AACzD,CAAC","sourcesContent":["import * as React from 'react';\nimport { useConst } from './useConst';\n\nexport type ChangeCallback<\n TElement extends HTMLElement,\n TValue,\n TEvent extends React.SyntheticEvent<TElement> | undefined,\n> = (ev: TEvent, newValue: TValue | undefined) => void;\n\n/**\n * Hook to manage a value that could be either controlled or uncontrolled, such as a checked state or\n * text box string.\n * @param controlledValue - The controlled value passed in the props. This value will always be used if provided,\n * and the internal state will be updated to reflect it.\n * @param defaultUncontrolledValue - Initial value for the internal state in the uncontrolled case.\n * @returns An array of the current value and an updater callback. Like `React.useState`, the updater\n * callback always has the same identity, and it can take either a new value, or a function which\n * is passed the previous value and returns the new value.\n * @see https://reactjs.org/docs/uncontrolled-components.html\n */\nexport function useControllableValue<TValue, TElement extends HTMLElement>(\n controlledValue: TValue | undefined,\n defaultUncontrolledValue: TValue | undefined,\n): Readonly<[TValue | undefined, (update: React.SetStateAction<TValue | undefined>) => void]>;\nexport function useControllableValue<\n TValue,\n TElement extends HTMLElement,\n TEvent extends React.SyntheticEvent<TElement> | undefined,\n>(\n controlledValue: TValue | undefined,\n defaultUncontrolledValue: TValue | undefined,\n onChange: ChangeCallback<TElement, TValue, TEvent> | undefined,\n): Readonly<\n [TValue | undefined, (update: React.SetStateAction<TValue | undefined>, ev?: React.FormEvent<TElement>) => void]\n>;\nexport function useControllableValue<\n TValue,\n TElement extends HTMLElement,\n TEvent extends React.SyntheticEvent<TElement> | undefined,\n>(\n controlledValue: TValue | undefined,\n defaultUncontrolledValue: TValue | undefined,\n onChange?: ChangeCallback<TElement, TValue, TEvent>,\n) {\n const [value, setValue] = React.useState<TValue | undefined>(defaultUncontrolledValue);\n const isControlled = useConst<boolean>(controlledValue !== undefined);\n const currentValue = isControlled ? controlledValue : value;\n\n // Duplicate the current value and onChange in refs so they're accessible from\n // setValueOrCallOnChange without creating a new callback every time\n const valueRef = React.useRef(currentValue);\n const onChangeRef = React.useRef(onChange);\n React.useEffect(() => {\n valueRef.current = currentValue;\n onChangeRef.current = onChange;\n });\n\n // To match the behavior of the setter returned by React.useState, this callback's identity\n // should never change. This means it MUST NOT directly reference variables that can change.\n const setValueOrCallOnChange = useConst(() => (update: React.SetStateAction<TValue | undefined>, ev?: TEvent) => {\n // Assuming here that TValue is not a function, because a controllable value will typically\n // be something a user can enter as input\n const newValue = typeof update === 'function' ? (update as Function)(valueRef.current) : update;\n\n if (onChangeRef.current) {\n onChangeRef.current(ev!, newValue);\n }\n\n if (!isControlled) {\n setValue(newValue);\n }\n });\n\n return [currentValue, setValueOrCallOnChange] as const;\n}\n"]}
+16
View File
@@ -0,0 +1,16 @@
/**
* Modified `useCallback` that returns the same function reference every time, but internally calls
* the most-recently passed callback implementation. Can be useful in situations such as:
* - Event handler dependencies change too frequently, such as user props which might change on
* every render, or volatile values such as useState/useDispatch
* - Callback must be referenced in a captured context (such as a window event handler or unmount
* handler that's registered once) but needs access to the latest props
*
* In general, prefer `useCallback` unless you've encountered one of the problems above.
*
* https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
*
* @param fn - The callback function that will be used
* @returns A function which is referentially stable but internally calls the most recently passed callback
*/
export declare function useEventCallback<Args extends unknown[], Return>(fn: (...args: Args) => Return): (...args: Args) => Return;
+40
View File
@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useEventCallback = useEventCallback;
var React = require("react");
var useConst_1 = require("./useConst");
var utilities_1 = require("@fluentui/utilities");
/**
* Modified `useCallback` that returns the same function reference every time, but internally calls
* the most-recently passed callback implementation. Can be useful in situations such as:
* - Event handler dependencies change too frequently, such as user props which might change on
* every render, or volatile values such as useState/useDispatch
* - Callback must be referenced in a captured context (such as a window event handler or unmount
* handler that's registered once) but needs access to the latest props
*
* In general, prefer `useCallback` unless you've encountered one of the problems above.
*
* https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
*
* @param fn - The callback function that will be used
* @returns A function which is referentially stable but internally calls the most recently passed callback
*/
function useEventCallback(fn) {
var callbackRef = React.useRef(function () {
throw new Error('Cannot call an event handler while rendering');
});
(0, utilities_1.useIsomorphicLayoutEffect)(function () {
callbackRef.current = fn;
}, [fn]);
// useConst rather than useCallback to ensure the reference is always stable
// (useCallback's deps list is an optimization, not a guarantee)
return (0, useConst_1.useConst)(function () { return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var callback = callbackRef.current;
return callback.apply(void 0, args);
}; });
}
//# sourceMappingURL=useEventCallback.js.map

Some files were not shown because too many files have changed in this diff Show More