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
+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
@@ -0,0 +1 @@
{"version":3,"file":"useEventCallback.js","sourceRoot":"../src/","sources":["useEventCallback.ts"],"names":[],"mappings":";;AAmBA,4CAiBC;AApCD,6BAA+B;AAC/B,uCAAsC;AACtC,iDAAgE;AAEhE;;;;;;;;;;;;;;GAcG;AACH,SAAgB,gBAAgB,CAC9B,EAA6B;IAE7B,IAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAY;QAC1C,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAClE,CAAC,CAAC,CAAC;IAEH,IAAA,qCAAyB,EAAC;QACxB,WAAW,CAAC,OAAO,GAAG,EAAE,CAAC;IAC3B,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAET,4EAA4E;IAC5E,gEAAgE;IAChE,OAAO,IAAA,mBAAQ,EAAC,cAAM,OAAA;QAAC,cAAa;aAAb,UAAa,EAAb,qBAAa,EAAb,IAAa;YAAb,yBAAa;;QAClC,IAAM,QAAQ,GAAG,WAAW,CAAC,OAAO,CAAC;QACrC,OAAO,QAAQ,eAAI,IAAI,EAAE;IAC3B,CAAC,EAHqB,CAGrB,CAAC,CAAC;AACL,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 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useForceUpdate = useForceUpdate;
var React = require("react");
var useConst_1 = require("./useConst");
/**
* 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
@@ -0,0 +1 @@
{"version":3,"file":"useForceUpdate.js","sourceRoot":"../src/","sources":["useForceUpdate.ts"],"names":[],"mappings":";;AAMA,wCAIC;AAVD,6BAA+B;AAC/B,uCAAsC;AAEtC;;GAEG;AACH,SAAgB,cAAc;IACtB,IAAA,KAAe,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,EAA7B,QAAQ,QAAqB,CAAC;IACvC,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;IACrE,OAAO,WAAW,CAAC;AACrB,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 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useId = useId;
var React = require("react");
var utilities_1 = require("@fluentui/utilities");
/**
* 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":";;AAWA,sBAQC;AAnBD,6BAA+B;AAC/B,iDAA4C;AAE5C;;;;;;;GAOG;AACH,SAAgB,KAAK,CAAC,MAAe,EAAE,UAAmB;IACxD,+FAA+F;IAC/F,+FAA+F;IAC/F,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAqB,UAAU,CAAC,CAAC;IACzD,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,CAAC;QACjB,GAAG,CAAC,OAAO,GAAG,IAAA,iBAAK,EAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,GAAG,CAAC,OAAO,CAAC;AACrB,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 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMergedRefs = useMergedRefs;
var tslib_1 = require("tslib");
var React = require("react");
/**
* 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":";;AAcA,sCAsBC;;AApCD,6BAA+B;AAQ/B;;;;;GAKG;AACH,SAAgB,aAAa;IAAI,cAAqC;SAArC,UAAqC,EAArC,qBAAqC,EAArC,IAAqC;QAArC,yBAAqC;;IACpE,IAAM,cAAc,GAAyB,KAAK,CAAC,WAAW,CAC5D,UAAC,KAAQ;QACP,qDAAqD;QACrD,4DAA4D;QAC3D,cAAuD,CAAC,OAAO,GAAG,KAAK,CAAC;QAEzE,KAAkB,UAAI,EAAJ,aAAI,EAAJ,kBAAI,EAAJ,IAAI,EAAE,CAAC;YAApB,IAAM,GAAG,aAAA;YACZ,IAAI,OAAO,GAAG,KAAK,UAAU,EAAE,CAAC;gBAC9B,GAAG,CAAC,KAAK,CAAC,CAAC;YACb,CAAC;iBAAM,IAAI,GAAG,EAAE,CAAC;gBACf,qDAAqD;gBACrD,4DAA4D;gBAC3D,GAA4C,CAAC,OAAO,GAAG,KAAK,CAAC;YAChE,CAAC;QACH,CAAC;IACH,CAAC,4BAEG,IAAI,QAC0B,CAAC;IAErC,OAAO,cAAc,CAAC;AACxB,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;
+19
View File
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMount = void 0;
var React = require("react");
/**
* 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":";;;AAAA,6BAA+B;AAE/B;;;;GAIG;AACI,IAAM,QAAQ,GAAG,UAAC,QAAoB;IAC3C,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACxC,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;IAC5B,KAAK,CAAC,SAAS,CAAC;;QACd,MAAA,QAAQ,CAAC,OAAO,wDAAI,CAAC;IACvB,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC,CAAC;AANW,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;
+26
View File
@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useMountSync = void 0;
var React = require("react");
/**
* 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":";;;AAAA,6BAA+B;AAE/B;;;;;;;;;;GAUG;AACI,IAAM,YAAY,GAAG,UAAC,QAAoB;IAC/C,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACxC,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;IAC5B,oDAAoD;IACpD,KAAK,CAAC,eAAe,CAAC;;QACpB,MAAA,QAAQ,CAAC,OAAO,wDAAI,CAAC;IACvB,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC,CAAC;AAPW,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 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useOnEvent = useOnEvent;
var utilities_1 = require("@fluentui/utilities");
var React = require("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
*/
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":";;AAUA,gCAmBC;AA7BD,iDAAyC;AACzC,6BAA+B;AAE/B;;;;;;GAMG;AACH,SAAgB,UAAU,CACxB,OAAuG,EACvG,SAAiB,EACjB,QAA8B,EAC9B,UAAoB;IAEpB,oHAAoH;IACpH,IAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC3C,WAAW,CAAC,OAAO,GAAG,QAAQ,CAAC;IAE/B,KAAK,CAAC,SAAS,CAAC;QACd,IAAM,aAAa,GAAG,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC;QAClF,IAAI,CAAC,aAAa,IAAI,CAAC,aAAa,CAAC,gBAAgB,EAAE,CAAC;YACtD,OAAO;QACT,CAAC;QAED,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;QAClG,OAAO,OAAO,CAAC;IACjB,CAAC,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC;AACvC,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;
+17
View File
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.usePrevious = usePrevious;
var React = require("react");
/**
* 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":";;AAMA,kCAMC;AAZD,6BAA+B;AAC/B;;;;GAIG;AACH,SAAgB,WAAW,CAAI,KAAQ;IACrC,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAgB,SAAS,CAAC,CAAC;IACnD,KAAK,CAAC,SAAS,CAAC;QACd,GAAG,CAAC,OAAO,GAAG,KAAK,CAAC;IACtB,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC,OAAO,CAAC;AACrB,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>;
+54
View File
@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useRefEffect = useRefEffect;
var React = require("react");
/**
* 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":";;AA+BA,oCAoCC;AAnED,6BAA+B;AAO/B;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,SAAgB,YAAY,CAAI,QAA2C,EAAE,OAAwB;IAAxB,wBAAA,EAAA,cAAwB;IAQnG,IAAM,iBAAiB,GAAG;QACxB,IAAM,WAAW,GAAG,UAAC,KAAe;YAClC,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,KAAK,KAAK,EAAE,CAAC;gBAC/B,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;oBACjB,IAAI,CAAC,OAAO,EAAE,CAAC;oBACf,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;gBAC3B,CAAC;gBAED,IAAI,CAAC,GAAG,CAAC,OAAO,GAAG,KAAK,CAAC;gBAEzB,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;oBACnB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;gBACtC,CAAC;YACH,CAAC;QACH,CAAC,CAAC;QAEF,WAAW,CAAC,OAAO,GAAG,OAAO,CAAC;QAC9B,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC;IAEF,IAAM,IAAI,GAAG,KAAK,CAAC,MAAM,CAAU;QACjC,GAAG,EAAE,iBAAiB,EAAE;QACxB,QAAQ,UAAA;KACT,CAAC,CAAC,OAAO,CAAC;IAEX,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAEzB,OAAO,IAAI,CAAC,GAAG,CAAC;AAClB,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 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSetInterval = void 0;
var React = require("react");
var useConst_1 = require("./useConst");
/**
* 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
@@ -0,0 +1 @@
{"version":3,"file":"useSetInterval.js","sourceRoot":"../src/","sources":["useSetInterval.ts"],"names":[],"mappings":";;;AAAA,6BAA+B;AAC/B,uCAAsC;AAOtC;;GAEG;AACI,IAAM,cAAc,GAAG;IAC5B,IAAM,WAAW,GAAG,IAAA,mBAAQ,EAAyB,EAAE,CAAC,CAAC;IAEzD,KAAK,CAAC,SAAS,CACb,cAAM,OAAA;QACJ,KAAiB,UAAwB,EAAxB,KAAA,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,EAAxB,cAAwB,EAAxB,IAAwB,EAAE,CAAC;YAAvC,IAAM,EAAE,SAAA;YACX,8DAA8D;YAC9D,aAAa,CAAC,EAAS,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC,EALK,CAKL;IACD,6FAA6F;IAC7F,CAAC,WAAW,CAAC,CACd,CAAC;IAEF,OAAO,IAAA,mBAAQ,EAAC;QACd,WAAW,EAAE,UAAC,IAAgB,EAAE,QAAgB;YAC9C,IAAM,EAAE,GAAG,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAsB,CAAC;YAE5D,WAAW,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;YAEpB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,aAAa,EAAE,UAAC,EAAU;YACxB,OAAO,WAAW,CAAC,EAAE,CAAC,CAAC;YACvB,aAAa,CAAC,EAAE,CAAC,CAAC;QACpB,CAAC;KACF,CAAC,CAAC;AACL,CAAC,CAAC;AA5BW,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 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSetTimeout = void 0;
var React = require("react");
var useConst_1 = require("./useConst");
/**
* 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":";;;AAAA,6BAA+B;AAC/B,uCAAsC;AAOtC;;GAEG;AACI,IAAM,aAAa,GAAG;IAC3B,IAAM,UAAU,GAAG,IAAA,mBAAQ,EAAyB,EAAE,CAAC,CAAC;IAExD,oBAAoB;IACpB,KAAK,CAAC,SAAS,CACb,cAAM,OAAA;QACJ,KAAiB,UAAuB,EAAvB,KAAA,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,EAAvB,cAAuB,EAAvB,IAAuB,EAAE,CAAC;YAAtC,IAAM,EAAE,SAAA;YACX,8DAA8D;YAC9D,YAAY,CAAC,EAAS,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC,EALK,CAKL;IACD,6FAA6F;IAC7F,CAAC,UAAU,CAAC,CACb,CAAC;IAEF,0CAA0C;IAC1C,OAAO,IAAA,mBAAQ,EAAC;QACd,UAAU,EAAE,UAAC,IAAgB,EAAE,QAAgB;YAC7C,IAAM,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,QAAQ,CAAsB,CAAC;YAE3D,UAAU,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;YAEnB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,YAAY,EAAE,UAAC,EAAU;YACvB,OAAO,UAAU,CAAC,EAAE,CAAC,CAAC;YACtB,YAAY,CAAC,EAAE,CAAC,CAAC;QACnB,CAAC;KACF,CAAC,CAAC;AACL,CAAC,CAAC;AA9BW,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]>;
+56
View File
@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTarget = useTarget;
var utilities_1 = require("@fluentui/utilities");
var React = require("react");
var react_window_provider_1 = require("@fluentui/react-window-provider");
/**
* 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":";;AAcA,8BA2CC;AAzDD,iDAA6D;AAC7D,6BAA+B;AAC/B,yEAA4D;AAK5D;;;;;;GAMG;AACH,SAAgB,SAAS,CACvB,MAA0B,EAC1B,WAA8C;;IAE9C,IAAM,kBAAkB,GAAG,KAAK,CAAC,MAAM,CAErC,SAAS,CAAC,CAAC;IAEb,IAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAkD,IAAI,CAAC,CAAC;IACtF;;;OAGG;IACH,IAAM,YAAY,GAAG,IAAA,iCAAS,GAAE,CAAC;IAEjC,sEAAsE;IACtE,wEAAwE;IACxE,kEAAkE;IAClE,IAAI,CAAC,MAAM,IAAI,MAAM,KAAK,kBAAkB,CAAC,OAAO,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QACnF,IAAM,cAAc,GAAG,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAC;QAC5C,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;gBAC/B,8FAA8F;gBAC9F,IAAI,MAAC,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,WAAW,EAAiB,0CAAE,IAAI,EAAE,CAAC;oBACxD,SAAS,CAAC,OAAO,GAAG,MAAA,MAAC,cAAc,aAAd,cAAc,uBAAd,cAAc,CAAE,WAAW,EAAiB,0CAAE,aAAa,CAAC,MAAM,CAAC,mCAAI,IAAI,CAAC;gBACnG,CAAC;qBAAM,CAAC;oBACN,IAAM,UAAU,GAAa,IAAA,uBAAW,EAAC,cAAc,CAAE,CAAC;oBAC1D,SAAS,CAAC,OAAO,GAAG,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;gBAC3E,CAAC;YACH,CAAC;iBAAM,IAAI,iBAAiB,IAAI,MAAM,EAAE,CAAC;gBACvC,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC;YAC7B,CAAC;iBAAM,IAAI,uBAAuB,IAAI,MAAM,EAAE,CAAC;gBAC7C,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC;YAC7B,CAAC;iBAAM,IAAI,SAAS,IAAI,MAAM,EAAE,CAAC;gBAC/B,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;YACrC,CAAC;iBAAM,CAAC;gBACN,SAAS,CAAC,OAAO,GAAG,MAAM,CAAC;YAC7B,CAAC;QACH,CAAC;QACD,kBAAkB,CAAC,OAAO,GAAG,MAAM,CAAC;IACtC,CAAC;IAED,OAAO,CAAC,SAAS,EAAE,YAAY,CAAU,CAAC;AAC5C,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;
+19
View File
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useUnmount = void 0;
var React = require("react");
/**
* 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":";;;AAAA,6BAA+B;AAE/B;;;;GAIG;AACI,IAAM,UAAU,GAAG,UAAC,QAAoB;IAC7C,IAAM,UAAU,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC1C,UAAU,CAAC,OAAO,GAAG,QAAQ,CAAC;IAC9B,KAAK,CAAC,SAAS,CACb,cAAM,OAAA;;QACJ,MAAA,UAAU,CAAC,OAAO,0DAAI,CAAC;IACzB,CAAC,EAFK,CAEL,EACD,EAAE,CACH,CAAC;AACJ,CAAC,CAAC;AATW,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;
+46
View File
@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useWarnings = useWarnings;
var tslib_1 = require("tslib");
var React = require("react");
var utilities_1 = require("@fluentui/utilities");
var usePrevious_1 = require("./usePrevious");
var useConst_1 = require("./useConst");
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) {
if (process.env.NODE_ENV !== 'production') {
var name_1 = options.name, props = options.props, _a = options.other, other = _a === void 0 ? [] : _a, conditionallyRequired = options.conditionallyRequired, deprecations = options.deprecations, mutuallyExclusive = options.mutuallyExclusive, controlledUsage = options.controlledUsage;
/* eslint-disable react-hooks/rules-of-hooks -- build-time conditional */
var hasWarnedRef = React.useRef(false);
var componentId = (0, useConst_1.useConst)(function () { return "useWarnings_".concat(warningId++); });
var oldProps = (0, usePrevious_1.usePrevious)(props);
/* eslint-enable react-hooks/rules-of-hooks */
// Warn synchronously (not in useEffect) on first render to make debugging easier.
if (!hasWarnedRef.current) {
hasWarnedRef.current = true;
for (var _i = 0, other_1 = other; _i < other_1.length; _i++) {
var warning = other_1[_i];
(0, utilities_1.warn)(warning);
}
if (conditionallyRequired) {
for (var _b = 0, conditionallyRequired_1 = conditionallyRequired; _b < conditionallyRequired_1.length; _b++) {
var req = conditionallyRequired_1[_b];
(0, utilities_1.warnConditionallyRequiredProps)(name_1, props, req.requiredProps, req.conditionalPropName, req.condition);
}
}
deprecations && (0, utilities_1.warnDeprecations)(name_1, props, deprecations);
mutuallyExclusive && (0, utilities_1.warnMutuallyExclusive)(name_1, props, mutuallyExclusive);
}
// Controlled usage warnings may be displayed on either first or subsequent renders due to
// prop changes. Note that it's safe to run this synchronously (not in useEffect) even in
// concurrent mode because `warnControlledUsage` internally tracks which warnings have been
// displayed for each component instance (so nothing will be displayed twice).
controlledUsage && (0, utilities_1.warnControlledUsage)(tslib_1.__assign(tslib_1.__assign({}, controlledUsage), { componentId: componentId, props: props, componentName: name_1, oldProps: oldProps }));
}
}
//# sourceMappingURL=useWarnings.js.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
export {};
+7
View File
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// Do not modify this file; it is generated as part of publish.
// The checked in version is a placeholder only and will not be updated.
var set_version_1 = require("@fluentui/set-version");
(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":";;AAAA,+DAA+D;AAC/D,wEAAwE;AACxE,qDAAmD;AACnD,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');"]}